revert previous push
[autoconf.git] / doc / autoconf.texi
blob3528f53251052900c4f6e38ad12ff032ac381b0d
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.3 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 * Parallel Make::               Parallel @command{make} quirks
513 * Comments in Make Rules::      Other problems with Make comments
514 * obj/ and Make::               Don't name a subdirectory @file{obj}
515 * make -k Status::              Exit status of @samp{make -k}
516 * VPATH and Make::              @code{VPATH} woes
517 * Single Suffix Rules::         Single suffix rules and separated dependencies
518 * Timestamps and Make::         Subsecond timestamp resolution
520 @code{VPATH} and Make
522 * Variables listed in VPATH::   @code{VPATH} must be literal on ancient hosts
523 * VPATH and Double-colon::      Problems with @samp{::} on ancient hosts
524 * $< in Explicit Rules::        @code{$<} does not work in ordinary rules
525 * Automatic Rule Rewriting::    @code{VPATH} goes wild on Solaris
526 * Tru64 Directory Magic::       @command{mkdir} goes wild on Tru64
527 * Make Target Lookup::          More details about @code{VPATH} lookup
529 Portable C and C++ Programming
531 * Varieties of Unportability::  How to make your programs unportable
532 * Integer Overflow::            When integers get too large
533 * Preprocessor Arithmetic::     @code{#if} expression problems
534 * Null Pointers::               Properties of null pointers
535 * Buffer Overruns::             Subscript errors and the like
536 * Volatile Objects::            @code{volatile} and signals
537 * Floating Point Portability::  Portable floating-point arithmetic
538 * Exiting Portably::            Exiting and the exit status
540 Manual Configuration
542 * Specifying Target Triplets::  Specifying target triplets
543 * Canonicalizing::              Getting the canonical system type
544 * Using System Type::           What to do with the system type
546 Site Configuration
548 * Help Formatting::             Customizing @samp{configure --help}
549 * External Software::           Working with other optional software
550 * Package Options::             Selecting optional features
551 * Pretty Help Strings::         Formatting help string
552 * Option Checking::             Controlling checking of @command{configure} options
553 * Site Details::                Configuring site details
554 * Transforming Names::          Changing program names when installing
555 * Site Defaults::               Giving @command{configure} local defaults
557 Transforming Program Names When Installing
559 * Transformation Options::      @command{configure} options to transform names
560 * Transformation Examples::     Sample uses of transforming names
561 * Transformation Rules::        Makefile uses of transforming names
563 Running @command{configure} Scripts
565 * Basic Installation::          Instructions for typical cases
566 * Compilers and Options::       Selecting compilers and optimization
567 * Multiple Architectures::      Compiling for multiple architectures at once
568 * Installation Names::          Installing in different directories
569 * Optional Features::           Selecting optional features
570 * Particular Systems::          Particular systems
571 * System Type::                 Specifying the system type
572 * Sharing Defaults::            Setting site-wide defaults for @command{configure}
573 * Defining Variables::          Specifying the compiler etc.
574 * configure Invocation::        Changing how @command{configure} runs
576 Obsolete Constructs
578 * Obsolete config.status Use::  Obsolete convention for @command{config.status}
579 * acconfig Header::             Additional entries in @file{config.h.in}
580 * autoupdate Invocation::       Automatic update of @file{configure.ac}
581 * Obsolete Macros::             Backward compatibility macros
582 * Autoconf 1::                  Tips for upgrading your files
583 * Autoconf 2.13::               Some fresher tips
585 Upgrading From Version 1
587 * Changed File Names::          Files you might rename
588 * Changed Makefiles::           New things to put in @file{Makefile.in}
589 * Changed Macros::              Macro calls you might replace
590 * Changed Results::             Changes in how to check test results
591 * Changed Macro Writing::       Better ways to write your own macros
593 Upgrading From Version 2.13
595 * Changed Quotation::           Broken code which used to work
596 * New Macros::                  Interaction with foreign macros
597 * Hosts and Cross-Compilation::  Bugward compatibility kludges
598 * AC_LIBOBJ vs LIBOBJS::        LIBOBJS is a forbidden token
599 * AC_ACT_IFELSE vs AC_TRY_ACT::  A more generic scheme for testing sources
601 Generating Test Suites with Autotest
603 * Using an Autotest Test Suite::  Autotest and the user
604 * Writing Testsuites::          Autotest macros
605 * testsuite Invocation::        Running @command{testsuite} scripts
606 * Making testsuite Scripts::    Using autom4te to create @command{testsuite}
608 Using an Autotest Test Suite
610 * testsuite Scripts::           The concepts of Autotest
611 * Autotest Logs::               Their contents
613 Frequent Autoconf Questions, with answers
615 * Distributing::                Distributing @command{configure} scripts
616 * Why GNU M4::                  Why not use the standard M4?
617 * Bootstrapping::               Autoconf and @acronym{GNU} M4 require each other?
618 * Why Not Imake::               Why @acronym{GNU} uses @command{configure} instead of Imake
619 * Defining Directories::        Passing @code{datadir} to program
620 * Autom4te Cache::              What is it?  Can I remove it?
621 * Present But Cannot Be Compiled::  Compiler and Preprocessor Disagree
622 * Expanded Before Required::    Expanded Before Required
624 History of Autoconf
626 * Genesis::                     Prehistory and naming of @command{configure}
627 * Exodus::                      The plagues of M4 and Perl
628 * Leviticus::                   The priestly code of portability arrives
629 * Numbers::                     Growth and contributors
630 * Deuteronomy::                 Approaching the promises of easy configuration
632 Indices
634 * Environment Variable Index::  Index of environment variables used
635 * Output Variable Index::       Index of variables set in output files
636 * Preprocessor Symbol Index::   Index of C preprocessor symbols defined
637 * Autoconf Macro Index::        Index of Autoconf macros
638 * M4 Macro Index::              Index of M4, M4sugar, and M4sh macros
639 * Autotest Macro Index::        Index of Autotest macros
640 * Program & Function Index::    Index of those with portability problems
641 * Concept Index::               General index
643 @end detailmenu
644 @end menu
646 @c ============================================================= Introduction.
648 @node Introduction
649 @chapter Introduction
650 @cindex Introduction
652 @flushright
653 A physicist, an engineer, and a computer scientist were discussing the
654 nature of God.  ``Surely a Physicist,'' said the physicist, ``because
655 early in the Creation, God made Light; and you know, Maxwell's
656 equations, the dual nature of electromagnetic waves, the relativistic
657 consequences@enddots{}'' ``An Engineer!,'' said the engineer, ``because
658 before making Light, God split the Chaos into Land and Water; it takes a
659 hell of an engineer to handle that big amount of mud, and orderly
660 separation of solids from liquids@enddots{}'' The computer scientist
661 shouted: ``And the Chaos, where do you think it was coming from, hmm?''
663 ---Anonymous
664 @end flushright
665 @c (via Franc,ois Pinard)
667 Autoconf is a tool for producing shell scripts that automatically
668 configure software source code packages to adapt to many kinds of
669 Posix-like systems.  The configuration scripts produced by Autoconf
670 are independent of Autoconf when they are run, so their users do not
671 need to have Autoconf.
673 The configuration scripts produced by Autoconf require no manual user
674 intervention when run; they do not normally even need an argument
675 specifying the system type.  Instead, they individually test for the
676 presence of each feature that the software package they are for might need.
677 (Before each check, they print a one-line message stating what they are
678 checking for, so the user doesn't get too bored while waiting for the
679 script to finish.)  As a result, they deal well with systems that are
680 hybrids or customized from the more common Posix variants.  There is
681 no need to maintain files that list the features supported by each
682 release of each variant of Posix.
684 For each software package that Autoconf is used with, it creates a
685 configuration script from a template file that lists the system features
686 that the package needs or can use.  After the shell code to recognize
687 and respond to a system feature has been written, Autoconf allows it to
688 be shared by many software packages that can use (or need) that feature.
689 If it later turns out that the shell code needs adjustment for some
690 reason, it needs to be changed in only one place; all of the
691 configuration scripts can be regenerated automatically to take advantage
692 of the updated code.
694 @c "Those who do not understand Unix are condemned to reinvent it, poorly."
695 @c --Henry Spencer, 1987 (see http://en.wikipedia.org/wiki/Unix_philosophy)
696 Those who do not understand Autoconf are condemned to reinvent it, poorly.
697 The primary goal of Autoconf is making the @emph{user's} life easier;
698 making the @emph{maintainer's} life easier is only a secondary goal.
699 Put another way, the primary goal is not to make the generation of
700 @file{configure} automatic for package maintainers (although patches
701 along that front are welcome, since package maintainers form the user
702 base of Autoconf); rather, the goal is to make @file{configure}
703 painless, portable, and predictable for the end user of each
704 @dfn{autoconfiscated} package.  And to this degree, Autoconf is highly
705 successful at its goal --- most complaints to the Autoconf list are
706 about difficulties in writing Autoconf input, and not in the behavior of
707 the resulting @file{configure}.  Even packages that don't use Autoconf
708 will generally provide a @file{configure} script, and the most common
709 complaint about these alternative home-grown scripts is that they fail
710 to meet one or more of the @acronym{GNU} Coding Standards that users
711 have come to expect from Autoconf-generated @file{configure} scripts.
713 The Metaconfig package is similar in purpose to Autoconf, but the
714 scripts it produces require manual user intervention, which is quite
715 inconvenient when configuring large source trees.  Unlike Metaconfig
716 scripts, Autoconf scripts can support cross-compiling, if some care is
717 taken in writing them.
719 Autoconf does not solve all problems related to making portable
720 software packages---for a more complete solution, it should be used in
721 concert with other @acronym{GNU} build tools like Automake and
722 Libtool.  These other tools take on jobs like the creation of a
723 portable, recursive makefile with all of the standard targets,
724 linking of shared libraries, and so on.  @xref{The GNU Build System},
725 for more information.
727 Autoconf imposes some restrictions on the names of macros used with
728 @code{#if} in C programs (@pxref{Preprocessor Symbol Index}).
730 Autoconf requires @acronym{GNU} M4 version 1.4.5 or later in order to
731 generate the scripts.  It uses features that some versions of M4,
732 including @acronym{GNU} M4 1.3, do not have.  Autoconf works better
733 with @acronym{GNU} M4 version 1.4.11 or later, though this is not
734 required.
736 @xref{Autoconf 1}, for information about upgrading from version 1.
737 @xref{History}, for the story of Autoconf's development.  @xref{FAQ},
738 for answers to some common questions about Autoconf.
740 See the @uref{http://@/www.gnu.org/@/software/@/autoconf/,
741 Autoconf web page} for up-to-date information, details on the mailing
742 lists, pointers to a list of known bugs, etc.
744 Mail suggestions to @email{autoconf@@gnu.org, the Autoconf mailing
745 list}.  Past suggestions are
746 @uref{http://@/lists.gnu.org/@/archive/@/html/@/autoconf/, archived}.
748 Mail bug reports to @email{bug-autoconf@@gnu.org, the
749 Autoconf Bugs mailing list}.  Past bug reports are
750 @uref{http://@/lists.gnu.org/@/archive/@/html/@/bug-autoconf/, archived}.
752 If possible, first check that your bug is
753 not already solved in current development versions, and that it has not
754 been reported yet.  Be sure to include all the needed information and a
755 short @file{configure.ac} that demonstrates the problem.
757 Autoconf's development tree is accessible via @command{git}; see the
758 @uref{http://@/savannah.gnu.org/@/projects/@/autoconf/, Autoconf
759 Summary} for details, or view
760 @uref{http://@/git.sv.gnu.org/@/gitweb/@/?p=autoconf.git, the actual
761 repository}.  Anonymous @acronym{CVS} access is also available, see
762 @file{README} for more details.  Patches relative to the
763 current @command{git} version can be sent for review to the
764 @email{autoconf-patches@@gnu.org, Autoconf Patches mailing list}, with
765 discussion on prior patches
766 @uref{http://@/lists.gnu.org/@/archive/@/html/@/autoconf-@/patches/,
767 archived}; and all commits are posted in the read-only
768 @email{autoconf-commit@@gnu.org, Autoconf Commit mailing list}, which is
769 also @uref{http://@/lists.gnu.org/@/archive/@/html/@/autoconf-commit/,
770 archived}.
772 Because of its mission, the Autoconf package itself
773 includes only a set of often-used
774 macros that have already demonstrated their usefulness.  Nevertheless,
775 if you wish to share your macros, or find existing ones, see the
776 @uref{http://@/autoconf-archive.cryp.to/, Autoconf Macro
777 Archive}, which is kindly run by @email{simons@@cryp.to,
778 Peter Simons}.
781 @c ================================================= The GNU Build System
783 @node The GNU Build System
784 @chapter The @acronym{GNU} Build System
785 @cindex @acronym{GNU} build system
787 Autoconf solves an important problem---reliable discovery of
788 system-specific build and runtime information---but this is only one
789 piece of the puzzle for the development of portable software.  To this
790 end, the @acronym{GNU} project has developed a suite of integrated
791 utilities to finish the job Autoconf started: the @acronym{GNU} build
792 system, whose most important components are Autoconf, Automake, and
793 Libtool.  In this chapter, we introduce you to those tools, point you
794 to sources of more information, and try to convince you to use the
795 entire @acronym{GNU} build system for your software.
797 @menu
798 * Automake::                    Escaping makefile hell
799 * Gnulib::                      The @acronym{GNU} portability library
800 * Libtool::                     Building libraries portably
801 * Pointers::                    More info on the @acronym{GNU} build system
802 @end menu
804 @node Automake
805 @section Automake
807 The ubiquity of @command{make} means that a makefile is almost the
808 only viable way to distribute automatic build rules for software, but
809 one quickly runs into its numerous limitations.  Its lack of
810 support for automatic dependency tracking, recursive builds in
811 subdirectories, reliable timestamps (e.g., for network file systems), and
812 so on, mean that developers must painfully (and often incorrectly)
813 reinvent the wheel for each project.  Portability is non-trivial, thanks
814 to the quirks of @command{make} on many systems.  On top of all this is the
815 manual labor required to implement the many standard targets that users
816 have come to expect (@code{make install}, @code{make distclean},
817 @code{make uninstall}, etc.).  Since you are, of course, using Autoconf,
818 you also have to insert repetitive code in your @file{Makefile.in} to
819 recognize @code{@@CC@@}, @code{@@CFLAGS@@}, and other substitutions
820 provided by @command{configure}.  Into this mess steps @dfn{Automake}.
821 @cindex Automake
823 Automake allows you to specify your build needs in a @file{Makefile.am}
824 file with a vastly simpler and more powerful syntax than that of a plain
825 makefile, and then generates a portable @file{Makefile.in} for
826 use with Autoconf.  For example, the @file{Makefile.am} to build and
827 install a simple ``Hello world'' program might look like:
829 @example
830 bin_PROGRAMS = hello
831 hello_SOURCES = hello.c
832 @end example
834 @noindent
835 The resulting @file{Makefile.in} (~400 lines) automatically supports all
836 the standard targets, the substitutions provided by Autoconf, automatic
837 dependency tracking, @code{VPATH} building, and so on.  @command{make}
838 builds the @code{hello} program, and @code{make install} installs it
839 in @file{/usr/local/bin} (or whatever prefix was given to
840 @command{configure}, if not @file{/usr/local}).
842 The benefits of Automake increase for larger packages (especially ones
843 with subdirectories), but even for small programs the added convenience
844 and portability can be substantial.  And that's not all@enddots{}
846 @node Gnulib
847 @section Gnulib
849 @acronym{GNU} software has a well-deserved reputation for running on
850 many different types of systems.  While our primary goal is to write
851 software for the @acronym{GNU} system, many users and developers have
852 been introduced to us through the systems that they were already using.
854 @cindex Gnulib
855 Gnulib is a central location for common @acronym{GNU} code, intended to
856 be shared among free software packages.  Its components are typically
857 shared at the source level, rather than being a library that gets built,
858 installed, and linked against.  The idea is to copy files from Gnulib
859 into your own source tree.  There is no distribution tarball; developers
860 should just grab source modules from the repository.  The source files
861 are available online, under various licenses, mostly @acronym{GNU}
862 @acronym{GPL} or @acronym{GNU} @acronym{LGPL}.
864 Gnulib modules typically contain C source code along with Autoconf
865 macros used to configure the source code.  For example, the Gnulib
866 @code{stdbool} module implements a @file{stdbool.h} header that nearly
867 conforms to C99, even on old-fashioned hosts that lack @file{stdbool.h}.
868 This module contains a source file for the replacement header, along
869 with an Autoconf macro that arranges to use the replacement header on
870 old-fashioned systems.
872 @node Libtool
873 @section Libtool
875 Often, one wants to build not only programs, but libraries, so that
876 other programs can benefit from the fruits of your labor.  Ideally, one
877 would like to produce @emph{shared} (dynamically linked) libraries,
878 which can be used by multiple programs without duplication on disk or in
879 memory and can be updated independently of the linked programs.
880 Producing shared libraries portably, however, is the stuff of
881 nightmares---each system has its own incompatible tools, compiler flags,
882 and magic incantations.  Fortunately, @acronym{GNU} provides a solution:
883 @dfn{Libtool}.
884 @cindex Libtool
886 Libtool handles all the requirements of building shared libraries for
887 you, and at this time seems to be the @emph{only} way to do so with any
888 portability.  It also handles many other headaches, such as: the
889 interaction of Make rules with the variable suffixes of
890 shared libraries, linking reliably with shared libraries before they are
891 installed by the superuser, and supplying a consistent versioning system
892 (so that different versions of a library can be installed or upgraded
893 without breaking binary compatibility).  Although Libtool, like
894 Autoconf, can be used without Automake, it is most simply utilized in
895 conjunction with Automake---there, Libtool is used automatically
896 whenever shared libraries are needed, and you need not know its syntax.
898 @node Pointers
899 @section Pointers
901 Developers who are used to the simplicity of @command{make} for small
902 projects on a single system might be daunted at the prospect of
903 learning to use Automake and Autoconf.  As your software is
904 distributed to more and more users, however, you otherwise
905 quickly find yourself putting lots of effort into reinventing the
906 services that the @acronym{GNU} build tools provide, and making the
907 same mistakes that they once made and overcame.  (Besides, since
908 you're already learning Autoconf, Automake is a piece of cake.)
910 There are a number of places that you can go to for more information on
911 the @acronym{GNU} build tools.
913 @itemize @minus
915 @item Web
917 The project home pages for
918 @uref{http://@/www@/.gnu@/.org/@/software/@/autoconf/, Autoconf},
919 @uref{http://@/www@/.gnu@/.org/@/software/@/automake/, Automake},
920 @uref{http://@/www@/.gnu@/.org/@/software/@/gnulib/, Gnulib}, and
921 @uref{http://@/www@/.gnu@/.org/@/software/@/libtool/, Libtool}.
923 @item Automake Manual
925 @xref{Top, , Automake, automake, @acronym{GNU} Automake}, for more
926 information on Automake.
928 @item Books
930 The book @cite{@acronym{GNU} Autoconf, Automake and
931 Libtool}@footnote{@cite{@acronym{GNU} Autoconf, Automake and Libtool},
932 by G. V. Vaughan, B. Elliston, T. Tromey, and I. L. Taylor.  SAMS (originally
933 New Riders), 2000, ISBN 1578701902.} describes the complete @acronym{GNU}
934 build environment.  You can also find
935 @uref{http://@/sources.redhat.com/@/autobook/, the entire book on-line}.
937 @end itemize
939 @c ================================================= Making configure Scripts.
941 @node Making configure Scripts
942 @chapter Making @command{configure} Scripts
943 @cindex @file{aclocal.m4}
944 @cindex @command{configure}
946 The configuration scripts that Autoconf produces are by convention
947 called @command{configure}.  When run, @command{configure} creates several
948 files, replacing configuration parameters in them with appropriate
949 values.  The files that @command{configure} creates are:
951 @itemize @minus
952 @item
953 one or more @file{Makefile} files, usually one in each subdirectory of the
954 package (@pxref{Makefile Substitutions});
956 @item
957 optionally, a C header file, the name of which is configurable,
958 containing @code{#define} directives (@pxref{Configuration Headers});
960 @item
961 a shell script called @file{config.status} that, when run, recreates
962 the files listed above (@pxref{config.status Invocation});
964 @item
965 an optional shell script normally called @file{config.cache}
966 (created when using @samp{configure --config-cache}) that
967 saves the results of running many of the tests (@pxref{Cache Files});
969 @item
970 a file called @file{config.log} containing any messages produced by
971 compilers, to help debugging if @command{configure} makes a mistake.
972 @end itemize
974 @cindex @file{configure.in}
975 @cindex @file{configure.ac}
976 To create a @command{configure} script with Autoconf, you need to write an
977 Autoconf input file @file{configure.ac} (or @file{configure.in}) and run
978 @command{autoconf} on it.  If you write your own feature tests to
979 supplement those that come with Autoconf, you might also write files
980 called @file{aclocal.m4} and @file{acsite.m4}.  If you use a C header
981 file to contain @code{#define} directives, you might also run
982 @command{autoheader}, and you can distribute the generated file
983 @file{config.h.in} with the package.
985 Here is a diagram showing how the files that can be used in
986 configuration are produced.  Programs that are executed are suffixed by
987 @samp{*}.  Optional files are enclosed in square brackets (@samp{[]}).
988 @command{autoconf} and @command{autoheader} also read the installed Autoconf
989 macro files (by reading @file{autoconf.m4}).
991 @noindent
992 Files used in preparing a software package for distribution:
993 @example
994 your source files --> [autoscan*] --> [configure.scan] --> configure.ac
996 @group
997 configure.ac --.
998                |   .------> autoconf* -----> configure
999 [aclocal.m4] --+---+
1000                |   `-----> [autoheader*] --> [config.h.in]
1001 [acsite.m4] ---'
1002 @end group
1004 Makefile.in -------------------------------> Makefile.in
1005 @end example
1007 @noindent
1008 Files used in configuring a software package:
1009 @example
1010 @group
1011                        .-------------> [config.cache]
1012 configure* ------------+-------------> config.log
1013                        |
1014 [config.h.in] -.       v            .-> [config.h] -.
1015                +--> config.status* -+               +--> make*
1016 Makefile.in ---'                    `-> Makefile ---'
1017 @end group
1018 @end example
1020 @menu
1021 * Writing Autoconf Input::      What to put in an Autoconf input file
1022 * autoscan Invocation::         Semi-automatic @file{configure.ac} writing
1023 * ifnames Invocation::          Listing the conditionals in source code
1024 * autoconf Invocation::         How to create configuration scripts
1025 * autoreconf Invocation::       Remaking multiple @command{configure} scripts
1026 @end menu
1028 @node Writing Autoconf Input
1029 @section Writing @file{configure.ac}
1031 To produce a @command{configure} script for a software package, create a
1032 file called @file{configure.ac} that contains invocations of the
1033 Autoconf macros that test the system features your package needs or can
1034 use.  Autoconf macros already exist to check for many features; see
1035 @ref{Existing Tests}, for their descriptions.  For most other features,
1036 you can use Autoconf template macros to produce custom checks; see
1037 @ref{Writing Tests}, for information about them.  For especially tricky
1038 or specialized features, @file{configure.ac} might need to contain some
1039 hand-crafted shell commands; see @ref{Portable Shell, , Portable Shell
1040 Programming}.  The @command{autoscan} program can give you a good start
1041 in writing @file{configure.ac} (@pxref{autoscan Invocation}, for more
1042 information).
1044 Previous versions of Autoconf promoted the name @file{configure.in},
1045 which is somewhat ambiguous (the tool needed to process this file is not
1046 described by its extension), and introduces a slight confusion with
1047 @file{config.h.in} and so on (for which @samp{.in} means ``to be
1048 processed by @command{configure}'').  Using @file{configure.ac} is now
1049 preferred.
1051 @menu
1052 * Shell Script Compiler::       Autoconf as solution of a problem
1053 * Autoconf Language::           Programming in Autoconf
1054 * Autoconf Input Layout::       Standard organization of @file{configure.ac}
1055 @end menu
1057 @node Shell Script Compiler
1058 @subsection A Shell Script Compiler
1060 Just as for any other computer language, in order to properly program
1061 @file{configure.ac} in Autoconf you must understand @emph{what} problem
1062 the language tries to address and @emph{how} it does so.
1064 The problem Autoconf addresses is that the world is a mess.  After all,
1065 you are using Autoconf in order to have your package compile easily on
1066 all sorts of different systems, some of them being extremely hostile.
1067 Autoconf itself bears the price for these differences: @command{configure}
1068 must run on all those systems, and thus @command{configure} must limit itself
1069 to their lowest common denominator of features.
1071 Naturally, you might then think of shell scripts; who needs
1072 @command{autoconf}?  A set of properly written shell functions is enough to
1073 make it easy to write @command{configure} scripts by hand.  Sigh!
1074 Unfortunately, even in 2008, where shells without any function support are
1075 far and few between, there are pitfalls to avoid when making use of them.
1076 Also, finding a Bourne shell that accepts shell functions is not trivial,
1077 even though there is almost always one on interesting porting targets.
1079 So, what is really needed is some kind of compiler, @command{autoconf},
1080 that takes an Autoconf program, @file{configure.ac}, and transforms it
1081 into a portable shell script, @command{configure}.
1083 How does @command{autoconf} perform this task?
1085 There are two obvious possibilities: creating a brand new language or
1086 extending an existing one.  The former option is attractive: all
1087 sorts of optimizations could easily be implemented in the compiler and
1088 many rigorous checks could be performed on the Autoconf program
1089 (e.g., rejecting any non-portable construct).  Alternatively, you can
1090 extend an existing language, such as the @code{sh} (Bourne shell)
1091 language.
1093 Autoconf does the latter: it is a layer on top of @code{sh}.  It was
1094 therefore most convenient to implement @command{autoconf} as a macro
1095 expander: a program that repeatedly performs @dfn{macro expansions} on
1096 text input, replacing macro calls with macro bodies and producing a pure
1097 @code{sh} script in the end.  Instead of implementing a dedicated
1098 Autoconf macro expander, it is natural to use an existing
1099 general-purpose macro language, such as M4, and implement the extensions
1100 as a set of M4 macros.
1103 @node Autoconf Language
1104 @subsection The Autoconf Language
1105 @cindex quotation
1107 The Autoconf language differs from many other computer
1108 languages because it treats actual code the same as plain text.  Whereas
1109 in C, for instance, data and instructions have different syntactic
1110 status, in Autoconf their status is rigorously the same.  Therefore, we
1111 need a means to distinguish literal strings from text to be expanded:
1112 quotation.
1114 When calling macros that take arguments, there must not be any white
1115 space between the macro name and the open parenthesis.  Arguments should
1116 be enclosed within the M4 quote characters @samp{[} and @samp{]}, and be
1117 separated by commas.  Any leading blanks or newlines in arguments are ignored,
1118 unless they are quoted.  You should always quote an argument that
1119 might contain a macro name, comma, parenthesis, or a leading blank or
1120 newline.  This rule applies recursively for every macro
1121 call, including macros called from other macros.
1123 For instance:
1125 @example
1126 AC_CHECK_HEADER([stdio.h],
1127                 [AC_DEFINE([HAVE_STDIO_H], [1],
1128                    [Define to 1 if you have <stdio.h>.])],
1129                 [AC_MSG_ERROR([Sorry, can't do anything for you])])
1130 @end example
1132 @noindent
1133 is quoted properly.  You may safely simplify its quotation to:
1135 @example
1136 AC_CHECK_HEADER([stdio.h],
1137                 [AC_DEFINE([HAVE_STDIO_H], 1,
1138                    [Define to 1 if you have <stdio.h>.])],
1139                 [AC_MSG_ERROR([Sorry, can't do anything for you])])
1140 @end example
1142 @noindent
1143 because @samp{1} cannot contain a macro call.  Here, the argument of
1144 @code{AC_MSG_ERROR} must be quoted; otherwise, its comma would be
1145 interpreted as an argument separator.  Also, the second and third arguments
1146 of @samp{AC_CHECK_HEADER} must be quoted, since they contain
1147 macro calls.  The three arguments @samp{HAVE_STDIO_H}, @samp{stdio.h},
1148 and @samp{Define to 1 if you have <stdio.h>.} do not need quoting, but
1149 if you unwisely defined a macro with a name like @samp{Define} or
1150 @samp{stdio} then they would need quoting.  Cautious Autoconf users
1151 would keep the quotes, but many Autoconf users find such precautions
1152 annoying, and would rewrite the example as follows:
1154 @example
1155 AC_CHECK_HEADER(stdio.h,
1156                 [AC_DEFINE(HAVE_STDIO_H, 1,
1157                    [Define to 1 if you have <stdio.h>.])],
1158                 [AC_MSG_ERROR([Sorry, can't do anything for you])])
1159 @end example
1161 @noindent
1162 This is safe, so long as you adopt good naming conventions and do not
1163 define macros with names like @samp{HAVE_STDIO_H}, @samp{stdio}, or
1164 @samp{h}.  Though it is also safe here to omit the quotes around
1165 @samp{Define to 1 if you have <stdio.h>.} this is not recommended, as
1166 message strings are more likely to inadvertently contain commas.
1168 The following example is wrong and dangerous, as it is underquoted:
1170 @example
1171 AC_CHECK_HEADER(stdio.h,
1172                 AC_DEFINE(HAVE_STDIO_H, 1,
1173                    Define to 1 if you have <stdio.h>.),
1174                 AC_MSG_ERROR([Sorry, can't do anything for you]))
1175 @end example
1177 In other cases, you may have to use text that also resembles a macro
1178 call.  You must quote that text even when it is not passed as a macro
1179 argument:
1181 @example
1182 echo "Hard rock was here!  --[AC_DC]"
1183 @end example
1185 @noindent
1186 which results in:
1188 @example
1189 echo "Hard rock was here!  --AC_DC"
1190 @end example
1192 @noindent
1193 When you use the same text in a macro argument, you must therefore have
1194 an extra quotation level (since one is stripped away by the macro
1195 substitution).  In general, then, it is a good idea to @emph{use double
1196 quoting for all literal string arguments}:
1198 @example
1199 AC_MSG_WARN([[AC_DC stinks  --Iron Maiden]])
1200 @end example
1202 You are now able to understand one of the constructs of Autoconf that
1203 has been continually misunderstood@enddots{}  The rule of thumb is that
1204 @emph{whenever you expect macro expansion, expect quote expansion};
1205 i.e., expect one level of quotes to be lost.  For instance:
1207 @example
1208 AC_COMPILE_IFELSE([char b[10];], [], [AC_MSG_ERROR([you lose])])
1209 @end example
1211 @noindent
1212 is incorrect: here, the first argument of @code{AC_COMPILE_IFELSE} is
1213 @samp{char b[10];} and is expanded once, which results in
1214 @samp{char b10;}.  (There was an idiom common in Autoconf's past to
1215 address this issue via the M4 @code{changequote} primitive, but do not
1216 use it!)  Let's take a closer look: the author meant the first argument
1217 to be understood as a literal, and therefore it must be quoted twice:
1219 @example
1220 AC_COMPILE_IFELSE([[char b[10];]], [], [AC_MSG_ERROR([you lose])])
1221 @end example
1223 @noindent
1224 Voil@`a, you actually produce @samp{char b[10];} this time!
1226 On the other hand, descriptions (e.g., the last parameter of
1227 @code{AC_DEFINE} or @code{AS_HELP_STRING}) are not literals---they
1228 are subject to line breaking, for example---and should not be double quoted.
1229 Even if these descriptions are short and are not actually broken, double
1230 quoting them yields weird results.
1232 Some macros take optional arguments, which this documentation represents
1233 as @ovar{arg} (not to be confused with the quote characters).  You may
1234 just leave them empty, or use @samp{[]} to make the emptiness of the
1235 argument explicit, or you may simply omit the trailing commas.  The
1236 three lines below are equivalent:
1238 @example
1239 AC_CHECK_HEADERS([stdio.h], [], [], [])
1240 AC_CHECK_HEADERS([stdio.h],,,)
1241 AC_CHECK_HEADERS([stdio.h])
1242 @end example
1244 It is best to put each macro call on its own line in
1245 @file{configure.ac}.  Most of the macros don't add extra newlines; they
1246 rely on the newline after the macro call to terminate the commands.
1247 This approach makes the generated @command{configure} script a little
1248 easier to read by not inserting lots of blank lines.  It is generally
1249 safe to set shell variables on the same line as a macro call, because
1250 the shell allows assignments without intervening newlines.
1252 You can include comments in @file{configure.ac} files by starting them
1253 with the @samp{#}.  For example, it is helpful to begin
1254 @file{configure.ac} files with a line like this:
1256 @example
1257 # Process this file with autoconf to produce a configure script.
1258 @end example
1260 @node Autoconf Input Layout
1261 @subsection Standard @file{configure.ac} Layout
1263 The order in which @file{configure.ac} calls the Autoconf macros is not
1264 important, with a few exceptions.  Every @file{configure.ac} must
1265 contain a call to @code{AC_INIT} before the checks, and a call to
1266 @code{AC_OUTPUT} at the end (@pxref{Output}).  Additionally, some macros
1267 rely on other macros having been called first, because they check
1268 previously set values of some variables to decide what to do.  These
1269 macros are noted in the individual descriptions (@pxref{Existing
1270 Tests}), and they also warn you when @command{configure} is created if they
1271 are called out of order.
1273 To encourage consistency, here is a suggested order for calling the
1274 Autoconf macros.  Generally speaking, the things near the end of this
1275 list are those that could depend on things earlier in it.  For example,
1276 library functions could be affected by types and libraries.
1278 @display
1279 @group
1280 Autoconf requirements
1281 @code{AC_INIT(@var{package}, @var{version}, @var{bug-report-address})}
1282 information on the package
1283 checks for programs
1284 checks for libraries
1285 checks for header files
1286 checks for types
1287 checks for structures
1288 checks for compiler characteristics
1289 checks for library functions
1290 checks for system services
1291 @code{AC_CONFIG_FILES(@r{[}@var{file@dots{}}@r{]})}
1292 @code{AC_OUTPUT}
1293 @end group
1294 @end display
1297 @node autoscan Invocation
1298 @section Using @command{autoscan} to Create @file{configure.ac}
1299 @cindex @command{autoscan}
1301 The @command{autoscan} program can help you create and/or maintain a
1302 @file{configure.ac} file for a software package.  @command{autoscan}
1303 examines source files in the directory tree rooted at a directory given
1304 as a command line argument, or the current directory if none is given.
1305 It searches the source files for common portability problems and creates
1306 a file @file{configure.scan} which is a preliminary @file{configure.ac}
1307 for that package, and checks a possibly existing @file{configure.ac} for
1308 completeness.
1310 When using @command{autoscan} to create a @file{configure.ac}, you
1311 should manually examine @file{configure.scan} before renaming it to
1312 @file{configure.ac}; it probably needs some adjustments.
1313 Occasionally, @command{autoscan} outputs a macro in the wrong order
1314 relative to another macro, so that @command{autoconf} produces a warning;
1315 you need to move such macros manually.  Also, if you want the package to
1316 use a configuration header file, you must add a call to
1317 @code{AC_CONFIG_HEADERS} (@pxref{Configuration Headers}).  You might
1318 also have to change or add some @code{#if} directives to your program in
1319 order to make it work with Autoconf (@pxref{ifnames Invocation}, for
1320 information about a program that can help with that job).
1322 When using @command{autoscan} to maintain a @file{configure.ac}, simply
1323 consider adding its suggestions.  The file @file{autoscan.log}
1324 contains detailed information on why a macro is requested.
1326 @command{autoscan} uses several data files (installed along with Autoconf)
1327 to determine which macros to output when it finds particular symbols in
1328 a package's source files.  These data files all have the same format:
1329 each line consists of a symbol, one or more blanks, and the Autoconf macro to
1330 output if that symbol is encountered.  Lines starting with @samp{#} are
1331 comments.
1333 @command{autoscan} accepts the following options:
1335 @table @option
1336 @item --help
1337 @itemx -h
1338 Print a summary of the command line options and exit.
1340 @item --version
1341 @itemx -V
1342 Print the version number of Autoconf and exit.
1344 @item --verbose
1345 @itemx -v
1346 Print the names of the files it examines and the potentially interesting
1347 symbols it finds in them.  This output can be voluminous.
1349 @item --debug
1350 @itemx -d
1351 Don't remove temporary files.
1353 @item --include=@var{dir}
1354 @itemx -I @var{dir}
1355 Append @var{dir} to the include path.  Multiple invocations accumulate.
1357 @item --prepend-include=@var{dir}
1358 @itemx -B @var{dir}
1359 Prepend @var{dir} to the include path.  Multiple invocations accumulate.
1360 @end table
1362 @node ifnames Invocation
1363 @section Using @command{ifnames} to List Conditionals
1364 @cindex @command{ifnames}
1366 @command{ifnames} can help you write @file{configure.ac} for a software
1367 package.  It prints the identifiers that the package already uses in C
1368 preprocessor conditionals.  If a package has already been set up to have
1369 some portability, @command{ifnames} can thus help you figure out what its
1370 @command{configure} needs to check for.  It may help fill in some gaps in a
1371 @file{configure.ac} generated by @command{autoscan} (@pxref{autoscan
1372 Invocation}).
1374 @command{ifnames} scans all of the C source files named on the command line
1375 (or the standard input, if none are given) and writes to the standard
1376 output a sorted list of all the identifiers that appear in those files
1377 in @code{#if}, @code{#elif}, @code{#ifdef}, or @code{#ifndef}
1378 directives.  It prints each identifier on a line, followed by a
1379 space-separated list of the files in which that identifier occurs.
1381 @noindent
1382 @command{ifnames} accepts the following options:
1384 @table @option
1385 @item --help
1386 @itemx -h
1387 Print a summary of the command line options and exit.
1389 @item --version
1390 @itemx -V
1391 Print the version number of Autoconf and exit.
1392 @end table
1394 @node autoconf Invocation
1395 @section Using @command{autoconf} to Create @command{configure}
1396 @cindex @command{autoconf}
1398 To create @command{configure} from @file{configure.ac}, run the
1399 @command{autoconf} program with no arguments.  @command{autoconf} processes
1400 @file{configure.ac} with the M4 macro processor, using the
1401 Autoconf macros.  If you give @command{autoconf} an argument, it reads that
1402 file instead of @file{configure.ac} and writes the configuration script
1403 to the standard output instead of to @command{configure}.  If you give
1404 @command{autoconf} the argument @option{-}, it reads from the standard
1405 input instead of @file{configure.ac} and writes the configuration script
1406 to the standard output.
1408 The Autoconf macros are defined in several files.  Some of the files are
1409 distributed with Autoconf; @command{autoconf} reads them first.  Then it
1410 looks for the optional file @file{acsite.m4} in the directory that
1411 contains the distributed Autoconf macro files, and for the optional file
1412 @file{aclocal.m4} in the current directory.  Those files can contain
1413 your site's or the package's own Autoconf macro definitions
1414 (@pxref{Writing Autoconf Macros}, for more information).  If a macro is
1415 defined in more than one of the files that @command{autoconf} reads, the
1416 last definition it reads overrides the earlier ones.
1418 @command{autoconf} accepts the following options:
1420 @table @option
1421 @item --help
1422 @itemx -h
1423 Print a summary of the command line options and exit.
1425 @item --version
1426 @itemx -V
1427 Print the version number of Autoconf and exit.
1429 @item --verbose
1430 @itemx -v
1431 Report processing steps.
1433 @item --debug
1434 @itemx -d
1435 Don't remove the temporary files.
1437 @item --force
1438 @itemx -f
1439 Remake @file{configure} even if newer than its input files.
1441 @item --include=@var{dir}
1442 @itemx -I @var{dir}
1443 Append @var{dir} to the include path.  Multiple invocations accumulate.
1445 @item --prepend-include=@var{dir}
1446 @itemx -B @var{dir}
1447 Prepend @var{dir} to the include path.  Multiple invocations accumulate.
1449 @item --output=@var{file}
1450 @itemx -o @var{file}
1451 Save output (script or trace) to @var{file}.  The file @option{-} stands
1452 for the standard output.
1454 @item --warnings=@var{category}
1455 @itemx -W @var{category}
1456 @evindex WARNINGS
1457 Report the warnings related to @var{category} (which can actually be a
1458 comma separated list).  @xref{Reporting Messages}, macro
1459 @code{AC_DIAGNOSE}, for a comprehensive list of categories.  Special
1460 values include:
1462 @table @samp
1463 @item all
1464 report all the warnings
1466 @item none
1467 report none
1469 @item error
1470 treats warnings as errors
1472 @item no-@var{category}
1473 disable warnings falling into @var{category}
1474 @end table
1476 Warnings about @samp{syntax} are enabled by default, and the environment
1477 variable @env{WARNINGS}, a comma separated list of categories, is
1478 honored as well.  Passing @option{-W @var{category}} actually behaves as if
1479 you had passed @option{--warnings syntax,$WARNINGS,@var{category}}.  To
1480 disable the defaults and @env{WARNINGS}, and then
1481 enable warnings about obsolete constructs, use @option{-W
1482 none,obsolete}.
1484 @cindex Back trace
1485 @cindex Macro invocation stack
1486 Because @command{autoconf} uses @command{autom4te} behind the scenes, it
1487 displays a back trace for errors, but not for warnings; if you want
1488 them, just pass @option{-W error}.  @xref{autom4te Invocation}, for some
1489 examples.
1491 @item --trace=@var{macro}[:@var{format}]
1492 @itemx -t @var{macro}[:@var{format}]
1493 Do not create the @command{configure} script, but list the calls to
1494 @var{macro} according to the @var{format}.  Multiple @option{--trace}
1495 arguments can be used to list several macros.  Multiple @option{--trace}
1496 arguments for a single macro are not cumulative; instead, you should
1497 just make @var{format} as long as needed.
1499 The @var{format} is a regular string, with newlines if desired, and
1500 several special escape codes.  It defaults to @samp{$f:$l:$n:$%}; see
1501 @ref{autom4te Invocation}, for details on the @var{format}.
1503 @item --initialization
1504 @itemx -i
1505 By default, @option{--trace} does not trace the initialization of the
1506 Autoconf macros (typically the @code{AC_DEFUN} definitions).  This
1507 results in a noticeable speedup, but can be disabled by this option.
1508 @end table
1511 It is often necessary to check the content of a @file{configure.ac}
1512 file, but parsing it yourself is extremely fragile and error-prone.  It
1513 is suggested that you rely upon @option{--trace} to scan
1514 @file{configure.ac}.  For instance, to find the list of variables that
1515 are substituted, use:
1517 @example
1518 @group
1519 $ @kbd{autoconf -t AC_SUBST}
1520 configure.ac:2:AC_SUBST:ECHO_C
1521 configure.ac:2:AC_SUBST:ECHO_N
1522 configure.ac:2:AC_SUBST:ECHO_T
1523 @i{More traces deleted}
1524 @end group
1525 @end example
1527 @noindent
1528 The example below highlights the difference between @samp{$@@},
1529 @samp{$*}, and @samp{$%}.
1531 @example
1532 @group
1533 $ @kbd{cat configure.ac}
1534 AC_DEFINE(This, is, [an
1535 [example]])
1536 $ @kbd{autoconf -t 'AC_DEFINE:@@: $@@}
1537 *: $*
1538 %: $%'
1539 @@: [This],[is],[an
1540 [example]]
1541 *: This,is,an
1542 [example]
1543 %: This:is:an [example]
1544 @end group
1545 @end example
1547 @noindent
1548 The @var{format} gives you a lot of freedom:
1550 @example
1551 @group
1552 $ @kbd{autoconf -t 'AC_SUBST:$$ac_subst@{"$1"@} = "$f:$l";'}
1553 $ac_subst@{"ECHO_C"@} = "configure.ac:2";
1554 $ac_subst@{"ECHO_N"@} = "configure.ac:2";
1555 $ac_subst@{"ECHO_T"@} = "configure.ac:2";
1556 @i{More traces deleted}
1557 @end group
1558 @end example
1560 @noindent
1561 A long @var{separator} can be used to improve the readability of complex
1562 structures, and to ease their parsing (for instance when no single
1563 character is suitable as a separator):
1565 @example
1566 @group
1567 $ @kbd{autoconf -t 'AM_MISSING_PROG:$@{|:::::|@}*'}
1568 ACLOCAL|:::::|aclocal|:::::|$missing_dir
1569 AUTOCONF|:::::|autoconf|:::::|$missing_dir
1570 AUTOMAKE|:::::|automake|:::::|$missing_dir
1571 @i{More traces deleted}
1572 @end group
1573 @end example
1575 @node autoreconf Invocation
1576 @section Using @command{autoreconf} to Update @command{configure} Scripts
1577 @cindex @command{autoreconf}
1579 Installing the various components of the @acronym{GNU} Build System can be
1580 tedious: running @command{autopoint} for Gettext, @command{automake} for
1581 @file{Makefile.in} etc.@: in each directory.  It may be needed either
1582 because some tools such as @command{automake} have been updated on your
1583 system, or because some of the sources such as @file{configure.ac} have
1584 been updated, or finally, simply in order to install the @acronym{GNU} Build
1585 System in a fresh tree.
1587 @command{autoreconf} runs @command{autoconf}, @command{autoheader},
1588 @command{aclocal}, @command{automake}, @command{libtoolize}, and
1589 @command{autopoint} (when appropriate) repeatedly to update the
1590 @acronym{GNU} Build System in the specified directories and their
1591 subdirectories (@pxref{Subdirectories}).  By default, it only remakes
1592 those files that are older than their sources.  The environment variables
1593 @env{AUTOCONF}, @env{AUTOHEADER}, @env{AUTOMAKE}, @env{ACLOCAL},
1594 @env{AUTOPOINT}, @env{LIBTOOLIZE}, @env{M4}, and @env{MAKE} may be used
1595 to override the invocation of the respective tools.
1597 If you install a new version of some tool, you can make
1598 @command{autoreconf} remake @emph{all} of the files by giving it the
1599 @option{--force} option.
1601 @xref{Automatic Remaking}, for Make rules to automatically
1602 rebuild @command{configure} scripts when their source files change.  That
1603 method handles the timestamps of configuration header templates
1604 properly, but does not pass @option{--autoconf-dir=@var{dir}} or
1605 @option{--localdir=@var{dir}}.
1607 @cindex Gettext
1608 @cindex @command{autopoint}
1609 Gettext supplies the @command{autopoint} command to add translation
1610 infrastructure to a source package.  If you use @command{autopoint},
1611 your @file{configure.ac} should invoke both @code{AM_GNU_GETTEXT} and
1612 @code{AM_GNU_GETTEXT_VERSION(@var{gettext-version})}.  @xref{autopoint
1613 Invocation, , Invoking the @code{autopoint} Program, gettext,
1614 @acronym{GNU} @code{gettext} utilities}, for further details.
1616 @noindent
1617 @command{autoreconf} accepts the following options:
1619 @table @option
1620 @item --help
1621 @itemx -h
1622 Print a summary of the command line options and exit.
1624 @item --version
1625 @itemx -V
1626 Print the version number of Autoconf and exit.
1628 @item --verbose
1629 @itemx -V
1630 Print the name of each directory @command{autoreconf} examines and the
1631 commands it runs.  If given two or more times, pass @option{--verbose}
1632 to subordinate tools that support it.
1634 @item --debug
1635 @itemx -d
1636 Don't remove the temporary files.
1638 @item --force
1639 @itemx -f
1640 Remake even @file{configure} scripts and configuration headers that are
1641 newer than their input files (@file{configure.ac} and, if present,
1642 @file{aclocal.m4}).
1644 @item --install
1645 @itemx -i
1646 Install the missing auxiliary files in the package.  By default, files
1647 are copied; this can be changed with @option{--symlink}.
1649 If deemed appropriate, this option triggers calls to
1650 @samp{automake --add-missing},
1651 @samp{libtoolize}, @samp{autopoint}, etc.
1653 @item --no-recursive
1654 Do not rebuild files in subdirectories to configure (see @ref{Subdirectories},
1655 macro @code{AC_CONFIG_SUBDIRS}).
1657 @item --symlink
1658 @itemx -s
1659 When used with @option{--install}, install symbolic links to the missing
1660 auxiliary files instead of copying them.
1662 @item --make
1663 @itemx -m
1664 When the directories were configured, update the configuration by
1665 running @samp{./config.status --recheck && ./config.status}, and then
1666 run @samp{make}.
1668 @item --include=@var{dir}
1669 @itemx -I @var{dir}
1670 Append @var{dir} to the include path.  Multiple invocations accumulate.
1671 Passed on to @command{aclocal}, @command{autoconf} and
1672 @command{autoheader} internally.
1674 @item --prepend-include=@var{dir}
1675 @itemx -B @var{dir}
1676 Prepend @var{dir} to the include path.  Multiple invocations accumulate.
1677 Passed on to @command{autoconf} and @command{autoheader} internally.
1679 @item --warnings=@var{category}
1680 @itemx -W @var{category}
1681 @evindex WARNINGS
1682 Report the warnings related to @var{category} (which can actually be a
1683 comma separated list).
1685 @table @samp
1686 @item cross
1687 related to cross compilation issues.
1689 @item obsolete
1690 report the uses of obsolete constructs.
1692 @item portability
1693 portability issues
1695 @item syntax
1696 dubious syntactic constructs.
1698 @item all
1699 report all the warnings
1701 @item none
1702 report none
1704 @item error
1705 treats warnings as errors
1707 @item no-@var{category}
1708 disable warnings falling into @var{category}
1709 @end table
1711 Warnings about @samp{syntax} are enabled by default, and the environment
1712 variable @env{WARNINGS}, a comma separated list of categories, is
1713 honored as well.  Passing @option{-W @var{category}} actually behaves as if
1714 you had passed @option{--warnings syntax,$WARNINGS,@var{category}}.  To
1715 disable the defaults and @env{WARNINGS}, and then
1716 enable warnings about obsolete constructs, use @option{-W
1717 none,obsolete}.
1718 @end table
1720 If you want @command{autoreconf} to pass flags that are not listed here
1721 on to @command{aclocal}, set @code{ACLOCAL_AMFLAGS} in your @file{Makefile.am}.
1722 Due to a limitation in the Autoconf implementation these flags currently
1723 must be set on a single line in @file{Makefile.am}, without any
1724 backslash-newlines.
1726 @c ========================================= Initialization and Output Files.
1728 @node Setup
1729 @chapter Initialization and Output Files
1731 Autoconf-generated @command{configure} scripts need some information about
1732 how to initialize, such as how to find the package's source files and
1733 about the output files to produce.  The following sections describe the
1734 initialization and the creation of output files.
1736 @menu
1737 * Initializing configure::      Option processing etc.
1738 * Versioning::                  Dealing with Autoconf versions
1739 * Notices::                     Copyright, version numbers in @command{configure}
1740 * Input::                       Where Autoconf should find files
1741 * Output::                      Outputting results from the configuration
1742 * Configuration Actions::       Preparing the output based on results
1743 * Configuration Files::         Creating output files
1744 * Makefile Substitutions::      Using output variables in makefiles
1745 * Configuration Headers::       Creating a configuration header file
1746 * Configuration Commands::      Running arbitrary instantiation commands
1747 * Configuration Links::         Links depending on the configuration
1748 * Subdirectories::              Configuring independent packages together
1749 * Default Prefix::              Changing the default installation prefix
1750 @end menu
1752 @node Initializing configure
1753 @section Initializing @command{configure}
1755 Every @command{configure} script must call @code{AC_INIT} before doing
1756 anything else.  The only other required macro is @code{AC_OUTPUT}
1757 (@pxref{Output}).
1759 @anchor{AC_INIT}
1760 @defmac AC_INIT (@var{package}, @var{version}, @ovar{bug-report}, @
1761   @ovar{tarname}, @ovar{url})
1762 @acindex{INIT}
1763 Process any command-line arguments and perform various initializations
1764 and verifications.
1766 Set the name of the @var{package} and its @var{version}.  These are
1767 typically used in @option{--version} support, including that of
1768 @command{configure}.  The optional argument @var{bug-report} should be
1769 the email to which users should send bug reports.  The package
1770 @var{tarname} differs from @var{package}: the latter designates the full
1771 package name (e.g., @samp{GNU Autoconf}), while the former is meant for
1772 distribution tar ball names (e.g., @samp{autoconf}).  It defaults to
1773 @var{package} with @samp{GNU } stripped, lower-cased, and all characters
1774 other than alphanumerics and underscores are changed to @samp{-}.  If
1775 provided, @var{url} should be the home page for the package.
1777 It is preferable that the arguments of @code{AC_INIT} be static, i.e.,
1778 there should not be any shell computation, but they can be computed by
1781 The following M4 macros (e.g., @code{AC_PACKAGE_NAME}), output variables
1782 (e.g., @code{PACKAGE_NAME}), and preprocessor symbols (e.g.,
1783 @code{PACKAGE_NAME}), are defined by @code{AC_INIT}:
1785 @table @asis
1786 @item @code{AC_PACKAGE_NAME}, @code{PACKAGE_NAME}
1787 @acindex{PACKAGE_NAME}
1788 @ovindex PACKAGE_NAME
1789 @cvindex PACKAGE_NAME
1790 Exactly @var{package}.
1792 @item @code{AC_PACKAGE_TARNAME}, @code{PACKAGE_TARNAME}
1793 @acindex{PACKAGE_TARNAME}
1794 @ovindex PACKAGE_TARNAME
1795 @cvindex PACKAGE_TARNAME
1796 Exactly @var{tarname}, possibly generated from @var{package}.
1798 @item @code{AC_PACKAGE_VERSION}, @code{PACKAGE_VERSION}
1799 @acindex{PACKAGE_VERSION}
1800 @ovindex PACKAGE_VERSION
1801 @cvindex PACKAGE_VERSION
1802 Exactly @var{version}.
1804 @item @code{AC_PACKAGE_STRING}, @code{PACKAGE_STRING}
1805 @acindex{PACKAGE_STRING}
1806 @ovindex PACKAGE_STRING
1807 @cvindex PACKAGE_STRING
1808 Exactly @samp{@var{package} @var{version}}.
1810 @item @code{AC_PACKAGE_BUGREPORT}, @code{PACKAGE_BUGREPORT}
1811 @acindex{PACKAGE_BUGREPORT}
1812 @ovindex PACKAGE_BUGREPORT
1813 @cvindex PACKAGE_BUGREPORT
1814 Exactly @var{bug-report}, if one was provided.
1816 @item @code{AC_PACKAGE_URL}, @code{PACKAGE_URL}
1817 @acindex{PACKAGE_URL}
1818 @ovindex PACKAGE_URL
1819 @cvindex PACKAGE_URL
1820 Exactly @var{url}, if one was provided.  If @var{url} was empty, but
1821 @var{package} begins with @samp{GNU }, then this defaults to
1822 @samp{http://@/www.gnu.org/@/software/@/@var{tarname}/}, otherwise, no URL is
1823 assumed.
1824 @end table
1825 @end defmac
1827 If your @command{configure} script does its own option processing, it
1828 should inspect @samp{$@@} or @samp{$*} immediately after calling
1829 @code{AC_INIT}, because other Autoconf macros liberally use the
1830 @command{set} command to process strings, and this has the side effect
1831 of updating @samp{$@@} and @samp{$*}.  However, we suggest that you use
1832 standard macros like @code{AC_ARG_ENABLE} instead of attempting to
1833 implement your own option processing.  @xref{Site Configuration}.
1835 @node Versioning
1836 @section Dealing with Autoconf versions
1837 @cindex Autoconf version
1838 @cindex version, Autoconf
1840 The following optional macros can be used to help choose the minimum
1841 version of Autoconf that can successfully compile a given
1842 @file{configure.ac}.
1844 @defmac AC_PREREQ (@var{version})
1845 @acindex{PREREQ}
1846 @cindex Version
1847 Ensure that a recent enough version of Autoconf is being used.  If the
1848 version of Autoconf being used to create @command{configure} is
1849 earlier than @var{version}, print an error message to the standard
1850 error output and exit with failure (exit status is 63).  For example:
1852 @example
1853 AC_PREREQ([@value{VERSION}])
1854 @end example
1856 This macro is the only macro that may be used before @code{AC_INIT}, but
1857 for consistency, you are invited not to do so.
1858 @end defmac
1860 @defmac AC_AUTOCONF_VERSION
1861 @acindex{AUTOCONF_VERSION}
1862 This macro was introduced in Autoconf 2.62.  It identifies the version
1863 of Autoconf that is currently parsing the input file, in a format
1864 suitable for @code{m4_version_compare} (@pxref{m4_version_compare}); in
1865 other words, for this release of Autoconf, its value is
1866 @samp{@value{VERSION}}.  One potential use of this macro is for writing
1867 conditional fallbacks based on when a feature was added to Autoconf,
1868 rather than using @code{AC_PREREQ} to require the newer version of
1869 Autoconf.  However, remember that the Autoconf philosophy favors feature
1870 checks over version checks.
1872 You should not expand this macro directly; use
1873 @samp{m4_defn([AC_AUTOCONF_VERSION])} instead.  This is because some
1874 users might
1875 have a beta version of Autoconf installed, with arbitrary letters
1876 included in its version string.  This means it is possible for the
1877 version string to contain the name of a defined macro, such that
1878 expanding @code{AC_AUTOCONF_VERSION} would trigger the expansion of that
1879 macro during rescanning, and change the version string to be different
1880 than what you intended to check.
1881 @end defmac
1883 @node Notices
1884 @section Notices in @command{configure}
1885 @cindex Notices in @command{configure}
1887 The following macros manage version numbers for @command{configure}
1888 scripts.  Using them is optional.
1890 @defmac AC_COPYRIGHT (@var{copyright-notice})
1891 @acindex{COPYRIGHT}
1892 @cindex Copyright Notice
1893 State that, in addition to the Free Software Foundation's copyright on
1894 the Autoconf macros, parts of your @command{configure} are covered by the
1895 @var{copyright-notice}.
1897 The @var{copyright-notice} shows up in both the head of
1898 @command{configure} and in @samp{configure --version}.
1899 @end defmac
1902 @defmac AC_REVISION (@var{revision-info})
1903 @acindex{REVISION}
1904 @cindex Revision
1905 Copy revision stamp @var{revision-info} into the @command{configure}
1906 script, with any dollar signs or double-quotes removed.  This macro lets
1907 you put a revision stamp from @file{configure.ac} into @command{configure}
1908 without @acronym{RCS} or @acronym{CVS} changing it when you check in
1909 @command{configure}.  That way, you can determine easily which revision of
1910 @file{configure.ac} a particular @command{configure} corresponds to.
1912 For example, this line in @file{configure.ac}:
1914 @c The @w prevents RCS from changing the example in the manual.
1915 @example
1916 AC_REVISION([@w{$}Revision: 1.30 $])
1917 @end example
1919 @noindent
1920 produces this in @command{configure}:
1922 @example
1923 #!/bin/sh
1924 # From configure.ac Revision: 1.30
1925 @end example
1926 @end defmac
1929 @node Input
1930 @section Finding @command{configure} Input
1932 @anchor{AC_CONFIG_SRCDIR}
1933 @defmac AC_CONFIG_SRCDIR (@var{unique-file-in-source-dir})
1934 @acindex{CONFIG_SRCDIR}
1935 @var{unique-file-in-source-dir} is some file that is in the package's
1936 source directory; @command{configure} checks for this file's existence to
1937 make sure that the directory that it is told contains the source code in
1938 fact does.  Occasionally people accidentally specify the wrong directory
1939 with @option{--srcdir}; this is a safety check.  @xref{configure
1940 Invocation}, for more information.
1941 @end defmac
1944 @c FIXME: Remove definitively once --install explained.
1946 @c Small packages may store all their macros in @code{aclocal.m4}.  As the
1947 @c set of macros grows, or for maintenance reasons, a maintainer may prefer
1948 @c to split the macros in several files.  In this case, Autoconf must be
1949 @c told which files to load, and in which order.
1951 @c @defmac AC_INCLUDE (@var{file}@dots{})
1952 @c @acindex{INCLUDE}
1953 @c @c FIXME: There is no longer shell globbing.
1954 @c Read the macro definitions that appear in the listed files.  A list of
1955 @c space-separated file names or shell globbing patterns is expected.  The
1956 @c files are read in the order they're listed.
1958 @c Because the order of definition of macros is important (only the last
1959 @c definition of a macro is used), beware that it is @code{AC_INIT} that
1960 @c loads @file{acsite.m4} and @file{aclocal.m4}.  Note that
1961 @c @code{AC_INCLUDE}ing a file before @code{AC_INIT} or within
1962 @c @file{aclocal.m4} is different from doing so after @code{AC_INIT}: in
1963 @c the latter case, non-macro lines from included files may end up in the
1964 @c @file{configure} script, whereas in the former case, they'd be discarded
1965 @c just like any text that appear before @code{AC_INIT}.
1966 @c @end defmac
1968 Packages that do manual configuration or use the @command{install} program
1969 might need to tell @command{configure} where to find some other shell
1970 scripts by calling @code{AC_CONFIG_AUX_DIR}, though the default places
1971 it looks are correct for most cases.
1973 @defmac AC_CONFIG_AUX_DIR (@var{dir})
1974 @acindex{CONFIG_AUX_DIR}
1975 Use the auxiliary build tools (e.g., @file{install-sh},
1976 @file{config.sub}, @file{config.guess}, Cygnus @command{configure},
1977 Automake and Libtool scripts, etc.)@: that are in directory @var{dir}.
1978 These are auxiliary files used in configuration.  @var{dir} can be
1979 either absolute or relative to @file{@var{srcdir}}.  The default is
1980 @file{@var{srcdir}} or @file{@var{srcdir}/..} or
1981 @file{@var{srcdir}/../..}, whichever is the first that contains
1982 @file{install-sh}.  The other files are not checked for, so that using
1983 @code{AC_PROG_INSTALL} does not automatically require distributing the
1984 other auxiliary files.  It checks for @file{install.sh} also, but that
1985 name is obsolete because some @command{make} have a rule that creates
1986 @file{install} from it if there is no makefile.
1988 The auxiliary directory is commonly named @file{build-aux}.
1989 If you need portability to @acronym{DOS} variants, do not name the
1990 auxiliary directory @file{aux}.  @xref{File System Conventions}.
1991 @end defmac
1993 @defmac AC_REQUIRE_AUX_FILE (@var{file})
1994 @acindex{REQUIRE_AUX_FILE}
1995 Declares that @var{file} is expected in the directory defined above.  In
1996 Autoconf proper, this macro does nothing: its sole purpose is to be
1997 traced by third-party tools to produce a list of expected auxiliary
1998 files.  For instance it is called by macros like @code{AC_PROG_INSTALL}
1999 (@pxref{Particular Programs}) or @code{AC_CANONICAL_BUILD}
2000 (@pxref{Canonicalizing}) to register the auxiliary files they need.
2001 @end defmac
2003 Similarly, packages that use @command{aclocal} should declare where
2004 local macros can be found using @code{AC_CONFIG_MACRO_DIR}.
2006 @defmac AC_CONFIG_MACRO_DIR (@var{dir})
2007 @acindex{CONFIG_MACRO_DIR}
2008 Specify @var{dir} as the location of additional local Autoconf macros.
2009 This macro is intended for use by future versions of commands like
2010 @command{autoreconf} that trace macro calls.  It should be called
2011 directly from @file{configure.ac} so that tools that install macros for
2012 @command{aclocal} can find the macros' declarations.
2014 Note that if you use @command{aclocal} from Automake to generate
2015 @file{aclocal.m4}, you must also set @code{ACLOCAL_AMFLAGS = -I
2016 @var{dir}} in your top-level @file{Makefile.am}.  Due to a limitation in
2017 the Autoconf implementation of @command{autoreconf}, these include
2018 directives currently must be set on a single line in @file{Makefile.am},
2019 without any backslash-newlines.
2020 @end defmac
2023 @node Output
2024 @section Outputting Files
2025 @cindex Outputting files
2027 Every Autoconf script, e.g., @file{configure.ac}, should finish by
2028 calling @code{AC_OUTPUT}.  That is the macro that generates and runs
2029 @file{config.status}, which in turn creates the makefiles and any
2030 other files resulting from configuration.  This is the only required
2031 macro besides @code{AC_INIT} (@pxref{Input}).
2033 @anchor{AC_OUTPUT}
2034 @defmac AC_OUTPUT
2035 @acindex{OUTPUT}
2036 @cindex Instantiation
2037 Generate @file{config.status} and launch it.  Call this macro once, at
2038 the end of @file{configure.ac}.
2040 @file{config.status} performs all the configuration actions: all the
2041 output files (see @ref{Configuration Files}, macro
2042 @code{AC_CONFIG_FILES}), header files (see @ref{Configuration Headers},
2043 macro @code{AC_CONFIG_HEADERS}), commands (see @ref{Configuration
2044 Commands}, macro @code{AC_CONFIG_COMMANDS}), links (see
2045 @ref{Configuration Links}, macro @code{AC_CONFIG_LINKS}), subdirectories
2046 to configure (see @ref{Subdirectories}, macro @code{AC_CONFIG_SUBDIRS})
2047 are honored.
2049 The location of your @code{AC_OUTPUT} invocation is the exact point
2050 where configuration actions are taken: any code afterwards is
2051 executed by @command{configure} once @command{config.status} was run.  If
2052 you want to bind actions to @command{config.status} itself
2053 (independently of whether @command{configure} is being run), see
2054 @ref{Configuration Commands, , Running Arbitrary Configuration
2055 Commands}.
2056 @end defmac
2058 Historically, the usage of @code{AC_OUTPUT} was somewhat different.
2059 @xref{Obsolete Macros}, for a description of the arguments that
2060 @code{AC_OUTPUT} used to support.
2063 If you run @command{make} in subdirectories, you should run it using the
2064 @command{make} variable @code{MAKE}.  Most versions of @command{make} set
2065 @code{MAKE} to the name of the @command{make} program plus any options it
2066 was given.  (But many do not include in it the values of any variables
2067 set on the command line, so those are not passed on automatically.)
2068 Some old versions of @command{make} do not set this variable.  The
2069 following macro allows you to use it even with those versions.
2071 @anchor{AC_PROG_MAKE_SET}
2072 @defmac AC_PROG_MAKE_SET
2073 @acindex{PROG_MAKE_SET}
2074 @ovindex SET_MAKE
2075 If the Make command, @code{$MAKE} if set or else @samp{make}, predefines
2076 @code{$(MAKE)}, define output variable @code{SET_MAKE} to be empty.
2077 Otherwise, define @code{SET_MAKE} to a macro definition that sets
2078 @code{$(MAKE)}, such as @samp{MAKE=make}.  Calls @code{AC_SUBST} for
2079 @code{SET_MAKE}.
2080 @end defmac
2082 If you use this macro, place a line like this in each @file{Makefile.in}
2083 that runs @command{MAKE} on other directories:
2085 @example
2086 @@SET_MAKE@@
2087 @end example
2091 @node Configuration Actions
2092 @section Performing Configuration Actions
2093 @cindex Configuration actions
2095 @file{configure} is designed so that it appears to do everything itself,
2096 but there is actually a hidden slave: @file{config.status}.
2097 @file{configure} is in charge of examining your system, but it is
2098 @file{config.status} that actually takes the proper actions based on the
2099 results of @file{configure}.  The most typical task of
2100 @file{config.status} is to @emph{instantiate} files.
2102 @acindex{CONFIG_@var{ITEMS}}
2103 This section describes the common behavior of the four standard
2104 instantiating macros: @code{AC_CONFIG_FILES}, @code{AC_CONFIG_HEADERS},
2105 @code{AC_CONFIG_COMMANDS} and @code{AC_CONFIG_LINKS}.  They all
2106 have this prototype:
2108 @c FIXME: Can't use @ovar here, Texinfo 4.0 goes lunatic and emits something
2109 @c awful.
2110 @example
2111 AC_CONFIG_@var{ITEMS}(@var{tag}@dots{}, [@var{commands}], [@var{init-cmds}])
2112 @end example
2114 @noindent
2115 where the arguments are:
2117 @table @var
2118 @item tag@dots{}
2119 A blank-or-newline-separated list of tags, which are typically the names of
2120 the files to instantiate.
2122 You are encouraged to use literals as @var{tags}.  In particular, you
2123 should avoid
2125 @example
2126 @dots{} && my_foos="$my_foos fooo"
2127 @dots{} && my_foos="$my_foos foooo"
2128 AC_CONFIG_@var{ITEMS}([$my_foos])
2129 @end example
2131 @noindent
2132 and use this instead:
2134 @example
2135 @dots{} && AC_CONFIG_@var{ITEMS}([fooo])
2136 @dots{} && AC_CONFIG_@var{ITEMS}([foooo])
2137 @end example
2139 The macros @code{AC_CONFIG_FILES} and @code{AC_CONFIG_HEADERS} use
2140 special @var{tag} values: they may have the form @samp{@var{output}} or
2141 @samp{@var{output}:@var{inputs}}.  The file @var{output} is instantiated
2142 from its templates, @var{inputs} (defaulting to @samp{@var{output}.in}).
2144 @samp{AC_CONFIG_FILES([Makefile:boiler/top.mk:boiler/bot.mk)]},
2145 for example, asks for
2146 the creation of the file @file{Makefile} that contains the expansion of the
2147 output variables in the concatenation of @file{boiler/top.mk} and
2148 @file{boiler/bot.mk}.
2150 The special value @samp{-} might be used to denote the standard output
2151 when used in @var{output}, or the standard input when used in the
2152 @var{inputs}.  You most probably don't need to use this in
2153 @file{configure.ac}, but it is convenient when using the command line
2154 interface of @file{./config.status}, see @ref{config.status Invocation},
2155 for more details.
2157 The @var{inputs} may be absolute or relative file names.  In the latter
2158 case they are first looked for in the build tree, and then in the source
2159 tree.  Input files should be text files, and a line length below 2000
2160 bytes should be safe.
2162 @item commands
2163 Shell commands output literally into @file{config.status}, and
2164 associated with a tag that the user can use to tell @file{config.status}
2165 which commands to run.  The commands are run each time a @var{tag}
2166 request is given to @file{config.status}, typically each time the file
2167 @file{@var{tag}} is created.
2169 The variables set during the execution of @command{configure} are
2170 @emph{not} available here: you first need to set them via the
2171 @var{init-cmds}.  Nonetheless the following variables are precomputed:
2173 @table @code
2174 @item srcdir
2175 The name of the top source directory, assuming that the working
2176 directory is the top build directory.  This
2177 is what the @command{configure} option @option{--srcdir} sets.
2179 @item ac_top_srcdir
2180 The name of the top source directory, assuming that the working
2181 directory is the current build directory.
2184 @item ac_top_build_prefix
2185 The name of the top build directory, assuming that the working
2186 directory is the current build directory.
2187 It can be empty, or else ends with a slash, so that you may concatenate
2190 @item ac_srcdir
2191 The name of the corresponding source directory, assuming that the
2192 working directory is the current build directory.
2193 @end table
2195 @noindent
2196 The @dfn{current} directory refers to the directory (or
2197 pseudo-directory) containing the input part of @var{tags}.  For
2198 instance, running
2200 @example
2201 AC_CONFIG_COMMANDS([deep/dir/out:in/in.in], [@dots{}], [@dots{}])
2202 @end example
2204 @noindent
2205  with @option{--srcdir=../package} produces the following values:
2207 @example
2208 # Argument of --srcdir
2209 srcdir='../package'
2210 # Reversing deep/dir
2211 ac_top_build_prefix='../../'
2212 # Concatenation of $ac_top_build_prefix and srcdir
2213 ac_top_srcdir='../../../package'
2214 # Concatenation of $ac_top_srcdir and deep/dir
2215 ac_srcdir='../../../package/deep/dir'
2216 @end example
2218 @noindent
2219 independently of @samp{in/in.in}.
2221 @item init-cmds
2222 Shell commands output @emph{unquoted} near the beginning of
2223 @file{config.status}, and executed each time @file{config.status} runs
2224 (regardless of the tag).  Because they are unquoted, for example,
2225 @samp{$var} is output as the value of @code{var}.  @var{init-cmds}
2226 is typically used by @file{configure} to give @file{config.status} some
2227 variables it needs to run the @var{commands}.
2229 You should be extremely cautious in your variable names: all the
2230 @var{init-cmds} share the same name space and may overwrite each other
2231 in unpredictable ways.  Sorry@enddots{}
2232 @end table
2234 All these macros can be called multiple times, with different
2235 @var{tag} values, of course!
2238 @node Configuration Files
2239 @section Creating Configuration Files
2240 @cindex Creating configuration files
2241 @cindex Configuration file creation
2243 Be sure to read the previous section, @ref{Configuration Actions}.
2245 @anchor{AC_CONFIG_FILES}
2246 @defmac AC_CONFIG_FILES (@var{file}@dots{}, @ovar{cmds}, @ovar{init-cmds})
2247 @acindex{CONFIG_FILES}
2248 Make @code{AC_OUTPUT} create each @file{@var{file}} by copying an input
2249 file (by default @file{@var{file}.in}), substituting the output variable
2250 values.
2251 @c Before we used to have this feature, which was later rejected
2252 @c because it complicates the writing of makefiles:
2253 @c If the file would be unchanged, it is left untouched, to preserve
2254 @c timestamp.
2255 This macro is one of the instantiating macros; see @ref{Configuration
2256 Actions}.  @xref{Makefile Substitutions}, for more information on using
2257 output variables.  @xref{Setting Output Variables}, for more information
2258 on creating them.  This macro creates the directory that the file is in
2259 if it doesn't exist.  Usually, makefiles are created this way,
2260 but other files, such as @file{.gdbinit}, can be specified as well.
2262 Typical calls to @code{AC_CONFIG_FILES} look like this:
2264 @example
2265 AC_CONFIG_FILES([Makefile src/Makefile man/Makefile X/Imakefile])
2266 AC_CONFIG_FILES([autoconf], [chmod +x autoconf])
2267 @end example
2269 You can override an input file name by appending to @var{file} a
2270 colon-separated list of input files.  Examples:
2272 @example
2273 AC_CONFIG_FILES([Makefile:boiler/top.mk:boiler/bot.mk]
2274                 [lib/Makefile:boiler/lib.mk])
2275 @end example
2277 @noindent
2278 Doing this allows you to keep your file names acceptable to
2279 @acronym{DOS} variants, or
2280 to prepend and/or append boilerplate to the file.
2281 @end defmac
2285 @node Makefile Substitutions
2286 @section Substitutions in Makefiles
2287 @cindex Substitutions in makefiles
2288 @cindex Makefile substitutions
2290 Each subdirectory in a distribution that contains something to be
2291 compiled or installed should come with a file @file{Makefile.in}, from
2292 which @command{configure} creates a file @file{Makefile} in that directory.
2293 To create @file{Makefile}, @command{configure} performs a simple variable
2294 substitution, replacing occurrences of @samp{@@@var{variable}@@} in
2295 @file{Makefile.in} with the value that @command{configure} has determined
2296 for that variable.  Variables that are substituted into output files in
2297 this way are called @dfn{output variables}.  They are ordinary shell
2298 variables that are set in @command{configure}.  To make @command{configure}
2299 substitute a particular variable into the output files, the macro
2300 @code{AC_SUBST} must be called with that variable name as an argument.
2301 Any occurrences of @samp{@@@var{variable}@@} for other variables are
2302 left unchanged.  @xref{Setting Output Variables}, for more information
2303 on creating output variables with @code{AC_SUBST}.
2305 A software package that uses a @command{configure} script should be
2306 distributed with a file @file{Makefile.in}, but no makefile; that
2307 way, the user has to properly configure the package for the local system
2308 before compiling it.
2310 @xref{Makefile Conventions, , Makefile Conventions, standards, The
2311 @acronym{GNU} Coding Standards}, for more information on what to put in
2312 makefiles.
2314 @menu
2315 * Preset Output Variables::     Output variables that are always set
2316 * Installation Directory Variables::  Other preset output variables
2317 * Changed Directory Variables:: Warnings about @file{datarootdir}
2318 * Build Directories::           Supporting multiple concurrent compiles
2319 * Automatic Remaking::          Makefile rules for configuring
2320 @end menu
2322 @node Preset Output Variables
2323 @subsection Preset Output Variables
2324 @cindex Output variables
2326 Some output variables are preset by the Autoconf macros.  Some of the
2327 Autoconf macros set additional output variables, which are mentioned in
2328 the descriptions for those macros.  @xref{Output Variable Index}, for a
2329 complete list of output variables.  @xref{Installation Directory
2330 Variables}, for the list of the preset ones related to installation
2331 directories.  Below are listed the other preset ones, many of which are
2332 precious variables (@pxref{Setting Output Variables},
2333 @code{AC_ARG_VAR}).
2335 @c Just say no to ASCII sorting!  We're humans, not computers.
2336 @c These variables are listed as they would be in a dictionary:
2337 @c actor
2338 @c Actress
2339 @c actress
2341 @defvar CFLAGS
2342 @evindex CFLAGS
2343 @ovindex CFLAGS
2344 Debugging and optimization options for the C compiler.  If it is not set
2345 in the environment when @command{configure} runs, the default value is set
2346 when you call @code{AC_PROG_CC} (or empty if you don't).  @command{configure}
2347 uses this variable when compiling or linking programs to test for C features.
2349 If a compiler option affects only the behavior of the preprocessor
2350 (e.g., @option{-D @var{name}}), it should be put into @code{CPPFLAGS}
2351 instead.  If it affects only the linker (e.g., @option{-L
2352 @var{directory}}), it should be put into @code{LDFLAGS} instead.  If it
2353 affects only the compiler proper, @code{CFLAGS} is the natural home for
2354 it.  If an option affects multiple phases of the compiler, though,
2355 matters get tricky.  One approach to put such options directly into
2356 @code{CC}, e.g., @code{CC='gcc -m64'}.  Another is to put them into both
2357 @code{CPPFLAGS} and @code{LDFLAGS}, but not into @code{CFLAGS}.
2359 However, remember that some @file{Makefile} variables are reserved by
2360 the GNU Coding Standards for the use of the ``user''---the person
2361 building the package.  For instance, @code{CFLAGS} is one such variable.
2363 Sometimes package developers are tempted to set user variables such as
2364 @code{CFLAGS} because it appears to make their job easier.  However, the
2365 package itself should never set a user variable, particularly not to
2366 include switches that are required for proper compilation of the
2367 package.  Since these variables are documented as being for the package
2368 builder, that person rightfully expects to be able to override any of
2369 these variables at build time.  If the package developer needs to add
2370 switches without interfering with the user, the proper way to do that is
2371 to introduce an additional variable.  Automake makes this easy by
2372 introducing @code{AM_CFLAGS} (@pxref{Flag Variables Ordering, , ,
2373 automake, @acronym{GNU} Automake}), but the concept is the same even if
2374 Automake is not used.
2375 @end defvar
2377 @defvar configure_input
2378 @ovindex configure_input
2379 A comment saying that the file was generated automatically by
2380 @command{configure} and giving the name of the input file.
2381 @code{AC_OUTPUT} adds a comment line containing this variable to the top
2382 of every makefile it creates.  For other files, you should
2383 reference this variable in a comment at the top of each input file.  For
2384 example, an input shell script should begin like this:
2386 @example
2387 #!/bin/sh
2388 # @@configure_input@@
2389 @end example
2391 @noindent
2392 The presence of that line also reminds people editing the file that it
2393 needs to be processed by @command{configure} in order to be used.
2394 @end defvar
2396 @defvar CPPFLAGS
2397 @evindex CPPFLAGS
2398 @ovindex CPPFLAGS
2399 Preprocessor options for the C, C++, and Objective C preprocessors and
2400 compilers.  If
2401 it is not set in the environment when @command{configure} runs, the default
2402 value is empty.  @command{configure} uses this variable when preprocessing
2403 or compiling programs to test for C, C++, and Objective C features.
2405 This variable's contents should contain options like @option{-I},
2406 @option{-D}, and @option{-U} that affect only the behavior of the
2407 preprocessor.  Please see the explanation of @code{CFLAGS} for what you
2408 can do if an option affects other phases of the compiler as well.
2410 Currently, @command{configure} always links as part of a single
2411 invocation of the compiler that also preprocesses and compiles, so it
2412 uses this variable also when linking programs.  However, it is unwise to
2413 depend on this behavior because the @acronym{GNU} coding standards do
2414 not require it and many packages do not use @code{CPPFLAGS} when linking
2415 programs.
2417 @xref{Special Chars in Variables}, for limitations that @code{CPPFLAGS}
2418 might run into.
2419 @end defvar
2421 @defvar CXXFLAGS
2422 @evindex CXXFLAGS
2423 @ovindex CXXFLAGS
2424 Debugging and optimization options for the C++ compiler.  It acts like
2425 @code{CFLAGS}, but for C++ instead of C.
2426 @end defvar
2428 @defvar DEFS
2429 @ovindex DEFS
2430 @option{-D} options to pass to the C compiler.  If @code{AC_CONFIG_HEADERS}
2431 is called, @command{configure} replaces @samp{@@DEFS@@} with
2432 @option{-DHAVE_CONFIG_H} instead (@pxref{Configuration Headers}).  This
2433 variable is not defined while @command{configure} is performing its tests,
2434 only when creating the output files.  @xref{Setting Output Variables}, for
2435 how to check the results of previous tests.
2436 @end defvar
2438 @defvar ECHO_C
2439 @defvarx ECHO_N
2440 @defvarx ECHO_T
2441 @ovindex ECHO_C
2442 @ovindex ECHO_N
2443 @ovindex ECHO_T
2444 How does one suppress the trailing newline from @command{echo} for
2445 question-answer message pairs?  These variables provide a way:
2447 @example
2448 echo $ECHO_N "And the winner is... $ECHO_C"
2449 sleep 100000000000
2450 echo "$@{ECHO_T@}dead."
2451 @end example
2453 @noindent
2454 Some old and uncommon @command{echo} implementations offer no means to
2455 achieve this, in which case @code{ECHO_T} is set to tab.  You might not
2456 want to use it.
2457 @end defvar
2459 @defvar ERLCFLAGS
2460 @evindex ERLCFLAGS
2461 @ovindex ERLCFLAGS
2462 Debugging and optimization options for the Erlang compiler.  If it is not set
2463 in the environment when @command{configure} runs, the default value is empty.
2464 @command{configure} uses this variable when compiling
2465 programs to test for Erlang features.
2466 @end defvar
2468 @defvar FCFLAGS
2469 @evindex FCFLAGS
2470 @ovindex FCFLAGS
2471 Debugging and optimization options for the Fortran 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_FC} (or empty if you don't).
2474 @command{configure} uses this variable when compiling or linking
2475 programs to test for Fortran features.
2476 @end defvar
2478 @defvar FFLAGS
2479 @evindex FFLAGS
2480 @ovindex FFLAGS
2481 Debugging and optimization options for the Fortran 77 compiler.  If it
2482 is not set in the environment when @command{configure} runs, the default
2483 value is set when you call @code{AC_PROG_F77} (or empty if you don't).
2484 @command{configure} uses this variable when compiling or linking
2485 programs to test for Fortran 77 features.
2486 @end defvar
2488 @defvar LDFLAGS
2489 @evindex LDFLAGS
2490 @ovindex LDFLAGS
2491 Options for the linker.  If it is not set
2492 in the environment when @command{configure} runs, the default value is empty.
2493 @command{configure} uses this variable when linking programs to test for
2494 C, C++, Objective C, and Fortran features.
2496 This variable's contents should contain options like @option{-s} and
2497 @option{-L} that affect only the behavior of the linker.  Please see the
2498 explanation of @code{CFLAGS} for what you can do if an option also
2499 affects other phases of the compiler.
2501 Don't use this variable to pass library names
2502 (@option{-l}) to the linker; use @code{LIBS} instead.
2503 @end defvar
2505 @defvar LIBS
2506 @evindex LIBS
2507 @ovindex LIBS
2508 @option{-l} options to pass to the linker.  The default value is empty,
2509 but some Autoconf macros may prepend extra libraries to this variable if
2510 those libraries are found and provide necessary functions, see
2511 @ref{Libraries}.  @command{configure} uses this variable when linking
2512 programs to test for C, C++, and Fortran features.
2513 @end defvar
2515 @defvar OBJCFLAGS
2516 @evindex OBJCFLAGS
2517 @ovindex OBJCFLAGS
2518 Debugging and optimization options for the Objective C compiler.  It
2519 acts like @code{CFLAGS}, but for Objective C instead of C.
2520 @end defvar
2522 @defvar builddir
2523 @ovindex builddir
2524 Rigorously equal to @samp{.}.  Added for symmetry only.
2525 @end defvar
2527 @defvar abs_builddir
2528 @ovindex abs_builddir
2529 Absolute name of @code{builddir}.
2530 @end defvar
2532 @defvar top_builddir
2533 @ovindex top_builddir
2534 The relative name of the top level of the current build tree.  In the
2535 top-level directory, this is the same as @code{builddir}.
2536 @end defvar
2538 @defvar top_build_prefix
2539 @ovindex top_build_prefix
2540 The relative name of the top level of the current build tree with final
2541 slash if nonemtpy.  This is the same as @code{top_builddir}, except that
2542 it contains zero or more runs of @code{../}, so it should not be
2543 appended with a slash for concatenation.  This helps for @command{make}
2544 implementations that otherwise do not treat @file{./file} and @file{file}
2545 as equal in the toplevel build directory.
2546 @end defvar
2548 @defvar abs_top_builddir
2549 @ovindex abs_top_builddir
2550 Absolute name of @code{top_builddir}.
2551 @end defvar
2553 @defvar srcdir
2554 @ovindex srcdir
2555 The name of the directory that contains the source code for
2556 that makefile.
2557 @end defvar
2559 @defvar abs_srcdir
2560 @ovindex abs_srcdir
2561 Absolute name of @code{srcdir}.
2562 @end defvar
2564 @defvar top_srcdir
2565 @ovindex top_srcdir
2566 The name of the top-level source code directory for the
2567 package.  In the top-level directory, this is the same as @code{srcdir}.
2568 @end defvar
2570 @defvar abs_top_srcdir
2571 @ovindex abs_top_srcdir
2572 Absolute name of @code{top_srcdir}.
2573 @end defvar
2575 @node Installation Directory Variables
2576 @subsection Installation Directory Variables
2577 @cindex Installation directories
2578 @cindex Directories, installation
2580 The following variables specify the directories for
2581 package installation, see @ref{Directory Variables, , Variables for
2582 Installation Directories, standards, The @acronym{GNU} Coding
2583 Standards}, for more information.  Each variable corresponds to an
2584 argument of @command{configure}; trailing slashes are stripped so that
2585 expressions such as @samp{$@{prefix@}/lib} expand with only one slash
2586 between directory names.  See the end of this section for
2587 details on when and how to use these variables.
2589 @defvar bindir
2590 @ovindex bindir
2591 The directory for installing executables that users run.
2592 @end defvar
2594 @defvar datadir
2595 @ovindex datadir
2596 The directory for installing idiosyncratic read-only
2597 architecture-independent data.
2598 @end defvar
2600 @defvar datarootdir
2601 @ovindex datarootdir
2602 The root of the directory tree for read-only architecture-independent
2603 data files.
2604 @end defvar
2606 @defvar docdir
2607 @ovindex docdir
2608 The directory for installing documentation files (other than Info and
2609 man).
2610 @end defvar
2612 @defvar dvidir
2613 @ovindex dvidir
2614 The directory for installing documentation files in DVI format.
2615 @end defvar
2617 @defvar exec_prefix
2618 @ovindex exec_prefix
2619 The installation prefix for architecture-dependent files.  By default
2620 it's the same as @var{prefix}.  You should avoid installing anything
2621 directly to @var{exec_prefix}.  However, the default value for
2622 directories containing architecture-dependent files should be relative
2623 to @var{exec_prefix}.
2624 @end defvar
2626 @defvar htmldir
2627 @ovindex htmldir
2628 The directory for installing HTML documentation.
2629 @end defvar
2631 @defvar includedir
2632 @ovindex includedir
2633 The directory for installing C header files.
2634 @end defvar
2636 @defvar infodir
2637 @ovindex infodir
2638 The directory for installing documentation in Info format.
2639 @end defvar
2641 @defvar libdir
2642 @ovindex libdir
2643 The directory for installing object code libraries.
2644 @end defvar
2646 @defvar libexecdir
2647 @ovindex libexecdir
2648 The directory for installing executables that other programs run.
2649 @end defvar
2651 @defvar localedir
2652 @ovindex localedir
2653 The directory for installing locale-dependent but
2654 architecture-independent data, such as message catalogs.  This directory
2655 usually has a subdirectory per locale.
2656 @end defvar
2658 @defvar localstatedir
2659 @ovindex localstatedir
2660 The directory for installing modifiable single-machine data.
2661 @end defvar
2663 @defvar mandir
2664 @ovindex mandir
2665 The top-level directory for installing documentation in man format.
2666 @end defvar
2668 @defvar oldincludedir
2669 @ovindex oldincludedir
2670 The directory for installing C header files for non-@acronym{GCC} compilers.
2671 @end defvar
2673 @defvar pdfdir
2674 @ovindex pdfdir
2675 The directory for installing PDF documentation.
2676 @end defvar
2678 @defvar prefix
2679 @ovindex prefix
2680 The common installation prefix for all files.  If @var{exec_prefix}
2681 is defined to a different value, @var{prefix} is used only for
2682 architecture-independent files.
2683 @end defvar
2685 @defvar psdir
2686 @ovindex psdir
2687 The directory for installing PostScript documentation.
2688 @end defvar
2690 @defvar sbindir
2691 @ovindex sbindir
2692 The directory for installing executables that system
2693 administrators run.
2694 @end defvar
2696 @defvar sharedstatedir
2697 @ovindex sharedstatedir
2698 The directory for installing modifiable architecture-independent data.
2699 @end defvar
2701 @defvar sysconfdir
2702 @ovindex sysconfdir
2703 The directory for installing read-only single-machine data.
2704 @end defvar
2707 Most of these variables have values that rely on @code{prefix} or
2708 @code{exec_prefix}.  It is deliberate that the directory output
2709 variables keep them unexpanded: typically @samp{@@datarootdir@@} is
2710 replaced by @samp{$@{prefix@}/share}, not @samp{/usr/local/share}, and
2711 @samp{@@datadir@@} is replaced by @samp{$@{datarootdir@}}.
2713 This behavior is mandated by the @acronym{GNU} coding standards, so that when
2714 the user runs:
2716 @table @samp
2717 @item make
2718 she can still specify a different prefix from the one specified to
2719 @command{configure}, in which case, if needed, the package should hard
2720 code dependencies corresponding to the make-specified prefix.
2722 @item make install
2723 she can specify a different installation location, in which case the
2724 package @emph{must} still depend on the location which was compiled in
2725 (i.e., never recompile when @samp{make install} is run).  This is an
2726 extremely important feature, as many people may decide to install all
2727 the files of a package grouped together, and then install links from
2728 the final locations to there.
2729 @end table
2731 In order to support these features, it is essential that
2732 @code{datarootdir} remains defined as @samp{$@{prefix@}/share},
2733 so that its value can be expanded based
2734 on the current value of @code{prefix}.
2736 A corollary is that you should not use these variables except in
2737 makefiles.  For instance, instead of trying to evaluate @code{datadir}
2738 in @file{configure} and hard-coding it in makefiles using
2739 e.g., @samp{AC_DEFINE_UNQUOTED([DATADIR], ["$datadir"], [Data directory.])},
2740 you should add
2741 @option{-DDATADIR='$(datadir)'} to your makefile's definition of
2742 @code{CPPFLAGS} (@code{AM_CPPFLAGS} if you are also using Automake).
2744 Similarly, you should not rely on @code{AC_CONFIG_FILES} to replace
2745 @code{bindir} and friends in your shell scripts and other files; instead,
2746 let @command{make} manage their replacement.  For instance Autoconf
2747 ships templates of its shell scripts ending with @samp{.in}, and uses a
2748 makefile snippet similar to the following to build scripts like
2749 @command{autoheader} and @command{autom4te}:
2751 @example
2752 @group
2753 edit = sed \
2754         -e 's|@@bindir[@@]|$(bindir)|g' \
2755         -e 's|@@pkgdatadir[@@]|$(pkgdatadir)|g' \
2756         -e 's|@@prefix[@@]|$(prefix)|g'
2757 @end group
2759 @group
2760 autoheader autom4te: Makefile
2761         rm -f $@@ $@@.tmp
2762         srcdir=''; \
2763           test -f ./$@@.in || srcdir=$(srcdir)/; \
2764           $(edit) $$@{srcdir@}$@@.in >$@@.tmp
2765         chmod +x $@@.tmp
2766         chmod a-w $@@.tmp
2767         mv $@@.tmp $@@
2768 @end group
2770 @group
2771 autoheader: $(srcdir)/autoheader.in
2772 autom4te: $(srcdir)/autom4te.in
2773 @end group
2774 @end example
2776 Some details are noteworthy:
2778 @table @asis
2779 @item @samp{@@bindir[@@]}
2780 The brackets prevent @command{configure} from replacing
2781 @samp{@@bindir@@} in the Sed expression itself.
2782 Brackets are preferable to a backslash here, since
2783 Posix says @samp{\@@} is not portable.
2785 @item @samp{$(bindir)}
2786 Don't use @samp{@@bindir@@}!  Use the matching makefile variable
2787 instead.
2789 @item @samp{$(pkgdatadir)}
2790 The example takes advantage of the variable @samp{$(pkgdatadir)}
2791 provided by Automake; it is equivalent to @samp{$(datadir)/$(PACKAGE)}.
2793 @item @samp{/}
2794 Don't use @samp{/} in the Sed expressions that replace file names since
2795 most likely the
2796 variables you use, such as @samp{$(bindir)}, contain @samp{/}.
2797 Use a shell metacharacter instead, such as @samp{|}.
2799 @item special characters
2800 File names, file name components, and the value of @code{VPATH} should
2801 not contain shell metacharacters or white
2802 space.  @xref{Special Chars in Variables}.
2804 @item dependency on @file{Makefile}
2805 Since @code{edit} uses values that depend on the configuration specific
2806 values (@code{prefix}, etc.)@: and not only on @code{VERSION} and so forth,
2807 the output depends on @file{Makefile}, not @file{configure.ac}.
2809 @item @samp{$@@}
2810 The main rule is generic, and uses @samp{$@@} extensively to
2811 avoid the need for multiple copies of the rule.
2813 @item Separated dependencies and single suffix rules
2814 You can't use them!  The above snippet cannot be (portably) rewritten
2817 @example
2818 autoconf autoheader: Makefile
2819 @group
2820 .in:
2821         rm -f $@@ $@@.tmp
2822         $(edit) $< >$@@.tmp
2823         chmod +x $@@.tmp
2824         mv $@@.tmp $@@
2825 @end group
2826 @end example
2828 @xref{Single Suffix Rules}, for details.
2830 @item @samp{$(srcdir)}
2831 Be sure to specify the name of the source directory,
2832 otherwise the package won't support separated builds.
2833 @end table
2835 For the more specific installation of Erlang libraries, the following variables
2836 are defined:
2838 @defvar ERLANG_INSTALL_LIB_DIR
2839 @ovindex ERLANG_INSTALL_LIB_DIR
2840 @acindex{ERLANG_SUBST_INSTALL_LIB_DIR}
2841 The common parent directory of Erlang library installation directories.
2842 This variable is set by calling the @code{AC_ERLANG_SUBST_INSTALL_LIB_DIR}
2843 macro in @file{configure.ac}.
2844 @end defvar
2846 @defvar ERLANG_INSTALL_LIB_DIR_@var{library}
2847 @ovindex ERLANG_INSTALL_LIB_DIR_@var{library}
2848 @acindex{ERLANG_SUBST_INSTALL_LIB_SUBDIR}
2849 The installation directory for Erlang library @var{library}.
2850 This variable is set by using the
2851 @samp{AC_ERLANG_SUBST_INSTALL_LIB_SUBDIR}
2852 macro in @file{configure.ac}.
2853 @end defvar
2855 @xref{Erlang Libraries}, for details.
2858 @node Changed Directory Variables
2859 @subsection Changed Directory Variables
2860 @cindex @file{datarootdir}
2862 In Autoconf 2.60, the set of directory variables has changed, and the
2863 defaults of some variables have been adjusted
2864 (@pxref{Installation Directory Variables}) to changes in the
2865 @acronym{GNU} Coding Standards.  Notably, @file{datadir}, @file{infodir}, and
2866 @file{mandir} are now expressed in terms of @file{datarootdir}.  If you are
2867 upgrading from an earlier Autoconf version, you may need to adjust your files
2868 to ensure that the directory variables are substituted correctly
2869 (@pxref{Defining Directories}), and that a definition of @file{datarootdir} is
2870 in place.  For example, in a @file{Makefile.in}, adding
2872 @example
2873 datarootdir = @@datarootdir@@
2874 @end example
2876 @noindent
2877 is usually sufficient.  If you use Automake to create @file{Makefile.in},
2878 it will add this for you.
2880 To help with the transition, Autoconf warns about files that seem to use
2881 @code{datarootdir} without defining it.  In some cases, it then expands
2882 the value of @code{$datarootdir} in substitutions of the directory
2883 variables.  The following example shows such a warning:
2885 @example
2886 $ @kbd{cat configure.ac}
2887 AC_INIT
2888 AC_CONFIG_FILES([Makefile])
2889 AC_OUTPUT
2890 $ @kbd{cat Makefile.in}
2891 prefix = @@prefix@@
2892 datadir = @@datadir@@
2893 $ @kbd{autoconf}
2894 $ @kbd{configure}
2895 configure: creating ./config.status
2896 config.status: creating Makefile
2897 config.status: WARNING:
2898                Makefile.in seems to ignore the --datarootdir setting
2899 $ @kbd{cat Makefile}
2900 prefix = /usr/local
2901 datadir = $@{prefix@}/share
2902 @end example
2904 Usually one can easily change the file to accommodate both older and newer
2905 Autoconf releases:
2907 @example
2908 $ @kbd{cat Makefile.in}
2909 prefix = @@prefix@@
2910 datarootdir = @@datarootdir@@
2911 datadir = @@datadir@@
2912 $ @kbd{configure}
2913 configure: creating ./config.status
2914 config.status: creating Makefile
2915 $ @kbd{cat Makefile}
2916 prefix = /usr/local
2917 datarootdir = $@{prefix@}/share
2918 datadir = $@{datarootdir@}
2919 @end example
2921 @acindex{DATAROOTDIR_CHECKED}
2922 In some cases, however, the checks may not be able to detect that a suitable
2923 initialization of @code{datarootdir} is in place, or they may fail to detect
2924 that such an initialization is necessary in the output file.  If, after
2925 auditing your package, there are still spurious @file{configure} warnings about
2926 @code{datarootdir}, you may add the line
2928 @example
2929 AC_DEFUN([AC_DATAROOTDIR_CHECKED])
2930 @end example
2932 @noindent
2933 to your @file{configure.ac} to disable the warnings.  This is an exception
2934 to the usual rule that you should not define a macro whose name begins with
2935 @code{AC_} (@pxref{Macro Names}).
2939 @node Build Directories
2940 @subsection Build Directories
2941 @cindex Build directories
2942 @cindex Directories, build
2944 You can support compiling a software package for several architectures
2945 simultaneously from the same copy of the source code.  The object files
2946 for each architecture are kept in their own directory.
2948 To support doing this, @command{make} uses the @code{VPATH} variable to
2949 find the files that are in the source directory.  @acronym{GNU} Make
2950 can do this.  Most other recent @command{make} programs can do this as
2951 well, though they may have difficulties and it is often simpler to
2952 recommend @acronym{GNU} @command{make} (@pxref{VPATH and Make}).  Older
2953 @command{make} programs do not support @code{VPATH}; when using them, the
2954 source code must be in the same directory as the object files.
2956 If you are using @acronym{GNU} Automake, the remaining details in this
2957 section are already covered for you, based on the contents of your
2958 @file{Makefile.am}.  But if you are using Autoconf in isolation, then
2959 supporting @code{VPATH} requires the following in your
2960 @file{Makefile.in}:
2962 @example
2963 srcdir = @@srcdir@@
2964 VPATH = @@srcdir@@
2965 @end example
2967 Do not set @code{VPATH} to the value of another variable (@pxref{Variables
2968 listed in VPATH}.
2970 @command{configure} substitutes the correct value for @code{srcdir} when
2971 it produces @file{Makefile}.
2973 Do not use the @command{make} variable @code{$<}, which expands to the
2974 file name of the file in the source directory (found with @code{VPATH}),
2975 except in implicit rules.  (An implicit rule is one such as @samp{.c.o},
2976 which tells how to create a @file{.o} file from a @file{.c} file.)  Some
2977 versions of @command{make} do not set @code{$<} in explicit rules; they
2978 expand it to an empty value.
2980 Instead, Make command lines should always refer to source
2981 files by prefixing them with @samp{$(srcdir)/}.  For example:
2983 @example
2984 time.info: time.texinfo
2985         $(MAKEINFO) '$(srcdir)/time.texinfo'
2986 @end example
2988 @node Automatic Remaking
2989 @subsection Automatic Remaking
2990 @cindex Automatic remaking
2991 @cindex Remaking automatically
2993 You can put rules like the following in the top-level @file{Makefile.in}
2994 for a package to automatically update the configuration information when
2995 you change the configuration files.  This example includes all of the
2996 optional files, such as @file{aclocal.m4} and those related to
2997 configuration header files.  Omit from the @file{Makefile.in} rules for
2998 any of these files that your package does not use.
3000 The @samp{$(srcdir)/} prefix is included because of limitations in the
3001 @code{VPATH} mechanism.
3003 The @file{stamp-} files are necessary because the timestamps of
3004 @file{config.h.in} and @file{config.h} are not changed if remaking
3005 them does not change their contents.  This feature avoids unnecessary
3006 recompilation.  You should include the file @file{stamp-h.in} in your
3007 package's distribution, so that @command{make} considers
3008 @file{config.h.in} up to date.  Don't use @command{touch}
3009 (@pxref{touch, , Limitations of Usual Tools}); instead, use
3010 @command{echo} (using
3011 @command{date} would cause needless differences, hence @acronym{CVS}
3012 conflicts, etc.).
3014 @example
3015 @group
3016 $(srcdir)/configure: configure.ac aclocal.m4
3017         cd '$(srcdir)' && autoconf
3019 # autoheader might not change config.h.in, so touch a stamp file.
3020 $(srcdir)/config.h.in: stamp-h.in
3021 $(srcdir)/stamp-h.in: configure.ac aclocal.m4
3022         cd '$(srcdir)' && autoheader
3023         echo timestamp > '$(srcdir)/stamp-h.in'
3025 config.h: stamp-h
3026 stamp-h: config.h.in config.status
3027         ./config.status
3029 Makefile: Makefile.in config.status
3030         ./config.status
3032 config.status: configure
3033         ./config.status --recheck
3034 @end group
3035 @end example
3037 @noindent
3038 (Be careful if you copy these lines directly into your makefile, as you
3039 need to convert the indented lines to start with the tab character.)
3041 In addition, you should use
3043 @example
3044 AC_CONFIG_FILES([stamp-h], [echo timestamp > stamp-h])
3045 @end example
3047 @noindent
3048 so @file{config.status} ensures that @file{config.h} is considered up to
3049 date.  @xref{Output}, for more information about @code{AC_OUTPUT}.
3051 @xref{config.status Invocation}, for more examples of handling
3052 configuration-related dependencies.
3054 @node Configuration Headers
3055 @section Configuration Header Files
3056 @cindex Configuration Header
3057 @cindex @file{config.h}
3059 When a package contains more than a few tests that define C preprocessor
3060 symbols, the command lines to pass @option{-D} options to the compiler
3061 can get quite long.  This causes two problems.  One is that the
3062 @command{make} output is hard to visually scan for errors.  More
3063 seriously, the command lines can exceed the length limits of some
3064 operating systems.  As an alternative to passing @option{-D} options to
3065 the compiler, @command{configure} scripts can create a C header file
3066 containing @samp{#define} directives.  The @code{AC_CONFIG_HEADERS}
3067 macro selects this kind of output.  Though it can be called anywhere
3068 between @code{AC_INIT} and @code{AC_OUTPUT}, it is customary to call
3069 it right after @code{AC_INIT}.
3071 The package should @samp{#include} the configuration header file before
3072 any other header files, to prevent inconsistencies in declarations (for
3073 example, if it redefines @code{const}).
3075 To provide for VPATH builds, remember to pass the C compiler a @option{-I.}
3076 option (or @option{-I..}; whichever directory contains @file{config.h}).
3077 Even if you use @samp{#include "config.h"}, the preprocessor searches only
3078 the directory of the currently read file, i.e., the source directory, not
3079 the build directory.
3081 With the appropriate @option{-I} option, you can use
3082 @samp{#include <config.h>}.  Actually, it's a good habit to use it,
3083 because in the rare case when the source directory contains another
3084 @file{config.h}, the build directory should be searched first.
3087 @defmac AC_CONFIG_HEADERS (@var{header} @dots{}, @ovar{cmds}, @ovar{init-cmds})
3088 @acindex{CONFIG_HEADERS}
3089 @cvindex HAVE_CONFIG_H
3090 This macro is one of the instantiating macros; see @ref{Configuration
3091 Actions}.  Make @code{AC_OUTPUT} create the file(s) in the
3092 blank-or-newline-separated list @var{header} containing C preprocessor
3093 @code{#define} statements, and replace @samp{@@DEFS@@} in generated
3094 files with @option{-DHAVE_CONFIG_H} instead of the value of @code{DEFS}.
3095 The usual name for @var{header} is @file{config.h}.
3097 If @var{header} already exists and its contents are identical to what
3098 @code{AC_OUTPUT} would put in it, it is left alone.  Doing this allows
3099 making some changes in the configuration without needlessly causing
3100 object files that depend on the header file to be recompiled.
3102 Usually the input file is named @file{@var{header}.in}; however, you can
3103 override the input file name by appending to @var{header} a
3104 colon-separated list of input files.  For example, you might need to make
3105 the input file name acceptable to @acronym{DOS} variants:
3107 @example
3108 AC_CONFIG_HEADERS([config.h:config.hin])
3109 @end example
3111 @end defmac
3113 @defmac AH_HEADER
3114 @ahindex{HEADER}
3115 This macro is defined as the name of the first declared config header
3116 and undefined if no config headers have been declared up to this point.
3117 A third-party macro may, for example, require use of a config header
3118 without invoking AC_CONFIG_HEADERS twice, like this:
3120 @example
3121 AC_CONFIG_COMMANDS_PRE(
3122         [m4_ifndef([AH_HEADER], [AC_CONFIG_HEADERS([config.h])])])
3123 @end example
3125 @end defmac
3127 @xref{Configuration Actions}, for more details on @var{header}.
3129 @menu
3130 * Header Templates::            Input for the configuration headers
3131 * autoheader Invocation::       How to create configuration templates
3132 * Autoheader Macros::           How to specify CPP templates
3133 @end menu
3135 @node Header Templates
3136 @subsection Configuration Header Templates
3137 @cindex Configuration Header Template
3138 @cindex Header templates
3139 @cindex @file{config.h.in}
3141 Your distribution should contain a template file that looks as you want
3142 the final header file to look, including comments, with @code{#undef}
3143 statements which are used as hooks.  For example, suppose your
3144 @file{configure.ac} makes these calls:
3146 @example
3147 AC_CONFIG_HEADERS([conf.h])
3148 AC_CHECK_HEADERS([unistd.h])
3149 @end example
3151 @noindent
3152 Then you could have code like the following in @file{conf.h.in}.
3153 The @file{conf.h} created by @command{configure} defines @samp{HAVE_UNISTD_H}
3154 to 1, if and only if the system has @file{unistd.h}.
3156 @example
3157 @group
3158 /* Define as 1 if you have unistd.h.  */
3159 #undef HAVE_UNISTD_H
3160 @end group
3161 @end example
3163 The format of the template file is stricter than what the C preprocessor
3164 is required to accept.  A directive line should contain only whitespace,
3165 @samp{#undef}, and @samp{HAVE_UNISTD_H}.  The use of @samp{#define}
3166 instead of @samp{#undef}, or of comments on the same line as
3167 @samp{#undef}, is strongly discouraged.  Each hook should only be listed
3168 once.  Other preprocessor lines, such as @samp{#ifdef} or
3169 @samp{#include}, are copied verbatim from the template into the
3170 generated header.
3172 Since it is a tedious task to keep a template header up to date, you may
3173 use @command{autoheader} to generate it, see @ref{autoheader Invocation}.
3175 During the instantiation of the header, each @samp{#undef} line in the
3176 template file for each symbol defined by @samp{AC_DEFINE} is changed to an
3177 appropriate @samp{#define}. If the corresponding @samp{AC_DEFINE} has not
3178 been executed during the @command{configure} run, the @samp{#undef} line is
3179 commented out.  (This is important, e.g., for @samp{_POSIX_SOURCE}:
3180 on many systems, it can be implicitly defined by the compiler, and
3181 undefining it in the header would then break compilation of subsequent
3182 headers.)
3184 Currently, @emph{all} remaining @samp{#undef} lines in the header
3185 template are commented out, whether or not there was a corresponding
3186 @samp{AC_DEFINE} for the macro name; but this behavior is not guaranteed
3187 for future releases of Autoconf.
3189 Generally speaking, since you should not use @samp{#define}, and you
3190 cannot guarantee whether a @samp{#undef} directive in the header
3191 template will be converted to a @samp{#define} or commented out in the
3192 generated header file, the template file cannot be used for conditional
3193 definition effects.  Consequently, if you need to use the construct
3195 @example
3196 @group
3197 #ifdef THIS
3198 # define THAT
3199 #endif
3200 @end group
3201 @end example
3203 @noindent
3204 you must place it outside of the template.
3205 If you absolutely need to hook it to the config header itself, please put
3206 the directives to a separate file, and @samp{#include} that file from the
3207 config header template.  If you are using @command{autoheader}, you would
3208 probably use @samp{AH_BOTTOM} to append the @samp{#include} directive.
3211 @node autoheader Invocation
3212 @subsection Using @command{autoheader} to Create @file{config.h.in}
3213 @cindex @command{autoheader}
3215 The @command{autoheader} program can create a template file of C
3216 @samp{#define} statements for @command{configure} to use.
3217 It searches for the first invocation of @code{AC_CONFIG_HEADERS} in
3218 @file{configure} sources to determine the name of the template.
3219 (If the first call of @code{AC_CONFIG_HEADERS} specifies more than one
3220 input file name, @command{autoheader} uses the first one.)
3222 It is recommended that only one input file is used.  If you want to append
3223 a boilerplate code, it is preferable to use
3224 @samp{AH_BOTTOM([#include <conf_post.h>])}.
3225 File @file{conf_post.h} is not processed during the configuration then,
3226 which make things clearer.  Analogically, @code{AH_TOP} can be used to
3227 prepend a boilerplate code.
3229 In order to do its job, @command{autoheader} needs you to document all
3230 of the symbols that you might use.  Typically this is done via an
3231 @code{AC_DEFINE} or @code{AC_DEFINE_UNQUOTED} call whose first argument
3232 is a literal symbol and whose third argument describes the symbol
3233 (@pxref{Defining Symbols}).  Alternatively, you can use
3234 @code{AH_TEMPLATE} (@pxref{Autoheader Macros}), or you can supply a
3235 suitable input file for a subsequent configuration header file.
3236 Symbols defined by Autoconf's builtin tests are already documented properly;
3237 you need to document only those that you
3238 define yourself.
3240 You might wonder why @command{autoheader} is needed: after all, why
3241 would @command{configure} need to ``patch'' a @file{config.h.in} to
3242 produce a @file{config.h} instead of just creating @file{config.h} from
3243 scratch?  Well, when everything rocks, the answer is just that we are
3244 wasting our time maintaining @command{autoheader}: generating
3245 @file{config.h} directly is all that is needed.  When things go wrong,
3246 however, you'll be thankful for the existence of @command{autoheader}.
3248 The fact that the symbols are documented is important in order to
3249 @emph{check} that @file{config.h} makes sense.  The fact that there is a
3250 well-defined list of symbols that should be defined (or not) is
3251 also important for people who are porting packages to environments where
3252 @command{configure} cannot be run: they just have to @emph{fill in the
3253 blanks}.
3255 But let's come back to the point: the invocation of @command{autoheader}@dots{}
3257 If you give @command{autoheader} an argument, it uses that file instead
3258 of @file{configure.ac} and writes the header file to the standard output
3259 instead of to @file{config.h.in}.  If you give @command{autoheader} an
3260 argument of @option{-}, it reads the standard input instead of
3261 @file{configure.ac} and writes the header file to the standard output.
3263 @command{autoheader} accepts the following options:
3265 @table @option
3266 @item --help
3267 @itemx -h
3268 Print a summary of the command line options and exit.
3270 @item --version
3271 @itemx -V
3272 Print the version number of Autoconf and exit.
3274 @item --verbose
3275 @itemx -v
3276 Report processing steps.
3278 @item --debug
3279 @itemx -d
3280 Don't remove the temporary files.
3282 @item --force
3283 @itemx -f
3284 Remake the template file even if newer than its input files.
3286 @item --include=@var{dir}
3287 @itemx -I @var{dir}
3288 Append @var{dir} to the include path.  Multiple invocations accumulate.
3290 @item --prepend-include=@var{dir}
3291 @itemx -B @var{dir}
3292 Prepend @var{dir} to the include path.  Multiple invocations accumulate.
3294 @item --warnings=@var{category}
3295 @itemx -W @var{category}
3296 @evindex WARNINGS
3297 Report the warnings related to @var{category} (which can actually be a
3298 comma separated list).  Current categories include:
3300 @table @samp
3301 @item obsolete
3302 report the uses of obsolete constructs
3304 @item all
3305 report all the warnings
3307 @item none
3308 report none
3310 @item error
3311 treats warnings as errors
3313 @item no-@var{category}
3314 disable warnings falling into @var{category}
3315 @end table
3317 @end table
3321 @node Autoheader Macros
3322 @subsection Autoheader Macros
3323 @cindex Autoheader macros
3325 @command{autoheader} scans @file{configure.ac} and figures out which C
3326 preprocessor symbols it might define.  It knows how to generate
3327 templates for symbols defined by @code{AC_CHECK_HEADERS},
3328 @code{AC_CHECK_FUNCS} etc., but if you @code{AC_DEFINE} any additional
3329 symbol, you must define a template for it.  If there are missing
3330 templates, @command{autoheader} fails with an error message.
3332 The template for a @var{symbol} is created
3333 by @command{autoheader} from
3334 the @var{description} argument to an @code{AC_DEFINE};
3335 see @ref{Defining Symbols}.
3337 For special needs, you can use the following macros.
3340 @defmac AH_TEMPLATE (@var{key}, @var{description})
3341 @ahindex{TEMPLATE}
3342 Tell @command{autoheader} to generate a template for @var{key}.  This macro
3343 generates standard templates just like @code{AC_DEFINE} when a
3344 @var{description} is given.
3346 For example:
3348 @example
3349 AH_TEMPLATE([CRAY_STACKSEG_END],
3350             [Define to one of _getb67, GETB67, getb67
3351              for Cray-2 and Cray-YMP systems.  This
3352              function is required for alloca.c support
3353              on those systems.])
3354 @end example
3356 @noindent
3357 generates the following template, with the description properly
3358 justified.
3360 @example
3361 /* Define to one of _getb67, GETB67, getb67 for Cray-2 and
3362    Cray-YMP systems.  This function is required for alloca.c
3363    support on those systems.  */
3364 #undef CRAY_STACKSEG_END
3365 @end example
3366 @end defmac
3369 @defmac AH_VERBATIM (@var{key}, @var{template})
3370 @ahindex{VERBATIM}
3371 Tell @command{autoheader} to include the @var{template} as-is in the header
3372 template file.  This @var{template} is associated with the @var{key},
3373 which is used to sort all the different templates and guarantee their
3374 uniqueness.  It should be a symbol that can be defined via @code{AC_DEFINE}.
3375 @end defmac
3378 @defmac AH_TOP (@var{text})
3379 @ahindex{TOP}
3380 Include @var{text} at the top of the header template file.
3381 @end defmac
3384 @defmac AH_BOTTOM (@var{text})
3385 @ahindex{BOTTOM}
3386 Include @var{text} at the bottom of the header template file.
3387 @end defmac
3390 Please note that @var{text} gets included ``verbatim'' to the template file,
3391 not to the resulting config header, so it can easily get mangled when the
3392 template is processed.  There is rarely a need for something other than
3394 @example
3395 AH_BOTTOM([#include <custom.h>])
3396 @end example
3400 @node Configuration Commands
3401 @section Running Arbitrary Configuration Commands
3402 @cindex Configuration commands
3403 @cindex Commands for configuration
3405 You can execute arbitrary commands before, during, and after
3406 @file{config.status} is run.  The three following macros accumulate the
3407 commands to run when they are called multiple times.
3408 @code{AC_CONFIG_COMMANDS} replaces the obsolete macro
3409 @code{AC_OUTPUT_COMMANDS}; see @ref{Obsolete Macros}, for details.
3411 @anchor{AC_CONFIG_COMMANDS}
3412 @defmac AC_CONFIG_COMMANDS (@var{tag}@dots{}, @ovar{cmds}, @ovar{init-cmds})
3413 @acindex{CONFIG_COMMANDS}
3414 Specify additional shell commands to run at the end of
3415 @file{config.status}, and shell commands to initialize any variables
3416 from @command{configure}.  Associate the commands with @var{tag}.
3417 Since typically the @var{cmds} create a file, @var{tag} should
3418 naturally be the name of that file.  If needed, the directory hosting
3419 @var{tag} is created.  This macro is one of the instantiating macros;
3420 see @ref{Configuration Actions}.
3422 Here is an unrealistic example:
3423 @example
3424 fubar=42
3425 AC_CONFIG_COMMANDS([fubar],
3426                    [echo this is extra $fubar, and so on.],
3427                    [fubar=$fubar])
3428 @end example
3430 Here is a better one:
3431 @example
3432 AC_CONFIG_COMMANDS([timestamp], [date >timestamp])
3433 @end example
3434 @end defmac
3436 The following two macros look similar, but in fact they are not of the same
3437 breed: they are executed directly by @file{configure}, so you cannot use
3438 @file{config.status} to rerun them.
3440 @c Yet it is good to leave them here.  The user sees them together and
3441 @c decides which best fits their needs.
3443 @defmac AC_CONFIG_COMMANDS_PRE (@var{cmds})
3444 @acindex{CONFIG_COMMANDS_PRE}
3445 Execute the @var{cmds} right before creating @file{config.status}.
3447 This macro presents the last opportunity to call @code{AC_SUBST},
3448 @code{AC_DEFINE}, or @code{AC_CONFIG_@var{ITEMS}} macros.
3449 @end defmac
3451 @defmac AC_CONFIG_COMMANDS_POST (@var{cmds})
3452 @acindex{CONFIG_COMMANDS_POST}
3453 Execute the @var{cmds} right after creating @file{config.status}.
3454 @end defmac
3459 @node Configuration Links
3460 @section Creating Configuration Links
3461 @cindex Configuration links
3462 @cindex Links for configuration
3464 You may find it convenient to create links whose destinations depend upon
3465 results of tests.  One can use @code{AC_CONFIG_COMMANDS} but the
3466 creation of relative symbolic links can be delicate when the package is
3467 built in a directory different from the source directory.
3469 @anchor{AC_CONFIG_LINKS}
3470 @defmac AC_CONFIG_LINKS (@var{dest}:@var{source}@dots{}, @ovar{cmds}, @
3471   @ovar{init-cmds})
3472 @acindex{CONFIG_LINKS}
3473 @cindex Links
3474 Make @code{AC_OUTPUT} link each of the existing files @var{source} to
3475 the corresponding link name @var{dest}.  Makes a symbolic link if
3476 possible, otherwise a hard link if possible, otherwise a copy.  The
3477 @var{dest} and @var{source} names should be relative to the top level
3478 source or build directory.  This macro is one of the instantiating
3479 macros; see @ref{Configuration Actions}.
3481 For example, this call:
3483 @example
3484 AC_CONFIG_LINKS([host.h:config/$machine.h
3485                 object.h:config/$obj_format.h])
3486 @end example
3488 @noindent
3489 creates in the current directory @file{host.h} as a link to
3490 @file{@var{srcdir}/config/$machine.h}, and @file{object.h} as a
3491 link to @file{@var{srcdir}/config/$obj_format.h}.
3493 The tempting value @samp{.} for @var{dest} is invalid: it makes it
3494 impossible for @samp{config.status} to guess the links to establish.
3496 One can then run:
3497 @example
3498 ./config.status host.h object.h
3499 @end example
3500 @noindent
3501 to create the links.
3502 @end defmac
3506 @node Subdirectories
3507 @section Configuring Other Packages in Subdirectories
3508 @cindex Configure subdirectories
3509 @cindex Subdirectory configure
3511 In most situations, calling @code{AC_OUTPUT} is sufficient to produce
3512 makefiles in subdirectories.  However, @command{configure} scripts
3513 that control more than one independent package can use
3514 @code{AC_CONFIG_SUBDIRS} to run @command{configure} scripts for other
3515 packages in subdirectories.
3517 @defmac AC_CONFIG_SUBDIRS (@var{dir} @dots{})
3518 @acindex{CONFIG_SUBDIRS}
3519 @ovindex subdirs
3520 Make @code{AC_OUTPUT} run @command{configure} in each subdirectory
3521 @var{dir} in the given blank-or-newline-separated list.  Each @var{dir} should
3522 be a literal, i.e., please do not use:
3524 @example
3525 if test "x$package_foo_enabled" = xyes; then
3526   $my_subdirs="$my_subdirs foo"
3528 AC_CONFIG_SUBDIRS([$my_subdirs])
3529 @end example
3531 @noindent
3532 because this prevents @samp{./configure --help=recursive} from
3533 displaying the options of the package @code{foo}.  Instead, you should
3534 write:
3536 @example
3537 if test "x$package_foo_enabled" = xyes; then
3538   AC_CONFIG_SUBDIRS([foo])
3540 @end example
3542 If a given @var{dir} is not found, an error is reported: if the
3543 subdirectory is optional, write:
3545 @example
3546 if test -d "$srcdir/foo"; then
3547   AC_CONFIG_SUBDIRS([foo])
3549 @end example
3551 @c NB: Yes, below we mean configure.in, not configure.ac.
3552 If a given @var{dir} contains @command{configure.gnu}, it is run instead
3553 of @command{configure}.  This is for packages that might use a
3554 non-Autoconf script @command{Configure}, which can't be called through a
3555 wrapper @command{configure} since it would be the same file on
3556 case-insensitive file systems.  Likewise, if a @var{dir} contains
3557 @file{configure.in} but no @command{configure}, the Cygnus
3558 @command{configure} script found by @code{AC_CONFIG_AUX_DIR} is used.
3560 The subdirectory @command{configure} scripts are given the same command
3561 line options that were given to this @command{configure} script, with minor
3562 changes if needed, which include:
3564 @itemize @minus
3565 @item
3566 adjusting a relative name for the cache file;
3568 @item
3569 adjusting a relative name for the source directory;
3571 @item
3572 propagating the current value of @code{$prefix}, including if it was
3573 defaulted, and if the default values of the top level and of the subdirectory
3574 @file{configure} differ.
3575 @end itemize
3577 This macro also sets the output variable @code{subdirs} to the list of
3578 directories @samp{@var{dir} @dots{}}.  Make rules can use
3579 this variable to determine which subdirectories to recurse into.
3581 This macro may be called multiple times.
3582 @end defmac
3584 @node Default Prefix
3585 @section Default Prefix
3586 @cindex Install prefix
3587 @cindex Prefix for install
3589 By default, @command{configure} sets the prefix for files it installs to
3590 @file{/usr/local}.  The user of @command{configure} can select a different
3591 prefix using the @option{--prefix} and @option{--exec-prefix} options.
3592 There are two ways to change the default: when creating
3593 @command{configure}, and when running it.
3595 Some software packages might want to install in a directory other than
3596 @file{/usr/local} by default.  To accomplish that, use the
3597 @code{AC_PREFIX_DEFAULT} macro.
3599 @defmac AC_PREFIX_DEFAULT (@var{prefix})
3600 @acindex{PREFIX_DEFAULT}
3601 Set the default installation prefix to @var{prefix} instead of
3602 @file{/usr/local}.
3603 @end defmac
3605 It may be convenient for users to have @command{configure} guess the
3606 installation prefix from the location of a related program that they
3607 have already installed.  If you wish to do that, you can call
3608 @code{AC_PREFIX_PROGRAM}.
3610 @anchor{AC_PREFIX_PROGRAM}
3611 @defmac AC_PREFIX_PROGRAM (@var{program})
3612 @acindex{PREFIX_PROGRAM}
3613 If the user did not specify an installation prefix (using the
3614 @option{--prefix} option), guess a value for it by looking for
3615 @var{program} in @env{PATH}, the way the shell does.  If @var{program}
3616 is found, set the prefix to the parent of the directory containing
3617 @var{program}, else default the prefix as described above
3618 (@file{/usr/local} or @code{AC_PREFIX_DEFAULT}).  For example, if
3619 @var{program} is @code{gcc} and the @env{PATH} contains
3620 @file{/usr/local/gnu/bin/gcc}, set the prefix to @file{/usr/local/gnu}.
3621 @end defmac
3625 @c ======================================================== Existing tests
3627 @node Existing Tests
3628 @chapter Existing Tests
3630 These macros test for particular system features that packages might
3631 need or want to use.  If you need to test for a kind of feature that
3632 none of these macros check for, you can probably do it by calling
3633 primitive test macros with appropriate arguments (@pxref{Writing
3634 Tests}).
3636 These tests print messages telling the user which feature they're
3637 checking for, and what they find.  They cache their results for future
3638 @command{configure} runs (@pxref{Caching Results}).
3640 Some of these macros set output variables.  @xref{Makefile
3641 Substitutions}, for how to get their values.  The phrase ``define
3642 @var{name}'' is used below as a shorthand to mean ``define the C
3643 preprocessor symbol @var{name} to the value 1''.  @xref{Defining
3644 Symbols}, for how to get those symbol definitions into your program.
3646 @menu
3647 * Common Behavior::             Macros' standard schemes
3648 * Alternative Programs::        Selecting between alternative programs
3649 * Files::                       Checking for the existence of files
3650 * Libraries::                   Library archives that might be missing
3651 * Library Functions::           C library functions that might be missing
3652 * Header Files::                Header files that might be missing
3653 * Declarations::                Declarations that may be missing
3654 * Structures::                  Structures or members that might be missing
3655 * Types::                       Types that might be missing
3656 * Compilers and Preprocessors::  Checking for compiling programs
3657 * System Services::             Operating system services
3658 * Posix Variants::              Special kludges for specific Posix variants
3659 * Erlang Libraries::            Checking for the existence of Erlang libraries
3660 @end menu
3662 @node Common Behavior
3663 @section Common Behavior
3664 @cindex Common autoconf behavior
3666 Much effort has been expended to make Autoconf easy to learn.  The most
3667 obvious way to reach this goal is simply to enforce standard interfaces
3668 and behaviors, avoiding exceptions as much as possible.  Because of
3669 history and inertia, unfortunately, there are still too many exceptions
3670 in Autoconf; nevertheless, this section describes some of the common
3671 rules.
3673 @menu
3674 * Standard Symbols::            Symbols defined by the macros
3675 * Default Includes::            Includes used by the generic macros
3676 @end menu
3678 @node Standard Symbols
3679 @subsection Standard Symbols
3680 @cindex Standard symbols
3682 All the generic macros that @code{AC_DEFINE} a symbol as a result of
3683 their test transform their @var{argument} values to a standard alphabet.
3684 First, @var{argument} is converted to upper case and any asterisks
3685 (@samp{*}) are each converted to @samp{P}.  Any remaining characters
3686 that are not alphanumeric are converted to underscores.
3688 For instance,
3690 @example
3691 AC_CHECK_TYPES([struct $Expensive*])
3692 @end example
3694 @noindent
3695 defines the symbol @samp{HAVE_STRUCT__EXPENSIVEP} if the check
3696 succeeds.
3699 @node Default Includes
3700 @subsection Default Includes
3701 @cindex Default includes
3702 @cindex Includes, default
3704 Several tests depend upon a set of header files.  Since these headers
3705 are not universally available, tests actually have to provide a set of
3706 protected includes, such as:
3708 @example
3709 @group
3710 #ifdef TIME_WITH_SYS_TIME
3711 # include <sys/time.h>
3712 # include <time.h>
3713 #else
3714 # ifdef HAVE_SYS_TIME_H
3715 #  include <sys/time.h>
3716 # else
3717 #  include <time.h>
3718 # endif
3719 #endif
3720 @end group
3721 @end example
3723 @noindent
3724 Unless you know exactly what you are doing, you should avoid using
3725 unconditional includes, and check the existence of the headers you
3726 include beforehand (@pxref{Header Files}).
3728 Most generic macros use the following macro to provide the default set
3729 of includes:
3731 @defmac AC_INCLUDES_DEFAULT (@ovar{include-directives})
3732 @acindex{INCLUDES_DEFAULT}
3733 Expand to @var{include-directives} if defined, otherwise to:
3735 @example
3736 @group
3737 #include <stdio.h>
3738 #ifdef HAVE_SYS_TYPES_H
3739 # include <sys/types.h>
3740 #endif
3741 #ifdef HAVE_SYS_STAT_H
3742 # include <sys/stat.h>
3743 #endif
3744 #ifdef STDC_HEADERS
3745 # include <stdlib.h>
3746 # include <stddef.h>
3747 #else
3748 # ifdef HAVE_STDLIB_H
3749 #  include <stdlib.h>
3750 # endif
3751 #endif
3752 #ifdef HAVE_STRING_H
3753 # if !defined STDC_HEADERS && defined HAVE_MEMORY_H
3754 #  include <memory.h>
3755 # endif
3756 # include <string.h>
3757 #endif
3758 #ifdef HAVE_STRINGS_H
3759 # include <strings.h>
3760 #endif
3761 #ifdef HAVE_INTTYPES_H
3762 # include <inttypes.h>
3763 #endif
3764 #ifdef HAVE_STDINT_H
3765 # include <stdint.h>
3766 #endif
3767 #ifdef HAVE_UNISTD_H
3768 # include <unistd.h>
3769 #endif
3770 @end group
3771 @end example
3773 If the default includes are used, then check for the presence of these
3774 headers and their compatibility, i.e., you don't need to run
3775 @code{AC_HEADER_STDC}, nor check for @file{stdlib.h} etc.
3777 These headers are checked for in the same order as they are included.
3778 For instance, on some systems @file{string.h} and @file{strings.h} both
3779 exist, but conflict.  Then @code{HAVE_STRING_H} is defined, not
3780 @code{HAVE_STRINGS_H}.
3781 @end defmac
3783 @node Alternative Programs
3784 @section Alternative Programs
3785 @cindex Programs, checking
3787 These macros check for the presence or behavior of particular programs.
3788 They are used to choose between several alternative programs and to
3789 decide what to do once one has been chosen.  If there is no macro
3790 specifically defined to check for a program you need, and you don't need
3791 to check for any special properties of it, then you can use one of the
3792 general program-check macros.
3794 @menu
3795 * Particular Programs::         Special handling to find certain programs
3796 * Generic Programs::            How to find other programs
3797 @end menu
3799 @node Particular Programs
3800 @subsection Particular Program Checks
3802 These macros check for particular programs---whether they exist, and
3803 in some cases whether they support certain features.
3805 @defmac AC_PROG_AWK
3806 @acindex{PROG_AWK}
3807 @ovindex AWK
3808 Check for @code{gawk}, @code{mawk}, @code{nawk}, and @code{awk}, in that
3809 order, and set output variable @code{AWK} to the first one that is found.
3810 It tries @code{gawk} first because that is reported to be the
3811 best implementation.
3812 @end defmac
3814 @defmac AC_PROG_GREP
3815 @acindex{PROG_GREP}
3816 @ovindex GREP
3817 Look for the best available @code{grep} or @code{ggrep} that accepts the
3818 longest input lines possible, and that supports multiple @option{-e} options.
3819 Set the output variable @code{GREP} to whatever is chosen.
3820 @xref{grep, , Limitations of Usual Tools}, for more information about
3821 portability problems with the @command{grep} command family.
3822 @end defmac
3824 @defmac AC_PROG_EGREP
3825 @acindex{PROG_EGREP}
3826 @ovindex EGREP
3827 Check whether @code{$GREP -E} works, or else look for the best available
3828 @code{egrep} or @code{gegrep} that accepts the longest input lines possible.
3829 Set the output variable @code{EGREP} to whatever is chosen.
3830 @end defmac
3832 @defmac AC_PROG_FGREP
3833 @acindex{PROG_FGREP}
3834 @ovindex FGREP
3835 Check whether @code{$GREP -F} works, or else look for the best available
3836 @code{fgrep} or @code{gfgrep} that accepts the longest input lines possible.
3837 Set the output variable @code{FGREP} to whatever is chosen.
3838 @end defmac
3840 @defmac AC_PROG_INSTALL
3841 @acindex{PROG_INSTALL}
3842 @ovindex INSTALL
3843 @ovindex INSTALL_PROGRAM
3844 @ovindex INSTALL_DATA
3845 @ovindex INSTALL_SCRIPT
3846 Set output variable @code{INSTALL} to the name of a @acronym{BSD}-compatible
3847 @command{install} program, if one is found in the current @env{PATH}.
3848 Otherwise, set @code{INSTALL} to @samp{@var{dir}/install-sh -c},
3849 checking the directories specified to @code{AC_CONFIG_AUX_DIR} (or its
3850 default directories) to determine @var{dir} (@pxref{Output}).  Also set
3851 the variables @code{INSTALL_PROGRAM} and @code{INSTALL_SCRIPT} to
3852 @samp{$@{INSTALL@}} and @code{INSTALL_DATA} to @samp{$@{INSTALL@} -m 644}.
3854 @samp{@@INSTALL@@} is special, as its value may vary for different
3855 configuration files.
3857 This macro screens out various instances of @command{install} known not to
3858 work.  It prefers to find a C program rather than a shell script, for
3859 speed.  Instead of @file{install-sh}, it can also use @file{install.sh},
3860 but that name is obsolete because some @command{make} programs have a rule
3861 that creates @file{install} from it if there is no makefile.  Further, this
3862 macro requires @command{install} to be able to install multiple files into a
3863 target directory in a single invocation.
3865 Autoconf comes with a copy of @file{install-sh} that you can use.  If
3866 you use @code{AC_PROG_INSTALL}, you must include either
3867 @file{install-sh} or @file{install.sh} in your distribution; otherwise
3868 @command{configure} produces an error message saying it can't find
3869 them---even if the system you're on has a good @command{install} program.
3870 This check is a safety measure to prevent you from accidentally leaving
3871 that file out, which would prevent your package from installing on
3872 systems that don't have a @acronym{BSD}-compatible @command{install} program.
3874 If you need to use your own installation program because it has features
3875 not found in standard @command{install} programs, there is no reason to use
3876 @code{AC_PROG_INSTALL}; just put the file name of your program into your
3877 @file{Makefile.in} files.
3878 @end defmac
3880 @defmac AC_PROG_MKDIR_P
3881 @acindex{PROG_MKDIR_P}
3882 @ovindex MKDIR_P
3883 Set output variable @code{MKDIR_P} to a program that ensures that for
3884 each argument, a directory named by this argument exists, creating it
3885 and its parent directories if needed, and without race conditions when
3886 two instances of the program attempt to make the same directory at
3887 nearly the same time.
3889 This macro uses the @samp{mkdir -p} command if possible.  Otherwise, it
3890 falls back on invoking @command{install-sh} with the @option{-d} option,
3891 so your package should
3892 contain @file{install-sh} as described under @code{AC_PROG_INSTALL}.
3893 An @file{install-sh} file that predates Autoconf 2.60 or Automake 1.10
3894 is vulnerable to race conditions, so if you want to support parallel
3895 installs from
3896 different packages into the same directory you need to make sure you
3897 have an up-to-date @file{install-sh}.  In particular, be careful about
3898 using @samp{autoreconf -if} if your Automake predates Automake 1.10.
3900 This macro is related to the @code{AS_MKDIR_P} macro (@pxref{Programming
3901 in M4sh}), but it sets an output variable intended for use in other
3902 files, whereas @code{AS_MKDIR_P} is intended for use in scripts like
3903 @command{configure}.  Also, @code{AS_MKDIR_P} does not accept options,
3904 but @code{MKDIR_P} supports the @option{-m} option, e.g., a makefile
3905 might invoke @code{$(MKDIR_P) -m 0 dir} to create an inaccessible
3906 directory, and conversely a makefile should use @code{$(MKDIR_P) --
3907 $(FOO)} if @var{FOO} might yield a value that begins with @samp{-}.
3908 Finally, @code{AS_MKDIR_P} does not check for race condition
3909 vulnerability, whereas @code{AC_PROG_MKDIR_P} does.
3911 @samp{@@MKDIR_P@@} is special, as its value may vary for different
3912 configuration files.
3913 @end defmac
3915 @anchor{AC_PROG_LEX}
3916 @defmac AC_PROG_LEX
3917 @acindex{PROG_LEX}
3918 @ovindex LEX
3919 @ovindex LEXLIB
3920 @cvindex YYTEXT_POINTER
3921 @ovindex LEX_OUTPUT_ROOT
3922 If @code{flex} is found, set output variable @code{LEX} to @samp{flex}
3923 and @code{LEXLIB} to @option{-lfl}, if that library is in a standard
3924 place.  Otherwise set @code{LEX} to @samp{lex} and @code{LEXLIB} to
3925 @option{-ll}, if found.  If neither variant is available, set @code{LEX}
3926 to @samp{:}; for packages that ship the generated @file{file.yy.c}
3927 alongside the source @file{file.l}, this default allows users without a
3928 lexer generator to still build the package even if the timestamp for
3929 @file{file.l} is inadvertantly changed.
3931 Define @code{YYTEXT_POINTER} if @code{yytext} defaults to @samp{char *} instead
3932 of to @samp{char []}.  Also set output variable @code{LEX_OUTPUT_ROOT} to
3933 the base of the file name that the lexer generates; usually
3934 @file{lex.yy}, but sometimes something else.  These results vary
3935 according to whether @code{lex} or @code{flex} is being used.
3937 You are encouraged to use Flex in your sources, since it is both more
3938 pleasant to use than plain Lex and the C source it produces is portable.
3939 In order to ensure portability, however, you must either provide a
3940 function @code{yywrap} or, if you don't use it (e.g., your scanner has
3941 no @samp{#include}-like feature), simply include a @samp{%noyywrap}
3942 statement in the scanner's source.  Once this done, the scanner is
3943 portable (unless @emph{you} felt free to use nonportable constructs) and
3944 does not depend on any library.  In this case, and in this case only, it
3945 is suggested that you use this Autoconf snippet:
3947 @example
3948 AC_PROG_LEX
3949 if test "x$LEX" != xflex; then
3950   LEX="$SHELL $missing_dir/missing flex"
3951   AC_SUBST([LEX_OUTPUT_ROOT], [lex.yy])
3952   AC_SUBST([LEXLIB], [''])
3954 @end example
3956 The shell script @command{missing} can be found in the Automake
3957 distribution.
3959 Remember that the user may have supplied an alternate location in
3960 @env{LEX}, so if Flex is required, it is better to check that the user
3961 provided something sufficient by parsing the output of @samp{$LEX
3962 --version} than by simply relying on @code{test "x$LEX" = xflex}.
3964 To ensure backward compatibility, Automake's @code{AM_PROG_LEX} invokes
3965 (indirectly) this macro twice, which causes an annoying but benign
3966 ``@code{AC_PROG_LEX} invoked multiple times'' warning.  Future versions
3967 of Automake will fix this issue; meanwhile, just ignore this message.
3969 As part of running the test, this macro may delete any file in the
3970 configuration directory named @file{lex.yy.c} or @file{lexyy.c}.
3971 @end defmac
3973 @anchor{AC_PROG_LN_S}
3974 @defmac AC_PROG_LN_S
3975 @acindex{PROG_LN_S}
3976 @ovindex LN_S
3977 If @samp{ln -s} works on the current file system (the operating system
3978 and file system support symbolic links), set the output variable
3979 @code{LN_S} to @samp{ln -s}; otherwise, if @samp{ln} works, set
3980 @code{LN_S} to @samp{ln}, and otherwise set it to @samp{cp -p}.
3982 If you make a link in a directory other than the current directory, its
3983 meaning depends on whether @samp{ln} or @samp{ln -s} is used.  To safely
3984 create links using @samp{$(LN_S)}, either find out which form is used
3985 and adjust the arguments, or always invoke @code{ln} in the directory
3986 where the link is to be created.
3988 In other words, it does not work to do:
3989 @example
3990 $(LN_S) foo /x/bar
3991 @end example
3993 Instead, do:
3995 @example
3996 (cd /x && $(LN_S) foo bar)
3997 @end example
3998 @end defmac
4000 @defmac AC_PROG_RANLIB
4001 @acindex{PROG_RANLIB}
4002 @ovindex RANLIB
4003 Set output variable @code{RANLIB} to @samp{ranlib} if @code{ranlib}
4004 is found, and otherwise to @samp{:} (do nothing).
4005 @end defmac
4007 @defmac AC_PROG_SED
4008 @acindex{PROG_SED}
4009 @ovindex SED
4010 Set output variable @code{SED} to a Sed implementation that conforms to
4011 Posix and does not have arbitrary length limits.  Report an error if no
4012 acceptable Sed is found.  @xref{sed, , Limitations of Usual Tools}, for more
4013 information about portability problems with Sed.
4014 @end defmac
4016 @defmac AC_PROG_YACC
4017 @acindex{PROG_YACC}
4018 @evindex YACC
4019 @evindex YFLAGS
4020 @ovindex YACC
4021 If @code{bison} is found, set output variable @code{YACC} to @samp{bison
4022 -y}.  Otherwise, if @code{byacc} is found, set @code{YACC} to
4023 @samp{byacc}.  Otherwise set @code{YACC} to @samp{yacc}.
4024 @end defmac
4026 @node Generic Programs
4027 @subsection Generic Program and File Checks
4029 These macros are used to find programs not covered by the ``particular''
4030 test macros.  If you need to check the behavior of a program as well as
4031 find out whether it is present, you have to write your own test for it
4032 (@pxref{Writing Tests}).  By default, these macros use the environment
4033 variable @env{PATH}.  If you need to check for a program that might not
4034 be in the user's @env{PATH}, you can pass a modified path to use
4035 instead, like this:
4037 @example
4038 AC_PATH_PROG([INETD], [inetd], [/usr/libexec/inetd],
4039              [$PATH$PATH_SEPARATOR/usr/libexec$PATH_SEPARATOR]dnl
4040 [/usr/sbin$PATH_SEPARATOR/usr/etc$PATH_SEPARATOR/etc])
4041 @end example
4043 You are strongly encouraged to declare the @var{variable} passed to
4044 @code{AC_CHECK_PROG} etc.@: as precious, @xref{Setting Output Variables},
4045 @code{AC_ARG_VAR}, for more details.
4047 @anchor{AC_CHECK_PROG}
4048 @defmac AC_CHECK_PROG (@var{variable}, @var{prog-to-check-for}, @
4049   @var{value-if-found}, @ovar{value-if-not-found}, @dvar{path, $PATH}, @
4050   @ovar{reject})
4051 @acindex{CHECK_PROG}
4052 Check whether program @var{prog-to-check-for} exists in @var{path}.  If
4053 it is found, set @var{variable} to @var{value-if-found}, otherwise to
4054 @var{value-if-not-found}, if given.  Always pass over @var{reject} (an
4055 absolute file name) even if it is the first found in the search path; in
4056 that case, set @var{variable} using the absolute file name of the
4057 @var{prog-to-check-for} found that is not @var{reject}.  If
4058 @var{variable} was already set, do nothing.  Calls @code{AC_SUBST} for
4059 @var{variable}.
4060 @end defmac
4062 @anchor{AC_CHECK_PROGS}
4063 @defmac AC_CHECK_PROGS (@var{variable}, @var{progs-to-check-for}, @
4064   @ovar{value-if-not-found}, @dvar{path, $PATH})
4065 @acindex{CHECK_PROGS}
4066 Check for each program in the blank-separated list
4067 @var{progs-to-check-for} existing in the @var{path}.  If one is found, set
4068 @var{variable} to the name of that program.  Otherwise, continue
4069 checking the next program in the list.  If none of the programs in the
4070 list are found, set @var{variable} to @var{value-if-not-found}; if
4071 @var{value-if-not-found} is not specified, the value of @var{variable}
4072 is not changed.  Calls @code{AC_SUBST} for @var{variable}.
4073 @end defmac
4075 @defmac AC_CHECK_TARGET_TOOL (@var{variable}, @var{prog-to-check-for}, @
4076   @ovar{value-if-not-found}, @dvar{path, $PATH})
4077 @acindex{CHECK_TARGET_TOOL}
4078 Like @code{AC_CHECK_PROG}, but first looks for @var{prog-to-check-for}
4079 with a prefix of the target type as determined by
4080 @code{AC_CANONICAL_TARGET}, followed by a dash (@pxref{Canonicalizing}).
4081 If the tool cannot be found with a prefix, and if the build and target
4082 types are equal, then it is also searched for without a prefix.
4084 As noted in @ref{Specifying Target Triplets}, the
4085 target is rarely specified, because most of the time it is the same
4086 as the host: it is the type of system for which any compiler tool in
4087 the package produces code.  What this macro looks for is,
4088 for example, @emph{a tool @r{(assembler, linker, etc.)}@: that the
4089 compiler driver @r{(@command{gcc} for the @acronym{GNU} C Compiler)}
4090 uses to produce objects, archives or executables}.
4091 @end defmac
4093 @defmac AC_CHECK_TOOL (@var{variable}, @var{prog-to-check-for}, @
4094   @ovar{value-if-not-found}, @dvar{path, $PATH})
4095 @acindex{CHECK_TOOL}
4096 Like @code{AC_CHECK_PROG}, but first looks for @var{prog-to-check-for}
4097 with a prefix of the host type as specified by @option{--host}, followed by a
4098 dash.  For example, if the user runs
4099 @samp{configure --build=x86_64-gnu --host=i386-gnu}, then this call:
4100 @example
4101 AC_CHECK_TOOL([RANLIB], [ranlib], [:])
4102 @end example
4103 @noindent
4104 sets @code{RANLIB} to @file{i386-gnu-ranlib} if that program exists in
4105 @var{path}, or otherwise to @samp{ranlib} if that program exists in
4106 @var{path}, or to @samp{:} if neither program exists.
4108 When cross-compiling, this macro will issue a warning if no program
4109 prefixed with the host type could be found.
4110 For more information, see @ref{Specifying Target Triplets}.
4111 @end defmac
4113 @defmac AC_CHECK_TARGET_TOOLS (@var{variable}, @var{progs-to-check-for}, @
4114   @ovar{value-if-not-found}, @dvar{path, $PATH})
4115 @acindex{CHECK_TARGET_TOOLS}
4116 Like @code{AC_CHECK_TARGET_TOOL}, each of the tools in the list
4117 @var{progs-to-check-for} are checked with a prefix of the target type as
4118 determined by @code{AC_CANONICAL_TARGET}, followed by a dash
4119 (@pxref{Canonicalizing}).  If none of the tools can be found with a
4120 prefix, and if the build and target types are equal, then the first one
4121 without a prefix is used.  If a tool is found, set @var{variable} to
4122 the name of that program.  If none of the tools in the list are found,
4123 set @var{variable} to @var{value-if-not-found}; if @var{value-if-not-found}
4124 is not specified, the value of @var{variable} is not changed.  Calls
4125 @code{AC_SUBST} for @var{variable}.
4126 @end defmac
4128 @defmac AC_CHECK_TOOLS (@var{variable}, @var{progs-to-check-for}, @
4129   @ovar{value-if-not-found}, @dvar{path, $PATH})
4130 @acindex{CHECK_TOOLS}
4131 Like @code{AC_CHECK_TOOL}, each of the tools in the list
4132 @var{progs-to-check-for} are checked with a prefix of the host type as
4133 determined by @code{AC_CANONICAL_HOST}, followed by a dash
4134 (@pxref{Canonicalizing}).  If none of the tools can be found with a
4135 prefix, then the first one without a prefix is used.  If a tool is found,
4136 set @var{variable} to the name of that program.  If none of the tools in
4137 the list are found, set @var{variable} to @var{value-if-not-found}; if
4138 @var{value-if-not-found} is not specified, the value of @var{variable}
4139 is not changed.  Calls @code{AC_SUBST} for @var{variable}.
4141 When cross-compiling, this macro will issue a warning if no program
4142 prefixed with the host type could be found.
4143 For more information, see @ref{Specifying Target Triplets}.
4144 @end defmac
4146 @anchor{AC_PATH_PROG}
4147 @defmac AC_PATH_PROG (@var{variable}, @var{prog-to-check-for}, @
4148   @ovar{value-if-not-found}, @dvar{path, $PATH})
4149 @acindex{PATH_PROG}
4150 Like @code{AC_CHECK_PROG}, but set @var{variable} to the absolute
4151 name of @var{prog-to-check-for} if found.
4152 @end defmac
4154 @anchor{AC_PATH_PROGS}
4155 @defmac AC_PATH_PROGS (@var{variable}, @var{progs-to-check-for}, @
4156   @ovar{value-if-not-found}, @dvar{path, $PATH})
4157 @acindex{PATH_PROGS}
4158 Like @code{AC_CHECK_PROGS}, but if any of @var{progs-to-check-for}
4159 are found, set @var{variable} to the absolute name of the program
4160 found.
4161 @end defmac
4163 @defmac AC_PATH_PROGS_FEATURE_CHECK (@var{variable}, @
4164   @var{progs-to-check-for}, @var{feature-test}, @
4165   @ovar{action-if-not-found}, @dvar{path, $PATH})
4166 @acindex{PATH_PROGS_FEATURE_CHECK}
4167 This macro was introduced in Autoconf 2.62.  If @var{variable} is not
4168 empty, then set the cache variable @code{$ac_cv_path_@var{variable}} to
4169 its value.  Otherwise, check for each program in the blank-separated
4170 list @var{progs-to-check-for} existing in @var{path}.  For each program
4171 found, execute @var{feature-test} with @code{$ac_path_@var{variable}}
4172 set to the absolute name of the candidate program.  If no invocation of
4173 @var{feature-test} sets the shell variable
4174 @code{$ac_cv_path_@var{variable}}, then @var{action-if-not-found} is
4175 executed.  @var{feature-test} will be run even when
4176 @code{ac_cv_path_@var{variable}} is set, to provide the ability to
4177 choose a better candidate found later in @var{path}; to accept the
4178 current setting and bypass all futher checks, @var{feature-test} can
4179 execute @code{ac_path_@var{variable}_found=:}.
4181 Note that this macro has some subtle differences from
4182 @code{AC_CHECK_PROGS}.  It is designed to be run inside
4183 @code{AC_CACHE_VAL}, therefore, it should have no side effects.  In
4184 particular, @var{variable} is not set to the final value of
4185 @code{ac_cv_path_@var{variable}}, nor is @code{AC_SUBST} automatically
4186 run.  Also, on failure, any action can be performed, whereas
4187 @code{AC_CHECK_PROGS} only performs
4188 @code{@var{variable}=@var{value-if-not-found}}.
4190 Here is an example, similar to what Autoconf uses in its own configure
4191 script.  It will search for an implementation of @command{m4} that
4192 supports the @code{indir} builtin, even if it goes by the name
4193 @command{gm4} or is not the first implementation on @env{PATH}.
4195 @example
4196 AC_CACHE_CHECK([for m4 that supports indir], [ac_cv_path_M4],
4197   [AC_PATH_PROGS_FEATURE_CHECK([M4], [m4 gm4],
4198     [[m4out=`echo 'changequote([,])indir([divnum])' | $ac_path_M4`
4199       test "x$m4out" = x0 \
4200       && ac_cv_path_M4=$ac_path_M4 ac_path_M4_found=:]],
4201     [AC_MSG_ERROR([could not find m4 that supports indir])])])
4202 AC_SUBST([M4], [$ac_cv_path_M4])
4203 @end example
4204 @end defmac
4206 @defmac AC_PATH_TARGET_TOOL (@var{variable}, @var{prog-to-check-for}, @
4207   @ovar{value-if-not-found}, @dvar{path, $PATH})
4208 @acindex{PATH_TARGET_TOOL}
4209 Like @code{AC_CHECK_TARGET_TOOL}, but set @var{variable} to the absolute
4210 name of the program if it is found.
4211 @end defmac
4213 @defmac AC_PATH_TOOL (@var{variable}, @var{prog-to-check-for}, @
4214   @ovar{value-if-not-found}, @dvar{path, $PATH})
4215 @acindex{PATH_TOOL}
4216 Like @code{AC_CHECK_TOOL}, but set @var{variable} to the absolute
4217 name of the program if it is found.
4219 When cross-compiling, this macro will issue a warning if no program
4220 prefixed with the host type could be found.
4221 For more information, see @ref{Specifying Target Triplets}.
4222 @end defmac
4225 @node Files
4226 @section Files
4227 @cindex File, checking
4229 You might also need to check for the existence of files.  Before using
4230 these macros, ask yourself whether a runtime test might not be a better
4231 solution.  Be aware that, like most Autoconf macros, they test a feature
4232 of the host machine, and therefore, they die when cross-compiling.
4234 @defmac AC_CHECK_FILE (@var{file}, @ovar{action-if-found}, @
4235   @ovar{action-if-not-found})
4236 @acindex{CHECK_FILE}
4237 Check whether file @var{file} exists on the native system.  If it is
4238 found, execute @var{action-if-found}, otherwise do
4239 @var{action-if-not-found}, if given.
4240 @end defmac
4242 @defmac AC_CHECK_FILES (@var{files}, @ovar{action-if-found}, @
4243   @ovar{action-if-not-found})
4244 @acindex{CHECK_FILES}
4245 Executes @code{AC_CHECK_FILE} once for each file listed in @var{files}.
4246 Additionally, defines @samp{HAVE_@var{file}} (@pxref{Standard Symbols})
4247 for each file found.
4248 @end defmac
4251 @node Libraries
4252 @section Library Files
4253 @cindex Library, checking
4255 The following macros check for the presence of certain C, C++, or Fortran
4256 library archive files.
4258 @anchor{AC_CHECK_LIB}
4259 @defmac AC_CHECK_LIB (@var{library}, @var{function}, @
4260   @ovar{action-if-found}, @ovar{action-if-not-found}, @ovar{other-libraries})
4261 @acindex{CHECK_LIB}
4262 Test whether the library @var{library} is available by trying to link
4263 a test program that calls function @var{function} with the library.
4264 @var{function} should be a function provided by the library.
4265 Use the base
4266 name of the library; e.g., to check for @option{-lmp}, use @samp{mp} as
4267 the @var{library} argument.
4269 @var{action-if-found} is a list of shell commands to run if the link
4270 with the library succeeds; @var{action-if-not-found} is a list of shell
4271 commands to run if the link fails.  If @var{action-if-found} is not
4272 specified, the default action prepends @option{-l@var{library}} to
4273 @code{LIBS} and defines @samp{HAVE_LIB@var{library}} (in all
4274 capitals).  This macro is intended to support building @code{LIBS} in
4275 a right-to-left (least-dependent to most-dependent) fashion such that
4276 library dependencies are satisfied as a natural side effect of
4277 consecutive tests.  Linkers are sensitive to library ordering
4278 so the order in which @code{LIBS} is generated is important to reliable
4279 detection of libraries.
4281 If linking with @var{library} results in unresolved symbols that would
4282 be resolved by linking with additional libraries, give those libraries
4283 as the @var{other-libraries} argument, separated by spaces:
4284 e.g., @option{-lXt -lX11}.  Otherwise, this macro fails to detect
4285 that @var{library} is present, because linking the test program
4286 always fails with unresolved symbols.  The @var{other-libraries} argument
4287 should be limited to cases where it is desirable to test for one library
4288 in the presence of another that is not already in @code{LIBS}.
4290 @code{AC_CHECK_LIB} requires some care in usage, and should be avoided
4291 in some common cases.  Many standard functions like @code{gethostbyname}
4292 appear in the standard C library on some hosts, and in special libraries
4293 like @code{nsl} on other hosts.  On some hosts the special libraries
4294 contain variant implementations that you may not want to use.  These
4295 days it is normally better to use @code{AC_SEARCH_LIBS([gethostbyname],
4296 [nsl])} instead of @code{AC_CHECK_LIB([nsl], [gethostbyname])}.
4297 @end defmac
4299 @anchor{AC_SEARCH_LIBS}
4300 @defmac AC_SEARCH_LIBS (@var{function}, @var{search-libs}, @
4301   @ovar{action-if-found}, @ovar{action-if-not-found}, @ovar{other-libraries})
4302 @acindex{SEARCH_LIBS}
4303 Search for a library defining @var{function} if it's not already
4304 available.  This equates to calling
4305 @samp{AC_LINK_IFELSE([AC_LANG_CALL([], [@var{function}])])} first with
4306 no libraries, then for each library listed in @var{search-libs}.
4308 Add @option{-l@var{library}} to @code{LIBS} for the first library found
4309 to contain @var{function}, and run @var{action-if-found}.  If the
4310 function is not found, run @var{action-if-not-found}.
4312 If linking with @var{library} results in unresolved symbols that would
4313 be resolved by linking with additional libraries, give those libraries
4314 as the @var{other-libraries} argument, separated by spaces:
4315 e.g., @option{-lXt -lX11}.  Otherwise, this macro fails to detect
4316 that @var{function} is present, because linking the test program
4317 always fails with unresolved symbols.
4318 @end defmac
4322 @node Library Functions
4323 @section Library Functions
4325 The following macros check for particular C library functions.
4326 If there is no macro specifically defined to check for a function you need,
4327 and you don't need to check for any special properties of
4328 it, then you can use one of the general function-check macros.
4330 @menu
4331 * Function Portability::        Pitfalls with usual functions
4332 * Particular Functions::        Special handling to find certain functions
4333 * Generic Functions::           How to find other functions
4334 @end menu
4336 @node Function Portability
4337 @subsection Portability of C Functions
4338 @cindex Portability of C functions
4339 @cindex C function portability
4341 Most usual functions can either be missing, or be buggy, or be limited
4342 on some architectures.  This section tries to make an inventory of these
4343 portability issues.  By definition, this list always requires
4344 additions.  Please help us keeping it as complete as possible.
4346 @table @asis
4347 @item @code{exit}
4348 @c @fuindex exit
4349 @prindex @code{exit}
4350 On ancient hosts, @code{exit} returned @code{int}.
4351 This is because @code{exit} predates @code{void}, and there was a long
4352 tradition of it returning @code{int}.
4354 On current hosts, the problem more likely is that @code{exit} is not
4355 declared, due to C++ problems of some sort or another.  For this reason
4356 we suggest that test programs not invoke @code{exit}, but return from
4357 @code{main} instead.
4359 @item @code{free}
4360 @c @fuindex free
4361 @prindex @code{free}
4362 The C standard says a call @code{free (NULL)} does nothing, but
4363 some old systems don't support this (e.g., NextStep).
4365 @item @code{isinf}
4366 @itemx @code{isnan}
4367 @c @fuindex isinf
4368 @c @fuindex isnan
4369 @prindex @code{isinf}
4370 @prindex @code{isnan}
4371 The C99 standard says that @code{isinf} and @code{isnan} are
4372 macros.  On some systems just macros are available
4373 (e.g., @acronym{HP-UX} and Solaris 10), on
4374 some systems both macros and functions (e.g., glibc 2.3.2), and on some
4375 systems only functions (e.g., IRIX 6 and Solaris 9).  In some cases
4376 these functions are declared in nonstandard headers like
4377 @code{<sunmath.h>} and defined in non-default libraries like
4378 @option{-lm} or @option{-lsunmath}.
4380 The C99 @code{isinf} and @code{isnan} macros work correctly with
4381 @code{long double} arguments, but pre-C99 systems that use functions
4382 typically assume @code{double} arguments.  On such a system,
4383 @code{isinf} incorrectly returns true for a finite @code{long double}
4384 argument that is outside the range of @code{double}.
4386 The best workaround for these issues is to use gnulib modules
4387 @code{isinf} and @code{isnan} (@pxref{Gnulib}).  But a lighter weight
4388 solution involves code like the following.
4390 @smallexample
4391 #include <math.h>
4393 #ifndef isnan
4394 # define isnan(x) \
4395     (sizeof (x) == sizeof (long double) ? isnan_ld (x) \
4396      : sizeof (x) == sizeof (double) ? isnan_d (x) \
4397      : isnan_f (x))
4398 static inline int isnan_f  (float       x) @{ return x != x; @}
4399 static inline int isnan_d  (double      x) @{ return x != x; @}
4400 static inline int isnan_ld (long double x) @{ return x != x; @}
4401 #endif
4403 #ifndef isinf
4404 # define isinf(x) \
4405     (sizeof (x) == sizeof (long double) ? isinf_ld (x) \
4406      : sizeof (x) == sizeof (double) ? isinf_d (x) \
4407      : isinf_f (x))
4408 static inline int isinf_f  (float       x)
4409 @{ return !isnan (x) && isnan (x - x); @}
4410 static inline int isinf_d  (double      x)
4411 @{ return !isnan (x) && isnan (x - x); @}
4412 static inline int isinf_ld (long double x)
4413 @{ return !isnan (x) && isnan (x - x); @}
4414 #endif
4415 @end smallexample
4417 Use @code{AC_C_INLINE} (@pxref{C Compiler}) so that this code works on
4418 compilers that lack the @code{inline} keyword.  Some optimizing
4419 compilers mishandle these definitions, but systems with that bug
4420 typically have many other floating point corner-case compliance problems
4421 anyway, so it's probably not worth worrying about.
4423 @item @code{malloc}
4424 @c @fuindex malloc
4425 @prindex @code{malloc}
4426 The C standard says a call @code{malloc (0)} is implementation
4427 dependent.  It can return either @code{NULL} or a new non-null pointer.
4428 The latter is more common (e.g., the @acronym{GNU} C Library) but is by
4429 no means universal.  @code{AC_FUNC_MALLOC}
4430 can be used to insist on non-@code{NULL} (@pxref{Particular Functions}).
4432 @item @code{putenv}
4433 @c @fuindex putenv
4434 @prindex @code{putenv}
4435 Posix prefers @code{setenv} to @code{putenv}; among other things,
4436 @code{putenv} is not required of all Posix implementations, but
4437 @code{setenv} is.
4439 Posix specifies that @code{putenv} puts the given string directly in
4440 @code{environ}, but some systems make a copy of it instead (e.g.,
4441 glibc 2.0, or @acronym{BSD}).  And when a copy is made, @code{unsetenv} might
4442 not free it, causing a memory leak (e.g., Free@acronym{BSD} 4).
4444 On some systems @code{putenv ("FOO")} removes @samp{FOO} from the
4445 environment, but this is not standard usage and it dumps core
4446 on some systems (e.g., AIX).
4448 On MinGW, a call @code{putenv ("FOO=")} removes @samp{FOO} from the
4449 environment, rather than inserting it with an empty value.
4451 @item @code{realloc}
4452 @c @fuindex realloc
4453 @prindex @code{realloc}
4454 The C standard says a call @code{realloc (NULL, size)} is equivalent
4455 to @code{malloc (size)}, but some old systems don't support this (e.g.,
4456 NextStep).
4458 @item @code{signal} handler
4459 @c @fuindex signal
4460 @prindex @code{signal}
4461 @prindex @code{sigaction}
4462 Normally @code{signal} takes a handler function with a return type of
4463 @code{void}, but some old systems required @code{int} instead.  Any
4464 actual @code{int} value returned is not used; this is only a
4465 difference in the function prototype demanded.
4467 All systems we know of in current use return @code{void}.  The
4468 @code{int} was to support K&R C, where of course @code{void} is not
4469 available.  The obsolete macro @code{AC_TYPE_SIGNAL}
4470 (@pxref{AC_TYPE_SIGNAL}) can be used to establish the correct type in
4471 all cases.
4473 In most cases, it is more robust to use @code{sigaction} when it is
4474 available, rather than @code{signal}.
4476 @item @code{snprintf}
4477 @c @fuindex snprintf
4478 @prindex @code{snprintf}
4479 @c @fuindex vsnprintf
4480 @prindex @code{vsnprintf}
4481 The C99 standard says that if the output array isn't big enough
4482 and if no other errors occur, @code{snprintf} and @code{vsnprintf}
4483 truncate the output and return the number of bytes that ought to have
4484 been produced.  Some older systems return the truncated length (e.g.,
4485 @acronym{GNU} C Library 2.0.x or @sc{irix} 6.5), some a negative value
4486 (e.g., earlier @acronym{GNU} C Library versions), and some the buffer
4487 length without truncation (e.g., 32-bit Solaris 7).  Also, some buggy
4488 older systems ignore the length and overrun the buffer (e.g., 64-bit
4489 Solaris 7).
4491 @item @code{sprintf}
4492 @c @fuindex sprintf
4493 @prindex @code{sprintf}
4494 @c @fuindex vsprintf
4495 @prindex @code{vsprintf}
4496 The C standard says @code{sprintf} and @code{vsprintf} return the
4497 number of bytes written.  On some ancient systems (SunOS 4 for
4498 instance) they return the buffer pointer instead, but these no
4499 longer need to be worried about.
4501 @item @code{sscanf}
4502 @c @fuindex sscanf
4503 @prindex @code{sscanf}
4504 On various old systems, e.g., @acronym{HP-UX} 9, @code{sscanf} requires
4505 that its
4506 input string be writable (though it doesn't actually change it).  This
4507 can be a problem when using @command{gcc} since it normally puts
4508 constant strings in read-only memory (@pxref{Incompatibilities,
4509 Incompatibilities of @acronym{GCC}, , gcc, Using and
4510 Porting the @acronym{GNU} Compiler Collection}).  Apparently in some cases even
4511 having format strings read-only can be a problem.
4513 @item @code{strerror_r}
4514 @c @fuindex strerror_r
4515 @prindex @code{strerror_r}
4516 Posix specifies that @code{strerror_r} returns an @code{int}, but many
4517 systems (e.g., @acronym{GNU} C Library version 2.2.4) provide a
4518 different version returning a @code{char *}.  @code{AC_FUNC_STRERROR_R}
4519 can detect which is in use (@pxref{Particular Functions}).
4521 @item @code{strnlen}
4522 @c @fuindex strnlen
4523 @prindex @code{strnlen}
4524 @acronym{AIX} 4.3 provides a broken version which produces the
4525 following results:
4527 @example
4528 strnlen ("foobar", 0) = 0
4529 strnlen ("foobar", 1) = 3
4530 strnlen ("foobar", 2) = 2
4531 strnlen ("foobar", 3) = 1
4532 strnlen ("foobar", 4) = 0
4533 strnlen ("foobar", 5) = 6
4534 strnlen ("foobar", 6) = 6
4535 strnlen ("foobar", 7) = 6
4536 strnlen ("foobar", 8) = 6
4537 strnlen ("foobar", 9) = 6
4538 @end example
4540 @item @code{sysconf}
4541 @c @fuindex sysconf
4542 @prindex @code{sysconf}
4543 @code{_SC_PAGESIZE} is standard, but some older systems (e.g., @acronym{HP-UX}
4544 9) have @code{_SC_PAGE_SIZE} instead.  This can be tested with
4545 @code{#ifdef}.
4547 @item @code{unlink}
4548 @c @fuindex unlink
4549 @prindex @code{unlink}
4550 The Posix spec says that @code{unlink} causes the given file to be
4551 removed only after there are no more open file handles for it.  Some
4552 non-Posix hosts have trouble with this requirement, though,
4553 and some @acronym{DOS} variants even corrupt the file system.
4555 @item @code{unsetenv}
4556 @c @fuindex unsetenv
4557 @prindex @code{unsetenv}
4558 On MinGW, @code{unsetenv} is not available, but a variable @samp{FOO}
4559 can be removed with a call @code{putenv ("FOO=")}, as described under
4560 @code{putenv} above.
4562 @item @code{va_copy}
4563 @c @fuindex va_copy
4564 @prindex @code{va_copy}
4565 The C99 standard provides @code{va_copy} for copying
4566 @code{va_list} variables.  It may be available in older environments
4567 too, though possibly as @code{__va_copy} (e.g., @command{gcc} in strict
4568 pre-C99 mode).  These can be tested with @code{#ifdef}.  A fallback to
4569 @code{memcpy (&dst, &src, sizeof (va_list))} gives maximum
4570 portability.
4572 @item @code{va_list}
4573 @c @fuindex va_list
4574 @prindex @code{va_list}
4575 @code{va_list} is not necessarily just a pointer.  It can be a
4576 @code{struct} (e.g., @command{gcc} on Alpha), which means @code{NULL} is
4577 not portable.  Or it can be an array (e.g., @command{gcc} in some
4578 PowerPC configurations), which means as a function parameter it can be
4579 effectively call-by-reference and library routines might modify the
4580 value back in the caller (e.g., @code{vsnprintf} in the @acronym{GNU} C Library
4581 2.1).
4583 @item Signed @code{>>}
4584 Normally the C @code{>>} right shift of a signed type replicates the
4585 high bit, giving a so-called ``arithmetic'' shift.  But care should be
4586 taken since Standard C doesn't require that behavior.  On those
4587 few processors without a native arithmetic shift (for instance Cray
4588 vector systems) zero bits may be shifted in, the same as a shift of an
4589 unsigned type.
4591 @item Integer @code{/}
4592 C divides signed integers by truncating their quotient toward zero,
4593 yielding the same result as Fortran.  However, before C99 the standard
4594 allowed C implementations to take the floor or ceiling of the quotient
4595 in some cases.  Hardly any implementations took advantage of this
4596 freedom, though, and it's probably not worth worrying about this issue
4597 nowadays.
4598 @end table
4601 @node Particular Functions
4602 @subsection Particular Function Checks
4603 @cindex Function, checking
4605 These macros check for particular C functions---whether they exist, and
4606 in some cases how they respond when given certain arguments.
4608 @anchor{AC_FUNC_ALLOCA}
4609 @defmac AC_FUNC_ALLOCA
4610 @acindex{FUNC_ALLOCA}
4611 @cvindex C_ALLOCA
4612 @cvindex HAVE_ALLOCA_H
4613 @ovindex ALLOCA
4614 @c @fuindex alloca
4615 @prindex @code{alloca}
4616 @hdrindex{alloca.h}
4617 Check how to get @code{alloca}.  Tries to get a builtin version by
4618 checking for @file{alloca.h} or the predefined C preprocessor macros
4619 @code{__GNUC__} and @code{_AIX}.  If this macro finds @file{alloca.h},
4620 it defines @code{HAVE_ALLOCA_H}.
4622 If those attempts fail, it looks for the function in the standard C
4623 library.  If any of those methods succeed, it defines
4624 @code{HAVE_ALLOCA}.  Otherwise, it sets the output variable
4625 @code{ALLOCA} to @samp{$@{LIBOBJDIR@}alloca.o} and defines
4626 @code{C_ALLOCA} (so programs can periodically call @samp{alloca (0)} to
4627 garbage collect).  This variable is separate from @code{LIBOBJS} so
4628 multiple programs can share the value of @code{ALLOCA} without needing
4629 to create an actual library, in case only some of them use the code in
4630 @code{LIBOBJS}.  The @samp{$@{LIBOBJDIR@}} prefix serves the same
4631 purpose as in @code{LIBOBJS} (@pxref{AC_LIBOBJ vs LIBOBJS}).
4633 This macro does not try to get @code{alloca} from the System V R3
4634 @file{libPW} or the System V R4 @file{libucb} because those libraries
4635 contain some incompatible functions that cause trouble.  Some versions
4636 do not even contain @code{alloca} or contain a buggy version.  If you
4637 still want to use their @code{alloca}, use @code{ar} to extract
4638 @file{alloca.o} from them instead of compiling @file{alloca.c}.
4640 Source files that use @code{alloca} should start with a piece of code
4641 like the following, to declare it properly.
4643 @example
4644 @group
4645 #ifdef HAVE_ALLOCA_H
4646 # include <alloca.h>
4647 #elif defined __GNUC__
4648 # define alloca __builtin_alloca
4649 #elif defined _AIX
4650 # define alloca __alloca
4651 #elif defined _MSC_VER
4652 # include <malloc.h>
4653 # define alloca _alloca
4654 #else
4655 # include <stddef.h>
4656 # ifdef  __cplusplus
4657 extern "C"
4658 # endif
4659 void *alloca (size_t);
4660 #endif
4661 @end group
4662 @end example
4663 @end defmac
4665 @defmac AC_FUNC_CHOWN
4666 @acindex{FUNC_CHOWN}
4667 @cvindex HAVE_CHOWN
4668 @c @fuindex chown
4669 @prindex @code{chown}
4670 If the @code{chown} function is available and works (in particular, it
4671 should accept @option{-1} for @code{uid} and @code{gid}), define
4672 @code{HAVE_CHOWN}.
4673 @end defmac
4675 @anchor{AC_FUNC_CLOSEDIR_VOID}
4676 @defmac AC_FUNC_CLOSEDIR_VOID
4677 @acindex{FUNC_CLOSEDIR_VOID}
4678 @cvindex CLOSEDIR_VOID
4679 @c @fuindex closedir
4680 @prindex @code{closedir}
4681 If the @code{closedir} function does not return a meaningful value,
4682 define @code{CLOSEDIR_VOID}.  Otherwise, callers ought to check its
4683 return value for an error indicator.
4685 Currently this test is implemented by running a test program.  When
4686 cross compiling the pessimistic assumption that @code{closedir} does not
4687 return a meaningful value is made.
4689 This macro is obsolescent, as @code{closedir} returns a meaningful value
4690 on current systems.  New programs need not use this macro.
4691 @end defmac
4693 @defmac AC_FUNC_ERROR_AT_LINE
4694 @acindex{FUNC_ERROR_AT_LINE}
4695 @c @fuindex error_at_line
4696 @prindex @code{error_at_line}
4697 If the @code{error_at_line} function is not found, require an
4698 @code{AC_LIBOBJ} replacement of @samp{error}.
4699 @end defmac
4701 @defmac AC_FUNC_FNMATCH
4702 @acindex{FUNC_FNMATCH}
4703 @c @fuindex fnmatch
4704 @prindex @code{fnmatch}
4705 If the @code{fnmatch} function conforms to Posix, define
4706 @code{HAVE_FNMATCH}.  Detect common implementation bugs, for example,
4707 the bugs in Solaris 2.4.
4709 Unlike the other specific
4710 @code{AC_FUNC} macros, @code{AC_FUNC_FNMATCH} does not replace a
4711 broken/missing @code{fnmatch}.  This is for historical reasons.
4712 See @code{AC_REPLACE_FNMATCH} below.
4714 This macro is obsolescent.  New programs should use Gnulib's
4715 @code{fnmatch-posix} module.  @xref{Gnulib}.
4716 @end defmac
4718 @defmac AC_FUNC_FNMATCH_GNU
4719 @acindex{FUNC_FNMATCH_GNU}
4720 @c @fuindex fnmatch
4721 @prindex @code{fnmatch}
4722 Behave like @code{AC_REPLACE_FNMATCH} (@emph{replace}) but also test
4723 whether @code{fnmatch} supports @acronym{GNU} extensions.  Detect common
4724 implementation bugs, for example, the bugs in the @acronym{GNU} C
4725 Library 2.1.
4727 This macro is obsolescent.  New programs should use Gnulib's
4728 @code{fnmatch-gnu} module.  @xref{Gnulib}.
4729 @end defmac
4731 @anchor{AC_FUNC_FORK}
4732 @defmac AC_FUNC_FORK
4733 @acindex{FUNC_FORK}
4734 @cvindex HAVE_VFORK_H
4735 @cvindex HAVE_WORKING_FORK
4736 @cvindex HAVE_WORKING_VFORK
4737 @cvindex vfork
4738 @c @fuindex fork
4739 @prindex @code{fork}
4740 @c @fuindex vfork
4741 @prindex @code{vfork}
4742 @hdrindex{vfork.h}
4743 This macro checks for the @code{fork} and @code{vfork} functions.  If a
4744 working @code{fork} is found, define @code{HAVE_WORKING_FORK}.  This macro
4745 checks whether @code{fork} is just a stub by trying to run it.
4747 If @file{vfork.h} is found, define @code{HAVE_VFORK_H}.  If a working
4748 @code{vfork} is found, define @code{HAVE_WORKING_VFORK}.  Otherwise,
4749 define @code{vfork} to be @code{fork} for backward compatibility with
4750 previous versions of @command{autoconf}.  This macro checks for several known
4751 errors in implementations of @code{vfork} and considers the system to not
4752 have a working @code{vfork} if it detects any of them.  It is not considered
4753 to be an implementation error if a child's invocation of @code{signal}
4754 modifies the parent's signal handler, since child processes rarely change
4755 their signal handlers.
4757 Since this macro defines @code{vfork} only for backward compatibility with
4758 previous versions of @command{autoconf} you're encouraged to define it
4759 yourself in new code:
4760 @example
4761 @group
4762 #ifndef HAVE_WORKING_VFORK
4763 # define vfork fork
4764 #endif
4765 @end group
4766 @end example
4767 @end defmac
4769 @defmac AC_FUNC_FSEEKO
4770 @acindex{FUNC_FSEEKO}
4771 @cvindex _LARGEFILE_SOURCE
4772 @cvindex HAVE_FSEEKO
4773 @c @fuindex fseeko
4774 @prindex @code{fseeko}
4775 @c @fuindex ftello
4776 @prindex @code{ftello}
4777 If the @code{fseeko} function is available, define @code{HAVE_FSEEKO}.
4778 Define @code{_LARGEFILE_SOURCE} if necessary to make the prototype
4779 visible on some systems (e.g., glibc 2.2).  Otherwise linkage problems
4780 may occur when compiling with @code{AC_SYS_LARGEFILE} on
4781 largefile-sensitive systems where @code{off_t} does not default to a
4782 64bit entity.  All systems with @code{fseeko} also supply @code{ftello}.
4783 @end defmac
4785 @defmac AC_FUNC_GETGROUPS
4786 @acindex{FUNC_GETGROUPS}
4787 @cvindex HAVE_GETGROUPS
4788 @ovindex GETGROUPS_LIBS
4789 @c @fuindex getgroups
4790 @prindex @code{getgroups}
4791 If the @code{getgroups} function is available and works (unlike on
4792 Ultrix 4.3, where @samp{getgroups (0, 0)} always fails), define
4793 @code{HAVE_GETGROUPS}.  Set @code{GETGROUPS_LIBS} to any libraries
4794 needed to get that function.  This macro runs @code{AC_TYPE_GETGROUPS}.
4795 @end defmac
4797 @anchor{AC_FUNC_GETLOADAVG}
4798 @defmac AC_FUNC_GETLOADAVG
4799 @acindex{FUNC_GETLOADAVG}
4800 @cvindex SVR4
4801 @cvindex DGUX
4802 @cvindex UMAX
4803 @cvindex UMAX4_3
4804 @cvindex HAVE_NLIST_H
4805 @cvindex NLIST_NAME_UNION
4806 @cvindex GETLOADAVG_PRIVILEGED
4807 @cvindex NEED_SETGID
4808 @cvindex C_GETLOADAVG
4809 @ovindex LIBOBJS
4810 @ovindex NEED_SETGID
4811 @ovindex KMEM_GROUP
4812 @ovindex GETLOADAVG_LIBS
4813 @c @fuindex getloadavg
4814 @prindex @code{getloadavg}
4815 Check how to get the system load averages.  To perform its tests
4816 properly, this macro needs the file @file{getloadavg.c}; therefore, be
4817 sure to set the @code{AC_LIBOBJ} replacement directory properly (see
4818 @ref{Generic Functions}, @code{AC_CONFIG_LIBOBJ_DIR}).
4820 If the system has the @code{getloadavg} function, define
4821 @code{HAVE_GETLOADAVG}, and set @code{GETLOADAVG_LIBS} to any libraries
4822 necessary to get that function.  Also add @code{GETLOADAVG_LIBS} to
4823 @code{LIBS}.  Otherwise, require an @code{AC_LIBOBJ} replacement for
4824 @samp{getloadavg} with source code in @file{@var{dir}/getloadavg.c}, and
4825 possibly define several other C preprocessor macros and output
4826 variables:
4828 @enumerate
4829 @item
4830 Define @code{C_GETLOADAVG}.
4832 @item
4833 Define @code{SVR4}, @code{DGUX}, @code{UMAX}, or @code{UMAX4_3} if on
4834 those systems.
4836 @item
4837 @hdrindex{nlist.h}
4838 If @file{nlist.h} is found, define @code{HAVE_NLIST_H}.
4840 @item
4841 If @samp{struct nlist} has an @samp{n_un.n_name} member, define
4842 @code{HAVE_STRUCT_NLIST_N_UN_N_NAME}.  The obsolete symbol
4843 @code{NLIST_NAME_UNION} is still defined, but do not depend upon it.
4845 @item
4846 Programs may need to be installed set-group-ID (or set-user-ID) for
4847 @code{getloadavg} to work.  In this case, define
4848 @code{GETLOADAVG_PRIVILEGED}, set the output variable @code{NEED_SETGID}
4849 to @samp{true} (and otherwise to @samp{false}), and set
4850 @code{KMEM_GROUP} to the name of the group that should own the installed
4851 program.
4852 @end enumerate
4854 The @code{AC_FUNC_GETLOADAVG} macro is obsolescent.  New programs should
4855 use Gnulib's @code{getloadavg} module.  @xref{Gnulib}.
4856 @end defmac
4858 @anchor{AC_FUNC_GETMNTENT}
4859 @defmac AC_FUNC_GETMNTENT
4860 @acindex{FUNC_GETMNTENT}
4861 @cvindex HAVE_GETMNTENT
4862 @c @fuindex getmntent
4863 @prindex @code{getmntent}
4864 Check for @code{getmntent} in the standard C library, and then in the
4865 @file{sun}, @file{seq}, and @file{gen} libraries, for @sc{unicos},
4866 @sc{irix} 4, @sc{ptx}, and UnixWare, respectively.  Then, if
4867 @code{getmntent} is available, define @code{HAVE_GETMNTENT}.
4868 @end defmac
4870 @defmac AC_FUNC_GETPGRP
4871 @acindex{FUNC_GETPGRP}
4872 @cvindex GETPGRP_VOID
4873 @c @fuindex getpgid
4874 @c @fuindex getpgrp
4875 @prindex @code{getpgid}
4876 @prindex @code{getpgrp}
4877 Define @code{GETPGRP_VOID} if it is an error to pass 0 to
4878 @code{getpgrp}; this is the Posix behavior.  On older @acronym{BSD}
4879 systems, you must pass 0 to @code{getpgrp}, as it takes an argument and
4880 behaves like Posix's @code{getpgid}.
4882 @example
4883 #ifdef GETPGRP_VOID
4884   pid = getpgrp ();
4885 #else
4886   pid = getpgrp (0);
4887 #endif
4888 @end example
4890 This macro does not check whether
4891 @code{getpgrp} exists at all; if you need to work in that situation,
4892 first call @code{AC_CHECK_FUNC} for @code{getpgrp}.
4894 This macro is obsolescent, as current systems have a @code{getpgrp}
4895 whose signature conforms to Posix.  New programs need not use this macro.
4896 @end defmac
4898 @defmac AC_FUNC_LSTAT_FOLLOWS_SLASHED_SYMLINK
4899 @acindex{FUNC_LSTAT_FOLLOWS_SLASHED_SYMLINK}
4900 @cvindex LSTAT_FOLLOWS_SLASHED_SYMLINK
4901 @c @fuindex lstat
4902 @prindex @code{lstat}
4903 If @file{link} is a symbolic link, then @code{lstat} should treat
4904 @file{link/} the same as @file{link/.}.  However, many older
4905 @code{lstat} implementations incorrectly ignore trailing slashes.
4907 It is safe to assume that if @code{lstat} incorrectly ignores
4908 trailing slashes, then other symbolic-link-aware functions like
4909 @code{unlink} also incorrectly ignore trailing slashes.
4911 If @code{lstat} behaves properly, define
4912 @code{LSTAT_FOLLOWS_SLASHED_SYMLINK}, otherwise require an
4913 @code{AC_LIBOBJ} replacement of @code{lstat}.
4914 @end defmac
4916 @defmac AC_FUNC_MALLOC
4917 @acindex{FUNC_MALLOC}
4918 @cvindex HAVE_MALLOC
4919 @cvindex malloc
4920 @c @fuindex malloc
4921 @prindex @code{malloc}
4922 If the @code{malloc} function is compatible with the @acronym{GNU} C
4923 library @code{malloc} (i.e., @samp{malloc (0)} returns a valid
4924 pointer), define @code{HAVE_MALLOC} to 1.  Otherwise define
4925 @code{HAVE_MALLOC} to 0, ask for an @code{AC_LIBOBJ} replacement for
4926 @samp{malloc}, and define @code{malloc} to @code{rpl_malloc} so that the
4927 native @code{malloc} is not used in the main project.
4929 Typically, the replacement file @file{malloc.c} should look like (note
4930 the @samp{#undef malloc}):
4932 @verbatim
4933 #include <config.h>
4934 #undef malloc
4936 #include <sys/types.h>
4938 void *malloc ();
4940 /* Allocate an N-byte block of memory from the heap.
4941    If N is zero, allocate a 1-byte block.  */
4943 void *
4944 rpl_malloc (size_t n)
4946   if (n == 0)
4947     n = 1;
4948   return malloc (n);
4950 @end verbatim
4951 @end defmac
4953 @defmac AC_FUNC_MEMCMP
4954 @acindex{FUNC_MEMCMP}
4955 @ovindex LIBOBJS
4956 @c @fuindex memcmp
4957 @prindex @code{memcmp}
4958 If the @code{memcmp} function is not available, or does not work on
4959 8-bit data (like the one on SunOS 4.1.3), or fails when comparing 16
4960 bytes or more and with at least one buffer not starting on a 4-byte
4961 boundary (such as the one on NeXT x86 OpenStep), require an
4962 @code{AC_LIBOBJ} replacement for @samp{memcmp}.
4964 This macro is obsolescent, as current systems have a working
4965 @code{memcmp}.  New programs need not use this macro.
4966 @end defmac
4968 @defmac AC_FUNC_MBRTOWC
4969 @acindex{FUNC_MBRTOWC}
4970 @cvindex HAVE_MBRTOWC
4971 @c @fuindex mbrtowc
4972 @prindex @code{mbrtowc}
4973 Define @code{HAVE_MBRTOWC} to 1 if the function @code{mbrtowc} and the
4974 type @code{mbstate_t} are properly declared.
4975 @end defmac
4977 @defmac AC_FUNC_MKTIME
4978 @acindex{FUNC_MKTIME}
4979 @ovindex LIBOBJS
4980 @c @fuindex mktime
4981 @prindex @code{mktime}
4982 If the @code{mktime} function is not available, or does not work
4983 correctly, require an @code{AC_LIBOBJ} replacement for @samp{mktime}.
4984 For the purposes of this test, @code{mktime} should conform to the
4985 Posix standard and should be the inverse of
4986 @code{localtime}.
4987 @end defmac
4989 @anchor{AC_FUNC_MMAP}
4990 @defmac AC_FUNC_MMAP
4991 @acindex{FUNC_MMAP}
4992 @cvindex HAVE_MMAP
4993 @c @fuindex mmap
4994 @prindex @code{mmap}
4995 If the @code{mmap} function exists and works correctly, define
4996 @code{HAVE_MMAP}.  This checks only private fixed mapping of already-mapped
4997 memory.
4998 @end defmac
5000 @defmac AC_FUNC_OBSTACK
5001 @acindex{FUNC_OBSTACK}
5002 @cvindex HAVE_OBSTACK
5003 @cindex obstack
5004 If the obstacks are found, define @code{HAVE_OBSTACK}, else require an
5005 @code{AC_LIBOBJ} replacement for @samp{obstack}.
5006 @end defmac
5008 @defmac AC_FUNC_REALLOC
5009 @acindex{FUNC_REALLOC}
5010 @cvindex HAVE_REALLOC
5011 @cvindex realloc
5012 @c @fuindex realloc
5013 @prindex @code{realloc}
5014 If the @code{realloc} function is compatible with the @acronym{GNU} C
5015 library @code{realloc} (i.e., @samp{realloc (NULL, 0)} returns a
5016 valid pointer), define @code{HAVE_REALLOC} to 1.  Otherwise define
5017 @code{HAVE_REALLOC} to 0, ask for an @code{AC_LIBOBJ} replacement for
5018 @samp{realloc}, and define @code{realloc} to @code{rpl_realloc} so that
5019 the native @code{realloc} is not used in the main project.  See
5020 @code{AC_FUNC_MALLOC} for details.
5021 @end defmac
5023 @defmac AC_FUNC_SELECT_ARGTYPES
5024 @acindex{FUNC_SELECT_ARGTYPES}
5025 @cvindex SELECT_TYPE_ARG1
5026 @cvindex SELECT_TYPE_ARG234
5027 @cvindex SELECT_TYPE_ARG5
5028 @c @fuindex select
5029 @prindex @code{select}
5030 Determines the correct type to be passed for each of the
5031 @code{select} function's arguments, and defines those types
5032 in @code{SELECT_TYPE_ARG1}, @code{SELECT_TYPE_ARG234}, and
5033 @code{SELECT_TYPE_ARG5} respectively.  @code{SELECT_TYPE_ARG1} defaults
5034 to @samp{int}, @code{SELECT_TYPE_ARG234} defaults to @samp{int *},
5035 and @code{SELECT_TYPE_ARG5} defaults to @samp{struct timeval *}.
5037 This macro is obsolescent, as current systems have a @code{select} whose
5038 signature conforms to Posix.  New programs need not use this macro.
5039 @end defmac
5041 @defmac AC_FUNC_SETPGRP
5042 @acindex{FUNC_SETPGRP}
5043 @cvindex SETPGRP_VOID
5044 @c @fuindex setpgrp
5045 @prindex @code{setpgrp}
5046 If @code{setpgrp} takes no argument (the Posix version), define
5047 @code{SETPGRP_VOID}.  Otherwise, it is the @acronym{BSD} version, which takes
5048 two process IDs as arguments.  This macro does not check whether
5049 @code{setpgrp} exists at all; if you need to work in that situation,
5050 first call @code{AC_CHECK_FUNC} for @code{setpgrp}.
5052 This macro is obsolescent, as current systems have a @code{setpgrp}
5053 whose signature conforms to Posix.  New programs need not use this macro.
5054 @end defmac
5056 @defmac AC_FUNC_STAT
5057 @defmacx AC_FUNC_LSTAT
5058 @acindex{FUNC_STAT}
5059 @acindex{FUNC_LSTAT}
5060 @cvindex HAVE_STAT_EMPTY_STRING_BUG
5061 @cvindex HAVE_LSTAT_EMPTY_STRING_BUG
5062 @c @fuindex stat
5063 @prindex @code{stat}
5064 @c @fuindex lstat
5065 @prindex @code{lstat}
5066 Determine whether @code{stat} or @code{lstat} have the bug that it
5067 succeeds when given the zero-length file name as argument.  The @code{stat}
5068 and @code{lstat} from SunOS 4.1.4 and the Hurd (as of 1998-11-01) do
5069 this.
5071 If it does, then define @code{HAVE_STAT_EMPTY_STRING_BUG} (or
5072 @code{HAVE_LSTAT_EMPTY_STRING_BUG}) and ask for an @code{AC_LIBOBJ}
5073 replacement of it.
5075 These macros are obsolescent, as no current systems have the bug.
5076 New programs need not use these macros.
5077 @end defmac
5079 @anchor{AC_FUNC_STRCOLL}
5080 @defmac AC_FUNC_STRCOLL
5081 @acindex{FUNC_STRCOLL}
5082 @cvindex HAVE_STRCOLL
5083 @c @fuindex strcoll
5084 @prindex @code{strcoll}
5085 If the @code{strcoll} function exists and works correctly, define
5086 @code{HAVE_STRCOLL}.  This does a bit more than
5087 @samp{AC_CHECK_FUNCS(strcoll)}, because some systems have incorrect
5088 definitions of @code{strcoll} that should not be used.
5089 @end defmac
5091 @defmac AC_FUNC_STRERROR_R
5092 @acindex{FUNC_STRERROR_R}
5093 @cvindex HAVE_STRERROR_R
5094 @cvindex HAVE_DECL_STRERROR_R
5095 @cvindex STRERROR_R_CHAR_P
5096 @c @fuindex strerror_r
5097 @prindex @code{strerror_r}
5098 If @code{strerror_r} is available, define @code{HAVE_STRERROR_R}, and if
5099 it is declared, define @code{HAVE_DECL_STRERROR_R}.  If it returns a
5100 @code{char *} message, define @code{STRERROR_R_CHAR_P}; otherwise it
5101 returns an @code{int} error number.  The Thread-Safe Functions option of
5102 Posix requires @code{strerror_r} to return @code{int}, but
5103 many systems (including, for example, version 2.2.4 of the @acronym{GNU} C
5104 Library) return a @code{char *} value that is not necessarily equal to
5105 the buffer argument.
5106 @end defmac
5108 @anchor{AC_FUNC_STRFTIME}
5109 @defmac AC_FUNC_STRFTIME
5110 @acindex{FUNC_STRFTIME}
5111 @cvindex HAVE_STRFTIME
5112 @c @fuindex strftime
5113 @prindex @code{strftime}
5114 Check for @code{strftime} in the @file{intl} library, for SCO Unix.
5115 Then, if @code{strftime} is available, define @code{HAVE_STRFTIME}.
5117 This macro is obsolescent, as no current systems require the @file{intl}
5118 library for @code{strftime}.  New programs need not use this macro.
5119 @end defmac
5121 @defmac AC_FUNC_STRTOD
5122 @acindex{FUNC_STRTOD}
5123 @ovindex POW_LIB
5124 @c @fuindex strtod
5125 @prindex @code{strtod}
5126 If the @code{strtod} function does not exist or doesn't work correctly,
5127 ask for an @code{AC_LIBOBJ} replacement of @samp{strtod}.  In this case,
5128 because @file{strtod.c} is likely to need @samp{pow}, set the output
5129 variable @code{POW_LIB} to the extra library needed.
5130 @end defmac
5132 @defmac AC_FUNC_STRTOLD
5133 @acindex{FUNC_STRTOLD}
5134 @cvindex HAVE_STRTOLD
5135 @prindex @code{strtold}
5136 If the @code{strtold} function exists and conforms to C99, define
5137 @code{HAVE_STRTOLD}.
5138 @end defmac
5140 @defmac AC_FUNC_STRNLEN
5141 @acindex{FUNC_STRNLEN}
5142 @cvindex HAVE_STRNLEN
5143 @c @fuindex strnlen
5144 @prindex @code{strnlen}
5145 If the @code{strnlen} function is not available, or is buggy (like the one
5146 from @acronym{AIX} 4.3), require an @code{AC_LIBOBJ} replacement for it.
5147 @end defmac
5149 @anchor{AC_FUNC_UTIME_NULL}
5150 @defmac AC_FUNC_UTIME_NULL
5151 @acindex{FUNC_UTIME_NULL}
5152 @cvindex HAVE_UTIME_NULL
5153 @c @fuindex utime
5154 @prindex @code{utime}
5155 If @samp{utime (@var{file}, NULL)} sets @var{file}'s timestamp to
5156 the present, define @code{HAVE_UTIME_NULL}.
5158 This macro is obsolescent, as all current systems have a @code{utime}
5159 that behaves this way.  New programs need not use this macro.
5160 @end defmac
5162 @anchor{AC_FUNC_VPRINTF}
5163 @defmac AC_FUNC_VPRINTF
5164 @acindex{FUNC_VPRINTF}
5165 @cvindex HAVE_VPRINTF
5166 @cvindex HAVE_DOPRNT
5167 @c @fuindex vprintf
5168 @prindex @code{vprintf}
5169 @c @fuindex vsprintf
5170 @prindex @code{vsprintf}
5171 If @code{vprintf} is found, define @code{HAVE_VPRINTF}.  Otherwise, if
5172 @code{_doprnt} is found, define @code{HAVE_DOPRNT}.  (If @code{vprintf}
5173 is available, you may assume that @code{vfprintf} and @code{vsprintf}
5174 are also available.)
5176 This macro is obsolescent, as all current systems have @code{vprintf}.
5177 New programs need not use this macro.
5178 @end defmac
5180 @defmac AC_REPLACE_FNMATCH
5181 @acindex{REPLACE_FNMATCH}
5182 @c @fuindex fnmatch
5183 @prindex @code{fnmatch}
5184 @hdrindex{fnmatch.h}
5185 If the @code{fnmatch} function does not conform to Posix (see
5186 @code{AC_FUNC_FNMATCH}), ask for its @code{AC_LIBOBJ} replacement.
5188 The files @file{fnmatch.c}, @file{fnmatch_loop.c}, and @file{fnmatch_.h}
5189 in the @code{AC_LIBOBJ} replacement directory are assumed to contain a
5190 copy of the source code of @acronym{GNU} @code{fnmatch}.  If necessary,
5191 this source code is compiled as an @code{AC_LIBOBJ} replacement, and the
5192 @file{fnmatch_.h} file is linked to @file{fnmatch.h} so that it can be
5193 included in place of the system @code{<fnmatch.h>}.
5195 This macro is obsolescent, as it assumes the use of particular source
5196 files.  New programs should use Gnulib's @code{fnmatch-posix} module,
5197 which provides this macro along with the source files.  @xref{Gnulib}.
5198 @end defmac
5202 @node Generic Functions
5203 @subsection Generic Function Checks
5205 These macros are used to find functions not covered by the ``particular''
5206 test macros.  If the functions might be in libraries other than the
5207 default C library, first call @code{AC_CHECK_LIB} for those libraries.
5208 If you need to check the behavior of a function as well as find out
5209 whether it is present, you have to write your own test for
5210 it (@pxref{Writing Tests}).
5212 @anchor{AC_CHECK_FUNC}
5213 @defmac AC_CHECK_FUNC (@var{function}, @ovar{action-if-found}, @
5214   @ovar{action-if-not-found})
5215 @acindex{CHECK_FUNC}
5216 If C function @var{function} is available, run shell commands
5217 @var{action-if-found}, otherwise @var{action-if-not-found}.  If you just
5218 want to define a symbol if the function is available, consider using
5219 @code{AC_CHECK_FUNCS} instead.  This macro checks for functions with C
5220 linkage even when @code{AC_LANG(C++)} has been called, since C is more
5221 standardized than C++.  (@pxref{Language Choice}, for more information
5222 about selecting the language for checks.)
5223 @end defmac
5225 @anchor{AC_CHECK_FUNCS}
5226 @defmac AC_CHECK_FUNCS (@var{function}@dots{}, @ovar{action-if-found}, @
5227   @ovar{action-if-not-found})
5228 @acindex{CHECK_FUNCS}
5229 @cvindex HAVE_@var{function}
5230 For each @var{function} enumerated in the blank-or-newline-separated argument
5231 list, define @code{HAVE_@var{function}} (in all capitals) if it is available.
5232 If @var{action-if-found} is given, it is additional shell code to
5233 execute when one of the functions is found.  You can give it a value of
5234 @samp{break} to break out of the loop on the first match.  If
5235 @var{action-if-not-found} is given, it is executed when one of the
5236 functions is not found.
5237 @end defmac
5239 @defmac AC_CHECK_FUNCS_ONCE (@var{function}@dots{})
5240 @acindex{CHECK_FUNCS_ONCE}
5241 @cvindex HAVE_@var{function}
5242 For each @var{function} enumerated in the blank-or-newline-separated argument
5243 list, define @code{HAVE_@var{function}} (in all capitals) if it is available.
5244 This is a once-only variant of @code{AC_CHECK_FUNCS}.  It generates the
5245 checking code at most once, so that @command{configure} is smaller and
5246 faster; but the checks cannot be conditionalized and are always done once,
5247 early during the @command{configure} run.
5248 @end defmac
5250 @sp 1
5252 Autoconf follows a philosophy that was formed over the years by those
5253 who have struggled for portability: isolate the portability issues in
5254 specific files, and then program as if you were in a Posix
5255 environment.  Some functions may be missing or unfixable, and your
5256 package must be ready to replace them.
5258 Suitable replacements for many such problem functions are available from
5259 Gnulib (@pxref{Gnulib}).
5261 @defmac AC_LIBOBJ (@var{function})
5262 @acindex{LIBOBJ}
5263 @ovindex LIBOBJS
5264 Specify that @samp{@var{function}.c} must be included in the executables
5265 to replace a missing or broken implementation of @var{function}.
5267 Technically, it adds @samp{@var{function}.$ac_objext} to the output
5268 variable @code{LIBOBJS} if it is not already in, and calls
5269 @code{AC_LIBSOURCE} for @samp{@var{function}.c}.  You should not
5270 directly change @code{LIBOBJS}, since this is not traceable.
5271 @end defmac
5273 @defmac AC_LIBSOURCE (@var{file})
5274 @acindex{LIBSOURCE}
5275 Specify that @var{file} might be needed to compile the project.  If you
5276 need to know what files might be needed by a @file{configure.ac}, you
5277 should trace @code{AC_LIBSOURCE}.  @var{file} must be a literal.
5279 This macro is called automatically from @code{AC_LIBOBJ}, but you must
5280 call it explicitly if you pass a shell variable to @code{AC_LIBOBJ}.  In
5281 that case, since shell variables cannot be traced statically, you must
5282 pass to @code{AC_LIBSOURCE} any possible files that the shell variable
5283 might cause @code{AC_LIBOBJ} to need.  For example, if you want to pass
5284 a variable @code{$foo_or_bar} to @code{AC_LIBOBJ} that holds either
5285 @code{"foo"} or @code{"bar"}, you should do:
5287 @example
5288 AC_LIBSOURCE([foo.c])
5289 AC_LIBSOURCE([bar.c])
5290 AC_LIBOBJ([$foo_or_bar])
5291 @end example
5293 @noindent
5294 There is usually a way to avoid this, however, and you are encouraged to
5295 simply call @code{AC_LIBOBJ} with literal arguments.
5297 Note that this macro replaces the obsolete @code{AC_LIBOBJ_DECL}, with
5298 slightly different semantics: the old macro took the function name,
5299 e.g., @code{foo}, as its argument rather than the file name.
5300 @end defmac
5302 @defmac AC_LIBSOURCES (@var{files})
5303 @acindex{LIBSOURCES}
5304 Like @code{AC_LIBSOURCE}, but accepts one or more @var{files} in a
5305 comma-separated M4 list.  Thus, the above example might be rewritten:
5307 @example
5308 AC_LIBSOURCES([foo.c, bar.c])
5309 AC_LIBOBJ([$foo_or_bar])
5310 @end example
5311 @end defmac
5313 @defmac AC_CONFIG_LIBOBJ_DIR (@var{directory})
5314 @acindex{CONFIG_LIBOBJ_DIR}
5315 Specify that @code{AC_LIBOBJ} replacement files are to be found in
5316 @var{directory}, a name relative to the top level of the
5317 source tree.  The replacement directory defaults to @file{.}, the top
5318 level directory, and the most typical value is @file{lib}, corresponding
5319 to @samp{AC_CONFIG_LIBOBJ_DIR([lib])}.
5321 @command{configure} might need to know the replacement directory for the
5322 following reasons: (i) some checks use the replacement files, (ii) some
5323 macros bypass broken system headers by installing links to the
5324 replacement headers (iii) when used in conjunction with Automake,
5325 within each makefile, @var{directory} is used as a relative path
5326 from @code{$(top_srcdir)} to each object named in @code{LIBOBJS} and
5327 @code{LTLIBOBJS}, etc.
5328 @end defmac
5330 @sp 1
5332 It is common to merely check for the existence of a function, and ask
5333 for its @code{AC_LIBOBJ} replacement if missing.  The following macro is
5334 a convenient shorthand.
5336 @defmac AC_REPLACE_FUNCS (@var{function}@dots{})
5337 @acindex{REPLACE_FUNCS}
5338 @cvindex HAVE_@var{function}
5339 @ovindex LIBOBJS
5340 Like @code{AC_CHECK_FUNCS}, but uses @samp{AC_LIBOBJ(@var{function})} as
5341 @var{action-if-not-found}.  You can declare your replacement function by
5342 enclosing the prototype in @samp{#ifndef HAVE_@var{function}}.  If the
5343 system has the function, it probably declares it in a header file you
5344 should be including, so you shouldn't redeclare it lest your declaration
5345 conflict.
5346 @end defmac
5348 @node Header Files
5349 @section Header Files
5350 @cindex Header, checking
5352 The following macros check for the presence of certain C header files.
5353 If there is no macro specifically defined to check for a header file you need,
5354 and you don't need to check for any special properties of
5355 it, then you can use one of the general header-file check macros.
5357 @menu
5358 * Header Portability::          Collected knowledge on common headers
5359 * Particular Headers::          Special handling to find certain headers
5360 * Generic Headers::             How to find other headers
5361 @end menu
5363 @node Header Portability
5364 @subsection Portability of Headers
5365 @cindex Portability of headers
5366 @cindex Header portability
5368 This section tries to collect knowledge about common headers, and the
5369 problems they cause.  By definition, this list always requires
5370 additions.  Please help us keeping it as complete as possible.
5372 @table @asis
5374 @item @file{limits.h}
5375 C99 says that @file{limits.h} defines @code{LLONG_MIN},
5376 @code{LLONG_MAX}, and @code{ULLONG_MAX}, but many almost-C99
5377 environments (e.g., default @acronym{GCC} 4.0.2 + glibc 2.4) do not
5378 define them.
5380 @item @file{inttypes.h} vs.@: @file{stdint.h}
5381 @hdrindex{inttypes.h}
5382 @hdrindex{stdint.h}
5383 The C99 standard says that @file{inttypes.h} includes
5384 @file{stdint.h}, so there's no need to include @file{stdint.h}
5385 separately in a standard environment.  Some implementations have
5386 @file{inttypes.h} but not @file{stdint.h} (e.g., Solaris 7), but we don't
5387 know of any implementation that has @file{stdint.h} but not
5388 @file{inttypes.h}.
5390 @item @file{linux/irda.h}
5391 @hdrindex{linux/irda.h}
5392 It requires @file{linux/types.h} and @file{sys/socket.h}.
5394 @item @file{linux/random.h}
5395 @hdrindex{linux/random.h}
5396 It requires @file{linux/types.h}.
5398 @item @file{net/if.h}
5399 @hdrindex{net/if.h}
5400 On Darwin, this file requires that @file{sys/socket.h} be included
5401 beforehand.  One should run:
5403 @example
5404 AC_CHECK_HEADERS([sys/socket.h])
5405 AC_CHECK_HEADERS([net/if.h], [], [],
5406 [#include <stdio.h>
5407 #ifdef STDC_HEADERS
5408 # include <stdlib.h>
5409 # include <stddef.h>
5410 #else
5411 # ifdef HAVE_STDLIB_H
5412 #  include <stdlib.h>
5413 # endif
5414 #endif
5415 #ifdef HAVE_SYS_SOCKET_H
5416 # include <sys/socket.h>
5417 #endif
5419 @end example
5421 @item @file{netinet/if_ether.h}
5422 @hdrindex{netinet/if_ether.h}
5423 On Darwin, this file requires that @file{stdio.h} and
5424 @file{sys/socket.h} be included beforehand.  One should run:
5426 @example
5427 AC_CHECK_HEADERS([sys/socket.h])
5428 AC_CHECK_HEADERS([netinet/if_ether.h], [], [],
5429 [#include <stdio.h>
5430 #ifdef STDC_HEADERS
5431 # include <stdlib.h>
5432 # include <stddef.h>
5433 #else
5434 # ifdef HAVE_STDLIB_H
5435 #  include <stdlib.h>
5436 # endif
5437 #endif
5438 #ifdef HAVE_SYS_SOCKET_H
5439 # include <sys/socket.h>
5440 #endif
5442 @end example
5444 @item @file{stdint.h}
5445 See above, item @file{inttypes.h} vs.@: @file{stdint.h}.
5447 @item @file{stdlib.h}
5448 @hdrindex{stdlib.h}
5449 On many systems (e.g., Darwin), @file{stdio.h} is a prerequisite.
5451 @item @file{sys/mount.h}
5452 @hdrindex{sys/mount.h}
5453 On Free@acronym{BSD} 4.8 on ia32 and using gcc version 2.95.4,
5454 @file{sys/params.h} is a prerequisite.
5456 @item @file{sys/ptem.h}
5457 @hdrindex{sys/ptem.h}
5458 On Solaris 8, @file{sys/stream.h} is a prerequisite.
5460 @item @file{sys/socket.h}
5461 @hdrindex{sys/socket.h}
5462 On Darwin, @file{stdlib.h} is a prerequisite.
5464 @item @file{sys/ucred.h}
5465 @hdrindex{sys/ucred.h}
5466 On Tru64 5.1, @file{sys/types.h} is a prerequisite.
5468 @item @file{X11/extensions/scrnsaver.h}
5469 @hdrindex{X11/extensions/scrnsaver.h}
5470 Using XFree86, this header requires @file{X11/Xlib.h}, which is probably
5471 so required that you might not even consider looking for it.
5473 @example
5474 AC_CHECK_HEADERS([X11/extensions/scrnsaver.h], [], [],
5475 [[#include <X11/Xlib.h>
5477 @end example
5478 @end table
5481 @node Particular Headers
5482 @subsection Particular Header Checks
5484 These macros check for particular system header files---whether they
5485 exist, and in some cases whether they declare certain symbols.
5487 @defmac AC_HEADER_ASSERT
5488 @acindex{HEADER_ASSERT}
5489 @cvindex NDEBUG
5490 @hdrindex{assert.h}
5491 Check whether to enable assertions in the style of @file{assert.h}.
5492 Assertions are enabled by default, but the user can override this by
5493 invoking @command{configure} with the @option{--disable-assert} option.
5494 @end defmac
5496 @anchor{AC_HEADER_DIRENT}
5497 @defmac AC_HEADER_DIRENT
5498 @acindex{HEADER_DIRENT}
5499 @cvindex HAVE_DIRENT_H
5500 @cvindex HAVE_NDIR_H
5501 @cvindex HAVE_SYS_DIR_H
5502 @cvindex HAVE_SYS_NDIR_H
5503 @hdrindex{dirent.h}
5504 @hdrindex{sys/ndir.h}
5505 @hdrindex{sys/dir.h}
5506 @hdrindex{ndir.h}
5507 Check for the following header files.  For the first one that is
5508 found and defines @samp{DIR}, define the listed C preprocessor macro:
5510 @multitable {@file{sys/ndir.h}} {@code{HAVE_SYS_NDIR_H}}
5511 @item @file{dirent.h}   @tab @code{HAVE_DIRENT_H}
5512 @item @file{sys/ndir.h} @tab @code{HAVE_SYS_NDIR_H}
5513 @item @file{sys/dir.h}  @tab @code{HAVE_SYS_DIR_H}
5514 @item @file{ndir.h}     @tab @code{HAVE_NDIR_H}
5515 @end multitable
5517 The directory-library declarations in your source code should look
5518 something like the following:
5520 @example
5521 @group
5522 #include <sys/types.h>
5523 #ifdef HAVE_DIRENT_H
5524 # include <dirent.h>
5525 # define NAMLEN(dirent) strlen ((dirent)->d_name)
5526 #else
5527 # define dirent direct
5528 # define NAMLEN(dirent) ((dirent)->d_namlen)
5529 # ifdef HAVE_SYS_NDIR_H
5530 #  include <sys/ndir.h>
5531 # endif
5532 # ifdef HAVE_SYS_DIR_H
5533 #  include <sys/dir.h>
5534 # endif
5535 # ifdef HAVE_NDIR_H
5536 #  include <ndir.h>
5537 # endif
5538 #endif
5539 @end group
5540 @end example
5542 Using the above declarations, the program would declare variables to be
5543 of type @code{struct dirent}, not @code{struct direct}, and would access
5544 the length of a directory entry name by passing a pointer to a
5545 @code{struct dirent} to the @code{NAMLEN} macro.
5547 This macro also checks for the SCO Xenix @file{dir} and @file{x} libraries.
5549 This macro is obsolescent, as all current systems with directory
5550 libraries have @code{<dirent.h>}.  New programs need not use this macro.
5552 Also see @code{AC_STRUCT_DIRENT_D_INO} and
5553 @code{AC_STRUCT_DIRENT_D_TYPE} (@pxref{Particular Structures}).
5554 @end defmac
5556 @anchor{AC_HEADER_MAJOR}
5557 @defmac AC_HEADER_MAJOR
5558 @acindex{HEADER_MAJOR}
5559 @cvindex MAJOR_IN_MKDEV
5560 @cvindex MAJOR_IN_SYSMACROS
5561 @hdrindex{sys/mkdev.h}
5562 @hdrindex{sys/sysmacros.h}
5563 If @file{sys/types.h} does not define @code{major}, @code{minor}, and
5564 @code{makedev}, but @file{sys/mkdev.h} does, define
5565 @code{MAJOR_IN_MKDEV}; otherwise, if @file{sys/sysmacros.h} does, define
5566 @code{MAJOR_IN_SYSMACROS}.
5567 @end defmac
5569 @defmac AC_HEADER_RESOLV
5570 @acindex{HEADER_RESOLV}
5571 @cvindex HAVE_RESOLV_H
5572 @hdrindex{resolv.h}
5573 Checks for header @file{resolv.h}, checking for prerequisites first.
5574 To properly use @file{resolv.h}, your code should contain something like
5575 the following:
5577 @verbatim
5578 #ifdef HAVE_SYS_TYPES_H
5579 #  include <sys/types.h>
5580 #endif
5581 #ifdef HAVE_NETINET_IN_H
5582 #  include <netinet/in.h>   /* inet_ functions / structs */
5583 #endif
5584 #ifdef HAVE_ARPA_NAMESER_H
5585 #  include <arpa/nameser.h> /* DNS HEADER struct */
5586 #endif
5587 #ifdef HAVE_NETDB_H
5588 #  include <netdb.h>
5589 #endif
5590 #include <resolv.h>
5591 @end verbatim
5592 @end defmac
5594 @anchor{AC_HEADER_STAT}
5595 @defmac AC_HEADER_STAT
5596 @acindex{HEADER_STAT}
5597 @cvindex STAT_MACROS_BROKEN
5598 @hdrindex{sys/stat.h}
5599 If the macros @code{S_ISDIR}, @code{S_ISREG}, etc.@: defined in
5600 @file{sys/stat.h} do not work properly (returning false positives),
5601 define @code{STAT_MACROS_BROKEN}.  This is the case on Tektronix UTekV,
5602 Amdahl UTS and Motorola System V/88.
5604 This macro is obsolescent, as no current systems have the bug.
5605 New programs need not use this macro.
5606 @end defmac
5608 @defmac AC_HEADER_STDBOOL
5609 @acindex{HEADER_STDBOOL}
5610 @cvindex HAVE_STDBOOL_H
5611 @cvindex HAVE__BOOL
5612 @hdrindex{stdbool.h}
5613 @hdrindex{system.h}
5614 If @file{stdbool.h} exists and conforms to C99, define
5615 @code{HAVE_STDBOOL_H} to 1; if the type @code{_Bool} is defined, define
5616 @code{HAVE__BOOL} to 1.  To fulfill the C99 requirements, your
5617 @file{system.h} could contain the following code:
5619 @verbatim
5620 #ifdef HAVE_STDBOOL_H
5621 # include <stdbool.h>
5622 #else
5623 # ifndef HAVE__BOOL
5624 #  ifdef __cplusplus
5625 typedef bool _Bool;
5626 #  else
5627 #   define _Bool signed char
5628 #  endif
5629 # endif
5630 # define bool _Bool
5631 # define false 0
5632 # define true 1
5633 # define __bool_true_false_are_defined 1
5634 #endif
5635 @end verbatim
5637 Alternatively you can use the @samp{stdbool} package of Gnulib
5638 (@pxref{Gnulib}); it packages the above code into a replacement header
5639 and contains a few other bells and whistles.
5641 @end defmac
5643 @anchor{AC_HEADER_STDC}
5644 @defmac AC_HEADER_STDC
5645 @acindex{HEADER_STDC}
5646 @cvindex STDC_HEADERS
5647 @hdrindex{stdlib.h}
5648 @hdrindex{stdarg.h}
5649 @hdrindex{string.h}
5650 @hdrindex{float.h}
5651 @hdrindex{ctype.h}
5652 Define @code{STDC_HEADERS} if the system has C header files
5653 conforming to @acronym{ANSI} C89 (@acronym{ISO} C90).
5654 Specifically, this macro checks for @file{stdlib.h}, @file{stdarg.h},
5655 @file{string.h}, and @file{float.h}; if the system has those, it
5656 probably has the rest of the C89 header files.  This macro also
5657 checks whether @file{string.h} declares @code{memchr} (and thus
5658 presumably the other @code{mem} functions), whether @file{stdlib.h}
5659 declare @code{free} (and thus presumably @code{malloc} and other related
5660 functions), and whether the @file{ctype.h} macros work on characters
5661 with the high bit set, as the C standard requires.
5663 If you use this macro, your code can refer to @code{STDC_HEADERS} to
5664 determine whether the system has conforming header files (and probably C
5665 library functions).
5667 This macro is obsolescent, as current systems have conforming header
5668 files.  New programs need not use this macro.
5670 @hdrindex{string.h}
5671 @hdrindex{strings.h}
5672 Nowadays @file{string.h} is part of the C standard and declares functions like
5673 @code{strcpy}, and @file{strings.h} is standardized by Posix and declares
5674 @acronym{BSD} functions like @code{bcopy}; but
5675 historically, string functions were a major sticking point in this area.
5676 If you still want to worry about portability to ancient systems without
5677 standard headers, there is so much variation
5678 that it is probably easier to declare the functions you use than to
5679 figure out exactly what the system header files declare.  Some ancient systems
5680 contained a mix of functions from the C standard and from @acronym{BSD};
5681 some were mostly standard but lacked @samp{memmove}; some defined the
5682 @acronym{BSD} functions as macros in @file{string.h} or
5683 @file{strings.h}; some had only the @acronym{BSD} functions but
5684 @file{string.h}; some declared the memory functions in @file{memory.h},
5685 some in @file{string.h}; etc.  It is probably sufficient to check for
5686 one string function and one memory function; if the library had the
5687 standard versions of those then it probably had most of the others.
5688 If you put the following in @file{configure.ac}:
5690 @example
5691 # This example is obsolescent.
5692 # Nowadays you can omit these macro calls.
5693 AC_HEADER_STDC
5694 AC_CHECK_FUNCS([strchr memcpy])
5695 @end example
5697 @noindent
5698 then, in your code, you can use declarations like this:
5700 @example
5701 @group
5702 /* This example is obsolescent.
5703    Nowadays you can just #include <string.h>.  */
5704 #ifdef STDC_HEADERS
5705 # include <string.h>
5706 #else
5707 # ifndef HAVE_STRCHR
5708 #  define strchr index
5709 #  define strrchr rindex
5710 # endif
5711 char *strchr (), *strrchr ();
5712 # ifndef HAVE_MEMCPY
5713 #  define memcpy(d, s, n) bcopy ((s), (d), (n))
5714 #  define memmove(d, s, n) bcopy ((s), (d), (n))
5715 # endif
5716 #endif
5717 @end group
5718 @end example
5720 @noindent
5721 If you use a function like @code{memchr}, @code{memset}, @code{strtok},
5722 or @code{strspn}, which have no @acronym{BSD} equivalent, then macros don't
5723 suffice to port to ancient hosts; you must provide an implementation of
5724 each function.  An easy
5725 way to incorporate your implementations only when needed (since the ones
5726 in system C libraries may be hand optimized) is to, taking @code{memchr}
5727 for example, put it in @file{memchr.c} and use
5728 @samp{AC_REPLACE_FUNCS([memchr])}.
5729 @end defmac
5731 @defmac AC_HEADER_SYS_WAIT
5732 @acindex{HEADER_SYS_WAIT}
5733 @cvindex HAVE_SYS_WAIT_H
5734 @hdrindex{sys/wait.h}
5735 If @file{sys/wait.h} exists and is compatible with Posix, define
5736 @code{HAVE_SYS_WAIT_H}.  Incompatibility can occur if @file{sys/wait.h}
5737 does not exist, or if it uses the old @acronym{BSD} @code{union wait} instead
5738 of @code{int} to store a status value.  If @file{sys/wait.h} is not
5739 Posix compatible, then instead of including it, define the
5740 Posix macros with their usual interpretations.  Here is an
5741 example:
5743 @example
5744 @group
5745 #include <sys/types.h>
5746 #ifdef HAVE_SYS_WAIT_H
5747 # include <sys/wait.h>
5748 #endif
5749 #ifndef WEXITSTATUS
5750 # define WEXITSTATUS(stat_val) ((unsigned int) (stat_val) >> 8)
5751 #endif
5752 #ifndef WIFEXITED
5753 # define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
5754 #endif
5755 @end group
5756 @end example
5758 @noindent
5759 This macro is obsolescent, as current systems are compatible with Posix.
5760 New programs need not use this macro.
5761 @end defmac
5763 @cvindex _POSIX_VERSION
5764 @hdrindex{unistd.h}
5765 @code{_POSIX_VERSION} is defined when @file{unistd.h} is included on
5766 Posix systems.  If there is no @file{unistd.h}, it is definitely
5767 not a Posix system.  However, some non-Posix systems do
5768 have @file{unistd.h}.
5770 The way to check whether the system supports Posix is:
5772 @example
5773 @group
5774 #ifdef HAVE_UNISTD_H
5775 # include <sys/types.h>
5776 # include <unistd.h>
5777 #endif
5779 #ifdef _POSIX_VERSION
5780 /* Code for Posix systems.  */
5781 #endif
5782 @end group
5783 @end example
5785 @anchor{AC_HEADER_TIME}
5786 @defmac AC_HEADER_TIME
5787 @acindex{HEADER_TIME}
5788 @cvindex TIME_WITH_SYS_TIME
5789 @hdrindex{time.h}
5790 @hdrindex{sys/time.h}
5791 If a program may include both @file{time.h} and @file{sys/time.h},
5792 define @code{TIME_WITH_SYS_TIME}.  On some ancient systems,
5793 @file{sys/time.h} included @file{time.h}, but @file{time.h} was not
5794 protected against multiple inclusion, so programs could not explicitly
5795 include both files.  This macro is useful in programs that use, for
5796 example, @code{struct timeval} as well as
5797 @code{struct tm}.  It is best used in conjunction with
5798 @code{HAVE_SYS_TIME_H}, which can be checked for using
5799 @code{AC_CHECK_HEADERS([sys/time.h])}.
5801 @example
5802 @group
5803 #ifdef TIME_WITH_SYS_TIME
5804 # include <sys/time.h>
5805 # include <time.h>
5806 #else
5807 # ifdef HAVE_SYS_TIME_H
5808 #  include <sys/time.h>
5809 # else
5810 #  include <time.h>
5811 # endif
5812 #endif
5813 @end group
5814 @end example
5816 @noindent
5817 This macro is obsolescent, as current systems can include both files
5818 when they exist.  New programs need not use this macro.
5819 @end defmac
5822 @defmac AC_HEADER_TIOCGWINSZ
5823 @acindex{HEADER_TIOCGWINSZ}
5824 @cvindex GWINSZ_IN_SYS_IOCTL
5825 @hdrindex{sys/ioctl.h}
5826 @hdrindex{termios.h}
5827 @c FIXME: I need clarifications from Jim.
5828 If the use of @code{TIOCGWINSZ} requires @file{<sys/ioctl.h>}, then
5829 define @code{GWINSZ_IN_SYS_IOCTL}.  Otherwise @code{TIOCGWINSZ} can be
5830 found in @file{<termios.h>}.
5832 Use:
5834 @example
5835 @group
5836 #ifdef HAVE_TERMIOS_H
5837 # include <termios.h>
5838 #endif
5840 #ifdef GWINSZ_IN_SYS_IOCTL
5841 # include <sys/ioctl.h>
5842 #endif
5843 @end group
5844 @end example
5845 @end defmac
5847 @node Generic Headers
5848 @subsection Generic Header Checks
5850 These macros are used to find system header files not covered by the
5851 ``particular'' test macros.  If you need to check the contents of a header
5852 as well as find out whether it is present, you have to write your own
5853 test for it (@pxref{Writing Tests}).
5855 @anchor{AC_CHECK_HEADER}
5856 @defmac AC_CHECK_HEADER (@var{header-file}, @ovar{action-if-found}, @
5857   @ovar{action-if-not-found}, @ovar{includes})
5858 @acindex{CHECK_HEADER}
5859 If the system header file @var{header-file} is compilable, execute shell
5860 commands @var{action-if-found}, otherwise execute
5861 @var{action-if-not-found}.  If you just want to define a symbol if the
5862 header file is available, consider using @code{AC_CHECK_HEADERS}
5863 instead.
5865 @var{includes} is decoded to determine the appropriate include
5866 directives.  If omitted or empty, @file{configure} will check for both header
5867 existence (with the preprocessor) and usability (with the compiler),
5868 using @code{AC_INCLUDES_DEFAULT} for the compile test.  If
5869 there is a discrepancy between the results, a warning is issued to the
5870 user, and the compiler results are favored (@pxref{Present But
5871 Cannot Be Compiled}).  In general, favoring the compiler results means
5872 that a header will be treated as not found even though the file exists,
5873 because you did not provide enough prerequisites.
5875 Providing a non-empty @var{includes} argument allows the code to provide
5876 any prerequisites prior to including the header under test; it is common
5877 to use the argument @code{AC_INCLUDES_DEFAULT} (@pxref{Default
5878 Includes}).  With an explicit fourth argument, no preprocessor test is
5879 needed.  As a special case, an @var{includes} of exactly @samp{-}
5880 triggers the older preprocessor check, which merely determines existence
5881 of the file in the preprocessor search path; this should only be used as
5882 a last resort (it is safer to determine the actual prerequisites and
5883 perform a compiler check, or else use @code{AC_PREPROC_IFELSE} to make
5884 it obvious that only a preprocessor check is desired).
5885 @end defmac
5887 @anchor{AC_CHECK_HEADERS}
5888 @defmac AC_CHECK_HEADERS (@var{header-file}@dots{}, @
5889   @ovar{action-if-found}, @ovar{action-if-not-found}, @
5890   @ovar{includes})
5891 @acindex{CHECK_HEADERS}
5892 @cvindex HAVE_@var{header}
5893 For each given system header file @var{header-file} in the
5894 blank-separated argument list that exists, define
5895 @code{HAVE_@var{header-file}} (in all capitals).  If @var{action-if-found}
5896 is given, it is additional shell code to execute when one of the header
5897 files is found.  You can give it a value of @samp{break} to break out of
5898 the loop on the first match.  If @var{action-if-not-found} is given, it
5899 is executed when one of the header files is not found.
5901 @var{includes} is interpreted as in @code{AC_CHECK_HEADER}, in order to
5902 choose the set of preprocessor directives supplied before the header
5903 under test.
5904 @end defmac
5906 Previous versions of Autoconf merely checked whether the header was
5907 accepted by the preprocessor.  This was changed because the old test was
5908 inappropriate for typical uses.  Headers are typically used to compile,
5909 not merely to preprocess, and the old behavior sometimes accepted
5910 headers that clashed at compile-time (@pxref{Present But Cannot Be
5911 Compiled}).  If you need to check whether a header is preprocessable,
5912 you can use @code{AC_PREPROC_IFELSE} (@pxref{Running the Preprocessor}).
5914 Actually requiring a header to compile improves the robustness of the
5915 test, but it also requires
5916 that you make sure that headers that must be included before the
5917 @var{header-file} be part of the @var{includes}, (@pxref{Default
5918 Includes}).  If looking for @file{bar.h}, which requires that
5919 @file{foo.h} be included before if it exists, we suggest the following
5920 scheme:
5922 @verbatim
5923 AC_CHECK_HEADERS([foo.h])
5924 AC_CHECK_HEADERS([bar.h], [], [],
5925 [#ifdef HAVE_FOO_H
5926 # include <foo.h>
5927 #endif
5929 @end verbatim
5931 The following variant generates smaller, faster @command{configure}
5932 files if you do not need the full power of @code{AC_CHECK_HEADERS}.
5934 @defmac AC_CHECK_HEADERS_ONCE (@var{header-file}@dots{})
5935 @acindex{CHECK_HEADERS_ONCE}
5936 @cvindex HAVE_@var{header}
5937 For each given system header file @var{header-file} in the
5938 blank-separated argument list that exists, define
5939 @code{HAVE_@var{header-file}} (in all capitals).
5940 This is a once-only variant of @code{AC_CHECK_HEADERS}.  It generates the
5941 checking code at most once, so that @command{configure} is smaller and
5942 faster; but the checks cannot be conditionalized and are always done once,
5943 early during the @command{configure} run.  Thus, this macro is only safe
5944 for checking headers that do not have prerequisites beyond what
5945 @code{AC_INCLUDES_DEFAULT} provides.
5946 @end defmac
5948 @node Declarations
5949 @section Declarations
5950 @cindex Declaration, checking
5952 The following macros check for the declaration of variables and
5953 functions.  If there is no macro specifically defined to check for a
5954 symbol you need, then you can use the general macros (@pxref{Generic
5955 Declarations}) or, for more complex tests, you may use
5956 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}).
5958 @menu
5959 * Particular Declarations::     Macros to check for certain declarations
5960 * Generic Declarations::        How to find other declarations
5961 @end menu
5963 @node Particular Declarations
5964 @subsection Particular Declaration Checks
5966 There are no specific macros for declarations.
5968 @node Generic Declarations
5969 @subsection Generic Declaration Checks
5971 These macros are used to find declarations not covered by the ``particular''
5972 test macros.
5974 @defmac AC_CHECK_DECL (@var{symbol}, @ovar{action-if-found}, @
5975   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
5976 @acindex{CHECK_DECL}
5977 If @var{symbol} (a function, variable, or constant) is not declared in
5978 @var{includes} and a declaration is needed, run the shell commands
5979 @var{action-if-not-found}, otherwise @var{action-if-found}.
5980 @var{includes} is a series of include directives, defaulting to
5981 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
5982 prior to the declaration under test.
5984 This macro actually tests whether @var{symbol} is defined as a macro or
5985 can be used as an r-value, not whether it is really declared, because it
5986 is much safer to avoid
5987 introducing extra declarations when they are not needed.
5988 @end defmac
5990 @anchor{AC_CHECK_DECLS}
5991 @defmac AC_CHECK_DECLS (@var{symbols}, @ovar{action-if-found}, @
5992   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
5993 @acindex{CHECK_DECLS}
5994 @cvindex HAVE_DECL_@var{symbol}
5995 For each of the @var{symbols} (@emph{comma}-separated list), define
5996 @code{HAVE_DECL_@var{symbol}} (in all capitals) to @samp{1} if
5997 @var{symbol} is declared, otherwise to @samp{0}.  If
5998 @var{action-if-not-found} is given, it is additional shell code to
5999 execute when one of the function declarations is needed, otherwise
6000 @var{action-if-found} is executed.
6002 @var{includes} is a series of include directives, defaulting to
6003 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
6004 prior to the declarations under test.
6006 This macro uses an M4 list as first argument:
6007 @example
6008 AC_CHECK_DECLS([strdup])
6009 AC_CHECK_DECLS([strlen])
6010 AC_CHECK_DECLS([malloc, realloc, calloc, free])
6011 AC_CHECK_DECLS([j0], [], [], [[#include <math.h>]])
6012 @end example
6014 Unlike the other @samp{AC_CHECK_*S} macros, when a @var{symbol} is not
6015 declared, @code{HAVE_DECL_@var{symbol}} is defined to @samp{0} instead
6016 of leaving @code{HAVE_DECL_@var{symbol}} undeclared.  When you are
6017 @emph{sure} that the check was performed, use
6018 @code{HAVE_DECL_@var{symbol}} in @code{#if}:
6020 @example
6021 #if !HAVE_DECL_SYMBOL
6022 extern char *symbol;
6023 #endif
6024 @end example
6026 @noindent
6027 If the test may have not been performed, however, because it is safer
6028 @emph{not} to declare a symbol than to use a declaration that conflicts
6029 with the system's one, you should use:
6031 @example
6032 #if defined HAVE_DECL_MALLOC && !HAVE_DECL_MALLOC
6033 void *malloc (size_t *s);
6034 #endif
6035 @end example
6037 @noindent
6038 You fall into the second category only in extreme situations: either
6039 your files may be used without being configured, or they are used during
6040 the configuration.  In most cases the traditional approach is enough.
6041 @end defmac
6043 @defmac AC_CHECK_DECLS_ONCE (@var{symbols})
6044 @acindex{CHECK_DECLS_ONCE}
6045 @cvindex HAVE_DECL_@var{symbol}
6046 For each of the @var{symbols} (@emph{comma}-separated list), define
6047 @code{HAVE_DECL_@var{symbol}} (in all capitals) to @samp{1} if
6048 @var{symbol} is declared in the default include files, otherwise to
6049 @samp{0}.  This is a once-only variant of @code{AC_CHECK_DECLS}.  It
6050 generates the checking code at most once, so that @command{configure} is
6051 smaller and faster; but the checks cannot be conditionalized and are
6052 always done once, early during the @command{configure} run.
6053 @end defmac
6056 @node Structures
6057 @section Structures
6058 @cindex Structure, checking
6060 The following macros check for the presence of certain members in C
6061 structures.  If there is no macro specifically defined to check for a
6062 member you need, then you can use the general structure-member macros
6063 (@pxref{Generic Structures}) or, for more complex tests, you may use
6064 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}).
6066 @menu
6067 * Particular Structures::       Macros to check for certain structure members
6068 * Generic Structures::          How to find other structure members
6069 @end menu
6071 @node Particular Structures
6072 @subsection Particular Structure Checks
6074 The following macros check for certain structures or structure members.
6076 @defmac AC_STRUCT_DIRENT_D_INO
6077 @acindex{STRUCT_DIRENT_D_INO}
6078 @cvindex HAVE_STRUCT_DIRENT_D_INO
6079 Perform all the actions of @code{AC_HEADER_DIRENT} (@pxref{Particular
6080 Headers}).  Then, if @code{struct dirent} contains a @code{d_ino}
6081 member, define @code{HAVE_STRUCT_DIRENT_D_INO}.
6083 @code{HAVE_STRUCT_DIRENT_D_INO} indicates only the presence of
6084 @code{d_ino}, not whether its contents are always reliable.
6085 Traditionally, a zero @code{d_ino} indicated a deleted directory entry,
6086 though current systems hide this detail from the user and never return
6087 zero @code{d_ino} values.
6088 Many current systems report an incorrect @code{d_ino} for a directory
6089 entry that is a mount point.
6090 @end defmac
6092 @defmac AC_STRUCT_DIRENT_D_TYPE
6093 @acindex{STRUCT_DIRENT_D_TYPE}
6094 @cvindex HAVE_STRUCT_DIRENT_D_TYPE
6095 Perform all the actions of @code{AC_HEADER_DIRENT} (@pxref{Particular
6096 Headers}).  Then, if @code{struct dirent} contains a @code{d_type}
6097 member, define @code{HAVE_STRUCT_DIRENT_D_TYPE}.
6098 @end defmac
6100 @anchor{AC_STRUCT_ST_BLOCKS}
6101 @defmac AC_STRUCT_ST_BLOCKS
6102 @acindex{STRUCT_ST_BLOCKS}
6103 @cvindex HAVE_STRUCT_STAT_ST_BLOCKS
6104 @cvindex HAVE_ST_BLOCKS
6105 @ovindex LIBOBJS
6106 If @code{struct stat} contains an @code{st_blocks} member, define
6107 @code{HAVE_STRUCT_STAT_ST_BLOCKS}.  Otherwise, require an
6108 @code{AC_LIBOBJ} replacement of @samp{fileblocks}.  The former name,
6109 @code{HAVE_ST_BLOCKS} is to be avoided, as its support will cease in the
6110 future.
6111 @end defmac
6113 @defmac AC_STRUCT_TM
6114 @acindex{STRUCT_TM}
6115 @cvindex TM_IN_SYS_TIME
6116 @hdrindex{time.h}
6117 @hdrindex{sys/time.h}
6118 If @file{time.h} does not define @code{struct tm}, define
6119 @code{TM_IN_SYS_TIME}, which means that including @file{sys/time.h}
6120 had better define @code{struct tm}.
6122 This macro is obsolescent, as @file{time.h} defines @code{struct tm} in
6123 current systems.  New programs need not use this macro.
6124 @end defmac
6126 @anchor{AC_STRUCT_TIMEZONE}
6127 @defmac AC_STRUCT_TIMEZONE
6128 @acindex{STRUCT_TIMEZONE}
6129 @cvindex HAVE_DECL_TZNAME
6130 @cvindex HAVE_STRUCT_TM_TM_ZONE
6131 @cvindex HAVE_TM_ZONE
6132 @cvindex HAVE_TZNAME
6133 Figure out how to get the current timezone.  If @code{struct tm} has a
6134 @code{tm_zone} member, define @code{HAVE_STRUCT_TM_TM_ZONE} (and the
6135 obsoleted @code{HAVE_TM_ZONE}).  Otherwise, if the external array
6136 @code{tzname} is found, define @code{HAVE_TZNAME}; if it is declared,
6137 define @code{HAVE_DECL_TZNAME}.
6138 @end defmac
6140 @node Generic Structures
6141 @subsection Generic Structure Checks
6143 These macros are used to find structure members not covered by the
6144 ``particular'' test macros.
6146 @defmac AC_CHECK_MEMBER (@var{aggregate}.@var{member}, @
6147   @ovar{action-if-found}, @ovar{action-if-not-found}, @
6148   @dvar{includes, AC_INCLUDES_DEFAULT})
6149 @acindex{CHECK_MEMBER}
6150 Check whether @var{member} is a member of the aggregate @var{aggregate}.
6151 If no @var{includes} are specified, the default includes are used
6152 (@pxref{Default Includes}).
6154 @example
6155 AC_CHECK_MEMBER([struct passwd.pw_gecos], [],
6156                 [AC_MSG_ERROR([We need `passwd.pw_gecos'!])],
6157                 [[#include <pwd.h>]])
6158 @end example
6160 You can use this macro for submembers:
6162 @example
6163 AC_CHECK_MEMBER(struct top.middle.bot)
6164 @end example
6165 @end defmac
6167 @anchor{AC_CHECK_MEMBERS}
6168 @defmac AC_CHECK_MEMBERS (@var{members}, @ovar{action-if-found}, @
6169   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6170 @acindex{CHECK_MEMBERS}
6171 @cvindex HAVE_@var{aggregate}_@var{member}
6172 Check for the existence of each @samp{@var{aggregate}.@var{member}} of
6173 @var{members} using the previous macro.  When @var{member} belongs to
6174 @var{aggregate}, define @code{HAVE_@var{aggregate}_@var{member}} (in all
6175 capitals, with spaces and dots replaced by underscores).  If
6176 @var{action-if-found} is given, it is executed for each of the found
6177 members.  If @var{action-if-not-found} is given, it is executed for each
6178 of the members that could not be found.
6180 @var{includes} is a series of include directives, defaulting to
6181 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
6182 prior to the members under test.
6184 This macro uses M4 lists:
6185 @example
6186 AC_CHECK_MEMBERS([struct stat.st_rdev, struct stat.st_blksize])
6187 @end example
6188 @end defmac
6191 @node Types
6192 @section Types
6193 @cindex Types
6194 @cindex C types
6196 The following macros check for C types, either builtin or typedefs.  If
6197 there is no macro specifically defined to check for a type you need, and
6198 you don't need to check for any special properties of it, then you can
6199 use a general type-check macro.
6201 @menu
6202 * Particular Types::            Special handling to find certain types
6203 * Generic Types::               How to find other types
6204 @end menu
6206 @node Particular Types
6207 @subsection Particular Type Checks
6209 @hdrindex{sys/types.h}
6210 @hdrindex{stdlib.h}
6211 @hdrindex{stdint.h}
6212 @hdrindex{inttypes.h}
6213 These macros check for particular C types in @file{sys/types.h},
6214 @file{stdlib.h}, @file{stdint.h}, @file{inttypes.h} and others, if they
6215 exist.
6217 The Gnulib @code{stdint} module is an alternate way to define many of
6218 these symbols; it is useful if you prefer your code to assume a
6219 C99-or-better environment.  @xref{Gnulib}.
6221 @anchor{AC_TYPE_GETGROUPS}
6222 @defmac AC_TYPE_GETGROUPS
6223 @acindex{TYPE_GETGROUPS}
6224 @cvindex GETGROUPS_T
6225 Define @code{GETGROUPS_T} to be whichever of @code{gid_t} or @code{int}
6226 is the base type of the array argument to @code{getgroups}.
6227 @end defmac
6229 @defmac AC_TYPE_INT8_T
6230 @acindex{TYPE_INT8_T}
6231 @cvindex HAVE_INT8_T
6232 @cvindex int8_t
6233 If @file{stdint.h} or @file{inttypes.h} does not define the type
6234 @code{int8_t}, define @code{int8_t} to a signed
6235 integer type that is exactly 8 bits wide and that uses two's complement
6236 representation, if such a type exists.
6237 If you are worried about porting to hosts that lack such a type, you can
6238 use the results of this macro in C89-or-later code as follows:
6240 @example
6241 #if HAVE_STDINT_H
6242 # include <stdint.h>
6243 #endif
6244 #if defined INT8_MAX || defined int8_t
6245  @emph{code using int8_t}
6246 #else
6247  @emph{complicated alternative using >8-bit 'signed char'}
6248 #endif
6249 @end example
6250 @end defmac
6252 @defmac AC_TYPE_INT16_T
6253 @acindex{TYPE_INT16_T}
6254 @cvindex HAVE_INT16_T
6255 @cvindex int16_t
6256 This is like @code{AC_TYPE_INT8_T}, except for 16-bit integers.
6257 @end defmac
6259 @defmac AC_TYPE_INT32_T
6260 @acindex{TYPE_INT32_T}
6261 @cvindex HAVE_INT32_T
6262 @cvindex int32_t
6263 This is like @code{AC_TYPE_INT8_T}, except for 32-bit integers.
6264 @end defmac
6266 @defmac AC_TYPE_INT64_T
6267 @acindex{TYPE_INT64_T}
6268 @cvindex HAVE_INT64_T
6269 @cvindex int64_t
6270 This is like @code{AC_TYPE_INT8_T}, except for 64-bit integers.
6271 @end defmac
6273 @defmac AC_TYPE_INTMAX_T
6274 @acindex{TYPE_INTMAX_T}
6275 @cvindex HAVE_INTMAX_T
6276 @cvindex intmax_t
6277 If @file{stdint.h} or @file{inttypes.h} defines the type @code{intmax_t},
6278 define @code{HAVE_INTMAX_T}.  Otherwise, define @code{intmax_t} to the
6279 widest signed integer type.
6280 @end defmac
6282 @defmac AC_TYPE_INTPTR_T
6283 @acindex{TYPE_INTPTR_T}
6284 @cvindex HAVE_INTPTR_T
6285 @cvindex intptr_t
6286 If @file{stdint.h} or @file{inttypes.h} defines the type @code{intptr_t},
6287 define @code{HAVE_INTPTR_T}.  Otherwise, define @code{intptr_t} to a
6288 signed integer type wide enough to hold a pointer, if such a type
6289 exists.
6290 @end defmac
6292 @defmac AC_TYPE_LONG_DOUBLE
6293 @acindex{TYPE_LONG_DOUBLE}
6294 @cvindex HAVE_LONG_DOUBLE
6295 If the C compiler supports a working @code{long double} type, define
6296 @code{HAVE_LONG_DOUBLE}.  The @code{long double} type might have the
6297 same range and precision as @code{double}.
6299 This macro is obsolescent, as current C compilers support @code{long
6300 double}.  New programs need not use this macro.
6301 @end defmac
6303 @defmac AC_TYPE_LONG_DOUBLE_WIDER
6304 @acindex{TYPE_LONG_DOUBLE_WIDER}
6305 @cvindex HAVE_LONG_DOUBLE_WIDER
6306 If the C compiler supports a working @code{long double} type with more
6307 range or precision than the @code{double} type, define
6308 @code{HAVE_LONG_DOUBLE_WIDER}.
6309 @end defmac
6311 @defmac AC_TYPE_LONG_LONG_INT
6312 @acindex{TYPE_LONG_LONG_INT}
6313 @cvindex HAVE_LONG_LONG_INT
6314 If the C compiler supports a working @code{long long int} type, define
6315 @code{HAVE_LONG_LONG_INT}.  However, this test does not test
6316 @code{long long int} values in preprocessor @code{#if} expressions,
6317 because too many compilers mishandle such expressions.
6318 @xref{Preprocessor Arithmetic}.
6319 @end defmac
6321 @defmac AC_TYPE_MBSTATE_T
6322 @acindex{TYPE_MBSTATE_T}
6323 @cvindex mbstate_t
6324 @hdrindex{wchar.h}
6325 Define @code{HAVE_MBSTATE_T} if @code{<wchar.h>} declares the
6326 @code{mbstate_t} type.  Also, define @code{mbstate_t} to be a type if
6327 @code{<wchar.h>} does not declare it.
6328 @end defmac
6330 @anchor{AC_TYPE_MODE_T}
6331 @defmac AC_TYPE_MODE_T
6332 @acindex{TYPE_MODE_T}
6333 @cvindex mode_t
6334 Define @code{mode_t} to a suitable type, if standard headers do not
6335 define it.
6336 @end defmac
6338 @anchor{AC_TYPE_OFF_T}
6339 @defmac AC_TYPE_OFF_T
6340 @acindex{TYPE_OFF_T}
6341 @cvindex off_t
6342 Define @code{off_t} to a suitable type, if standard headers do not
6343 define it.
6344 @end defmac
6346 @anchor{AC_TYPE_PID_T}
6347 @defmac AC_TYPE_PID_T
6348 @acindex{TYPE_PID_T}
6349 @cvindex pid_t
6350 Define @code{pid_t} to a suitable type, if standard headers do not
6351 define it.
6352 @end defmac
6354 @anchor{AC_TYPE_SIZE_T}
6355 @defmac AC_TYPE_SIZE_T
6356 @acindex{TYPE_SIZE_T}
6357 @cvindex size_t
6358 Define @code{size_t} to a suitable type, if standard headers do not
6359 define it.
6360 @end defmac
6362 @defmac AC_TYPE_SSIZE_T
6363 @acindex{TYPE_SSIZE_T}
6364 @cvindex ssize_t
6365 Define @code{ssize_t} to a suitable type, if standard headers do not
6366 define it.
6367 @end defmac
6369 @anchor{AC_TYPE_UID_T}
6370 @defmac AC_TYPE_UID_T
6371 @acindex{TYPE_UID_T}
6372 @cvindex uid_t
6373 @cvindex gid_t
6374 Define @code{uid_t} and @code{gid_t} to suitable types, if standard
6375 headers do not define them.
6376 @end defmac
6378 @defmac AC_TYPE_UINT8_T
6379 @acindex{TYPE_UINT8_T}
6380 @cvindex HAVE_UINT8_T
6381 @cvindex uint8_t
6382 If @file{stdint.h} or @file{inttypes.h} does not define the type
6383 @code{uint8_t}, define @code{uint8_t} to an
6384 unsigned integer type that is exactly 8 bits wide, if such a type
6385 exists.
6386 This is like @code{AC_TYPE_INT8_T}, except for unsigned integers.
6387 @end defmac
6389 @defmac AC_TYPE_UINT16_T
6390 @acindex{TYPE_UINT16_T}
6391 @cvindex HAVE_UINT16_T
6392 @cvindex uint16_t
6393 This is like @code{AC_TYPE_UINT8_T}, except for 16-bit integers.
6394 @end defmac
6396 @defmac AC_TYPE_UINT32_T
6397 @acindex{TYPE_UINT32_T}
6398 @cvindex HAVE_UINT32_T
6399 @cvindex uint32_t
6400 This is like @code{AC_TYPE_UINT8_T}, except for 32-bit integers.
6401 @end defmac
6403 @defmac AC_TYPE_UINT64_T
6404 @acindex{TYPE_UINT64_T}
6405 @cvindex HAVE_UINT64_T
6406 @cvindex uint64_t
6407 This is like @code{AC_TYPE_UINT8_T}, except for 64-bit integers.
6408 @end defmac
6410 @defmac AC_TYPE_UINTMAX_T
6411 @acindex{TYPE_UINTMAX_T}
6412 @cvindex HAVE_UINTMAX_T
6413 @cvindex uintmax_t
6414 If @file{stdint.h} or @file{inttypes.h} defines the type @code{uintmax_t},
6415 define @code{HAVE_UINTMAX_T}.  Otherwise, define @code{uintmax_t} to the
6416 widest unsigned integer type.
6417 @end defmac
6419 @defmac AC_TYPE_UINTPTR_T
6420 @acindex{TYPE_UINTPTR_T}
6421 @cvindex HAVE_UINTPTR_T
6422 @cvindex uintptr_t
6423 If @file{stdint.h} or @file{inttypes.h} defines the type @code{uintptr_t},
6424 define @code{HAVE_UINTPTR_T}.  Otherwise, define @code{uintptr_t} to an
6425 unsigned integer type wide enough to hold a pointer, if such a type
6426 exists.
6427 @end defmac
6429 @defmac AC_TYPE_UNSIGNED_LONG_LONG_INT
6430 @acindex{TYPE_UNSIGNED_LONG_LONG_INT}
6431 @cvindex HAVE_UNSIGNED_LONG_LONG_INT
6432 If the C compiler supports a working @code{unsigned long long int} type,
6433 define @code{HAVE_UNSIGNED_LONG_LONG_INT}.  However, this test does not test
6434 @code{unsigned long long int} values in preprocessor @code{#if} expressions,
6435 because too many compilers mishandle such expressions.
6436 @xref{Preprocessor Arithmetic}.
6437 @end defmac
6439 @node Generic Types
6440 @subsection Generic Type Checks
6442 These macros are used to check for types not covered by the ``particular''
6443 test macros.
6445 @defmac AC_CHECK_TYPE (@var{type}, @ovar{action-if-found}, @
6446   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6447 @acindex{CHECK_TYPE}
6448 Check whether @var{type} is defined.  It may be a compiler builtin type
6449 or defined by the @var{includes}.  @var{includes} is a series of include
6450 directives, defaulting to @code{AC_INCLUDES_DEFAULT} (@pxref{Default
6451 Includes}), which are used prior to the type under test.
6453 In C, @var{type} must be a type-name, so that the expression @samp{sizeof
6454 (@var{type})} is valid (but @samp{sizeof ((@var{type}))} is not).  The
6455 same test is applied when compiling for C++, which means that in C++
6456 @var{type} should be a type-id and should not be an anonymous
6457 @samp{struct} or @samp{union}.
6458 @end defmac
6461 @defmac AC_CHECK_TYPES (@var{types}, @ovar{action-if-found}, @
6462   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6463 @acindex{CHECK_TYPES}
6464 @cvindex HAVE_@var{type}
6465 For each @var{type} of the @var{types} that is defined, define
6466 @code{HAVE_@var{type}} (in all capitals).  Each @var{type} must follow
6467 the rules of @code{AC_CHECK_TYPE}.  If no @var{includes} are
6468 specified, the default includes are used (@pxref{Default Includes}).  If
6469 @var{action-if-found} is given, it is additional shell code to execute
6470 when one of the types is found.  If @var{action-if-not-found} is given,
6471 it is executed when one of the types is not found.
6473 This macro uses M4 lists:
6474 @example
6475 AC_CHECK_TYPES([ptrdiff_t])
6476 AC_CHECK_TYPES([unsigned long long int, uintmax_t])
6477 AC_CHECK_TYPES([float_t], [], [], [[#include <math.h>]])
6478 @end example
6480 @end defmac
6482 Autoconf, up to 2.13, used to provide to another version of
6483 @code{AC_CHECK_TYPE}, broken by design.  In order to keep backward
6484 compatibility, a simple heuristic, quite safe but not totally, is
6485 implemented.  In case of doubt, read the documentation of the former
6486 @code{AC_CHECK_TYPE}, see @ref{Obsolete Macros}.
6489 @node Compilers and Preprocessors
6490 @section Compilers and Preprocessors
6491 @cindex Compilers
6492 @cindex Preprocessors
6494 @ovindex EXEEXT
6495 All the tests for compilers (@code{AC_PROG_CC}, @code{AC_PROG_CXX},
6496 @code{AC_PROG_F77}) define the output variable @code{EXEEXT} based on
6497 the output of the compiler, typically to the empty string if
6498 Posix and @samp{.exe} if a @acronym{DOS} variant.
6500 @ovindex OBJEXT
6501 They also define the output variable @code{OBJEXT} based on the
6502 output of the compiler, after @file{.c} files have been excluded, typically
6503 to @samp{o} if Posix, @samp{obj} if a @acronym{DOS} variant.
6505 If the compiler being used does not produce executables, the tests fail.  If
6506 the executables can't be run, and cross-compilation is not enabled, they
6507 fail too.  @xref{Manual Configuration}, for more on support for cross
6508 compiling.
6510 @menu
6511 * Specific Compiler Characteristics::  Some portability issues
6512 * Generic Compiler Characteristics::  Language independent tests and features
6513 * C Compiler::                  Checking its characteristics
6514 * C++ Compiler::                Likewise
6515 * Objective C Compiler::        Likewise
6516 * Erlang Compiler and Interpreter::  Likewise
6517 * Fortran Compiler::            Likewise
6518 @end menu
6520 @node Specific Compiler Characteristics
6521 @subsection Specific Compiler Characteristics
6523 Some compilers exhibit different behaviors.
6525 @table @asis
6526 @item Static/Dynamic Expressions
6527 Autoconf relies on a trick to extract one bit of information from the C
6528 compiler: using negative array sizes.  For instance the following
6529 excerpt of a C source demonstrates how to test whether @samp{int} objects are 4
6530 bytes wide:
6532 @example
6533 static int test_array[sizeof (int) == 4 ? 1 : -1];
6534 @end example
6536 @noindent
6537 To our knowledge, there is a single compiler that does not support this
6538 trick: the @acronym{HP} C compilers (the real ones, not only the
6539 ``bundled'') on @acronym{HP-UX} 11.00.
6540 They incorrectly reject the above program with the diagnostic
6541 ``Variable-length arrays cannot have static storage.''
6542 This bug comes from @acronym{HP} compilers' mishandling of @code{sizeof (int)},
6543 not from the @code{? 1 : -1}, and
6544 Autoconf works around this problem by casting @code{sizeof (int)} to
6545 @code{long int} before comparing it.
6546 @end table
6548 @node Generic Compiler Characteristics
6549 @subsection Generic Compiler Characteristics
6551 @anchor{AC_CHECK_SIZEOF}
6552 @defmac AC_CHECK_SIZEOF (@var{type-or-expr}, @ovar{unused}, @
6553   @dvar{includes, AC_INCLUDES_DEFAULT})
6554 @acindex{CHECK_SIZEOF}
6555 @cvindex SIZEOF_@var{type-or-expr}
6556 Define @code{SIZEOF_@var{type-or-expr}} (@pxref{Standard Symbols}) to be
6557 the size in bytes of @var{type-or-expr}, which may be either a type or
6558 an expression returning a value that has a size.  If the expression
6559 @samp{sizeof (@var{type-or-expr})} is invalid, the result is 0.
6560 @var{includes} is a series of include directives, defaulting to
6561 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
6562 prior to the expression under test.
6564 This macro now works even when cross-compiling.  The @var{unused}
6565 argument was used when cross-compiling.
6567 For example, the call
6569 @example
6570 AC_CHECK_SIZEOF([int *])
6571 @end example
6573 @noindent
6574 defines @code{SIZEOF_INT_P} to be 8 on DEC Alpha AXP systems.
6575 @end defmac
6577 @defmac AC_CHECK_ALIGNOF (@var{type}, @dvar{includes, AC_INCLUDES_DEFAULT})
6578 @acindex{CHECK_ALIGNOF}
6579 @cvindex ALIGNOF_@var{type}
6580 Define @code{ALIGNOF_@var{type}} (@pxref{Standard Symbols}) to be the
6581 alignment in bytes of @var{type}.  @samp{@var{type} y;} must be valid as
6582 a structure member declaration.  If @samp{type} is unknown, the result
6583 is 0.  If no @var{includes} are specified, the default includes are used
6584 (@pxref{Default Includes}).
6585 @end defmac
6587 @defmac AC_COMPUTE_INT (@var{var}, @var{expression}, @
6588   @dvar{includes, AC_INCLUDES_DEFAULT}, @ovar{action-if-fails})
6589 @acindex{COMPUTE_INT}
6590 Store into the shell variable @var{var} the value of the integer
6591 @var{expression}.  The
6592 value should fit in an initializer in a C variable of type @code{signed
6593 long}.  To support cross compilation (in which case, the macro only works on
6594 hosts that use twos-complement arithmetic), it should be possible to evaluate
6595 the expression at compile-time.  If no @var{includes} are specified, the
6596 default includes are used (@pxref{Default Includes}).
6598 Execute @var{action-if-fails} if the value cannot be determined correctly.
6599 @end defmac
6601 @defmac AC_LANG_WERROR
6602 @acindex{LANG_WERROR}
6603 Normally Autoconf ignores warnings generated by the compiler, linker, and
6604 preprocessor.  If this macro is used, warnings count as fatal
6605 errors for the current language.  This macro is useful when the
6606 results of configuration are used where warnings are unacceptable; for
6607 instance, if parts of a program are built with the @acronym{GCC}
6608 @option{-Werror}
6609 option.  If the whole program is built using @option{-Werror} it is
6610 often simpler to put @option{-Werror} in the compiler flags (@code{CFLAGS},
6611 etc.).
6612 @end defmac
6614 @defmac AC_OPENMP
6615 @acindex{OPENMP}
6616 @cvindex _OPENMP
6617 @ovindex OPENMP_CFLAGS
6618 @ovindex OPENMP_CXXFLAGS
6619 @ovindex OPENMP_FFLAGS
6620 @ovindex OPENMP_FCFLAGS
6621 OpenMP (@url{http://@/www.openmp.org/}) specifies extensions of C, C++,
6622 and Fortran that simplify optimization of shared memory parallelism,
6623 which is a common problem on multicore CPUs.
6625 If the current language is C, the macro @code{AC_OPENMP} sets the
6626 variable @code{OPENMP_CFLAGS} to the C compiler flags needed for
6627 supporting OpenMP@.  @code{OPENMP_CFLAGS} is set to empty if the
6628 compiler already supports OpenMP, if it has no way to activate OpenMP
6629 support, or if the user rejects OpenMP support by invoking
6630 @samp{configure} with the @samp{--disable-openmp} option.
6632 @code{OPENMP_CFLAGS} needs to be used when compiling programs, when
6633 preprocessing program source, and when linking programs.  Therefore you
6634 need to add @code{$(OPENMP_CFLAGS)} to the @code{CFLAGS} of C programs
6635 that use OpenMP@.  If you preprocess OpenMP-specific C code, you also
6636 need to add @code{$(OPENMP_CFLAGS)} to @code{CPPFLAGS}.  The presence of
6637 OpenMP support is revealed at compile time by the preprocessor macro
6638 @code{_OPENMP}.
6640 Linking a program with @code{OPENMP_CFLAGS} typically adds one more
6641 shared library to the program's dependencies, so its use is recommended
6642 only on programs that actually require OpenMP.
6644 If the current language is C++, @code{AC_OPENMP} sets the variable
6645 @code{OPENMP_CXXFLAGS}, suitably for the C++ compiler.  The same remarks
6646 hold as for C.
6648 If the current language is Fortran 77 or Fortran, @code{AC_OPENMP} sets
6649 the variable @code{OPENMP_FFLAGS} or @code{OPENMP_FCFLAGS},
6650 respectively.  Similar remarks as for C hold, except that
6651 @code{CPPFLAGS} is not used for Fortran, and no preprocessor macro
6652 signals OpenMP support.
6654 For portability, it is best to avoid spaces between @samp{#} and
6655 @samp{pragma omp}.  That is, write @samp{#pragma omp}, not
6656 @samp{# pragma omp}.  The Sun WorkShop 6.2 C compiler chokes on the
6657 latter.
6658 @end defmac
6660 @node C Compiler
6661 @subsection C Compiler Characteristics
6663 The following macros provide ways to find and exercise a C Compiler.
6664 There are a few constructs that ought to be avoided, but do not deserve
6665 being checked for, since they can easily be worked around.
6667 @table @asis
6668 @item Don't use lines containing solitary backslashes
6669 They tickle a bug in the @acronym{HP-UX} C compiler (checked on
6670 @acronym{HP-UX} 10.20,
6671 11.00, and 11i).  When given the following source:
6673 @example
6674 #ifdef __STDC__
6676 * A comment with backslash-newlines in it.  %@{ %@} *\
6679 char str[] = "\\
6680 " A string with backslash-newlines in it %@{ %@} \\
6682 char apostrophe = '\\
6686 #endif
6687 @end example
6689 @noindent
6690 the compiler incorrectly fails with the diagnostics ``Non-terminating
6691 comment at end of file'' and ``Missing @samp{#endif} at end of file.''
6692 Removing the lines with solitary backslashes solves the problem.
6694 @item Don't compile several files at once if output matters to you
6695 Some compilers, such as @acronym{HP}'s, report names of files being
6696 compiled when given more than one file operand.  For instance:
6698 @example
6699 $ @kbd{cc a.c b.c}
6700 a.c:
6701 b.c:
6702 @end example
6704 @noindent
6705 This can cause problems if you observe the output of the compiler to
6706 detect failures.  Invoking @samp{cc -c a.c && cc -c b.c && cc -o c a.o
6707 b.o} solves the issue.
6709 @item Don't rely on @code{#error} failing
6710 The @sc{irix} C compiler does not fail when #error is preprocessed; it
6711 simply emits a diagnostic and continues, exiting successfully.  So,
6712 instead of an error directive like @code{#error "Unsupported word size"}
6713 it is more portable to use an invalid directive like @code{#Unsupported
6714 word size} in Autoconf tests.  In ordinary source code, @code{#error} is
6715 OK, since installers with inadequate compilers like @sc{irix} can simply
6716 examine these compilers' diagnostic output.
6718 @item Don't rely on correct @code{#line} support
6719 On Solaris, @command{c89} (at least Sun C 5.3 through 5.8)
6720 diagnoses @code{#line} directives whose line
6721 numbers are greater than 32767.  Nothing in Posix
6722 makes this invalid.  That is why Autoconf stopped issuing
6723 @code{#line} directives.
6724 @end table
6726 @defmac AC_PROG_CC (@ovar{compiler-search-list})
6727 @acindex{PROG_CC}
6728 @evindex CC
6729 @evindex CFLAGS
6730 @ovindex CC
6731 @ovindex CFLAGS
6732 Determine a C compiler to use.  If @code{CC} is not already set in the
6733 environment, check for @code{gcc} and @code{cc}, then for other C
6734 compilers.  Set output variable @code{CC} to the name of the compiler
6735 found.
6737 This macro may, however, be invoked with an optional first argument
6738 which, if specified, must be a blank-separated list of C compilers to
6739 search for.  This just gives the user an opportunity to specify an
6740 alternative search list for the C compiler.  For example, if you didn't
6741 like the default order, then you could invoke @code{AC_PROG_CC} like
6742 this:
6744 @example
6745 AC_PROG_CC([gcc cl cc])
6746 @end example
6748 If the C compiler does not handle function prototypes correctly by
6749 default, try to add an option to output variable @code{CC} to make it
6750 so.  This macro tries various options that select standard-conformance
6751 modes on various systems.
6753 After calling this macro you can check whether the C compiler has been
6754 set to accept @acronym{ANSI} C89 (@acronym{ISO} C90); if not, the shell
6755 variable
6756 @code{ac_cv_prog_cc_c89} is set to @samp{no}.  See also
6757 @code{AC_C_PROTOTYPES} below.
6759 If using the @acronym{GNU} C compiler, set shell variable @code{GCC} to
6760 @samp{yes}.  If output variable @code{CFLAGS} was not already set, set
6761 it to @option{-g -O2} for the @acronym{GNU} C compiler (@option{-O2} on systems
6762 where @acronym{GCC} does not accept @option{-g}), or @option{-g} for
6763 other compilers.
6765 Many Autoconf macros use a compiler, and thus call
6766 @samp{AC_REQUIRE([AC_PROG_CC])} to ensure that the compiler has been
6767 determined before the body of the outermost @code{AC_DEFUN} macro.
6768 Although @code{AC_PROG_CC} is safe to directly expand multiple times, it
6769 performs certain checks (such as the proper value of @env{EXEEXT}) only
6770 on the first invocation.  Therefore, care must be used when invoking
6771 this macro from within another macro rather than at the top level
6772 (@pxref{Expanded Before Required}).
6773 @end defmac
6775 @anchor{AC_PROG_CC_C_O}
6776 @defmac AC_PROG_CC_C_O
6777 @acindex{PROG_CC_C_O}
6778 @cvindex NO_MINUS_C_MINUS_O
6779 If the C compiler does not accept the @option{-c} and @option{-o} options
6780 simultaneously, define @code{NO_MINUS_C_MINUS_O}.  This macro actually
6781 tests both the compiler found by @code{AC_PROG_CC}, and, if different,
6782 the first @code{cc} in the path.  The test fails if one fails.  This
6783 macro was created for @acronym{GNU} Make to choose the default C compilation
6784 rule.
6785 @end defmac
6788 @defmac AC_PROG_CPP
6789 @acindex{PROG_CPP}
6790 @evindex CPP
6791 @ovindex CPP
6792 Set output variable @code{CPP} to a command that runs the
6793 C preprocessor.  If @samp{$CC -E} doesn't work, @file{/lib/cpp} is used.
6794 It is only portable to run @code{CPP} on files with a @file{.c}
6795 extension.
6797 Some preprocessors don't indicate missing include files by the error
6798 status.  For such preprocessors an internal variable is set that causes
6799 other macros to check the standard error from the preprocessor and
6800 consider the test failed if any warnings have been reported.
6801 For most preprocessors, though, warnings do not cause include-file
6802 tests to fail unless @code{AC_PROG_CPP_WERROR} is also specified.
6803 @end defmac
6805 @defmac AC_PROG_CPP_WERROR
6806 @acindex{PROG_CPP_WERROR}
6807 @ovindex CPP
6808 This acts like @code{AC_PROG_CPP}, except it treats warnings from the
6809 preprocessor as errors even if the preprocessor exit status indicates
6810 success.  This is useful for avoiding headers that generate mandatory
6811 warnings, such as deprecation notices.
6812 @end defmac
6815 The following macros check for C compiler or machine architecture
6816 features.  To check for characteristics not listed here, use
6817 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}) or
6818 @code{AC_RUN_IFELSE} (@pxref{Runtime}).
6820 @defmac AC_PROG_CC_STDC
6821 @acindex{PROG_CC_STDC}
6822 If the C compiler cannot compile @acronym{ISO} Standard C (currently
6823 C99), try to add an option to output variable @code{CC} to make it work.
6824 If the compiler does not support C99, fall back to supporting
6825 @acronym{ANSI} C89 (@acronym{ISO} C90).
6827 After calling this macro you can check whether the C compiler has been
6828 set to accept Standard C; if not, the shell variable
6829 @code{ac_cv_prog_cc_stdc} is set to @samp{no}.
6830 @end defmac
6832 @defmac AC_PROG_CC_C89
6833 @acindex{PROG_CC_C89}
6834 If the C compiler is not in @acronym{ANSI} C89 (@acronym{ISO} C90) mode by
6835 default, try to add an option to output variable @code{CC} to make it
6836 so.  This macro tries various options that select @acronym{ANSI} C89 on
6837 some system or another, preferring extended functionality modes over
6838 strict conformance modes.  It considers the compiler to be in
6839 @acronym{ANSI} C89 mode if it handles function prototypes correctly.
6841 After calling this macro you can check whether the C compiler has been
6842 set to accept @acronym{ANSI} C89; if not, the shell variable
6843 @code{ac_cv_prog_cc_c89} is set to @samp{no}.
6845 This macro is called automatically by @code{AC_PROG_CC}.
6846 @end defmac
6848 @defmac AC_PROG_CC_C99
6849 @acindex{PROG_CC_C99}
6850 If the C compiler is not in C99 mode by default, try to add an
6851 option to output variable @code{CC} to make it so.  This macro tries
6852 various options that select C99 on some system or another, preferring
6853 extended functionality modes over strict conformance modes.  It
6854 considers the compiler to be in C99 mode if it handles @code{_Bool},
6855 @code{//} comments, flexible array members, @code{inline}, signed and
6856 unsigned @code{long long int}, mixed code and declarations, named
6857 initialization of structs,
6858 @code{restrict}, @code{va_copy}, varargs macros, variable declarations
6859 in @code{for} loops, and variable length arrays.
6861 After calling this macro you can check whether the C compiler has been
6862 set to accept C99; if not, the shell variable
6863 @code{ac_cv_prog_cc_c99} is set to @samp{no}.
6864 @end defmac
6866 @defmac AC_C_BACKSLASH_A
6867 @acindex{C_BACKSLASH_A}
6868 @cvindex HAVE_C_BACKSLASH_A
6869 Define @samp{HAVE_C_BACKSLASH_A} to 1 if the C compiler understands
6870 @samp{\a}.
6872 This macro is obsolescent, as current C compilers understand @samp{\a}.
6873 New programs need not use this macro.
6874 @end defmac
6876 @anchor{AC_C_BIGENDIAN}
6877 @defmac AC_C_BIGENDIAN (@ovar{action-if-true}, @ovar{action-if-false}, @
6878   @ovar{action-if-unknown}, @ovar{action-if-universal})
6879 @acindex{C_BIGENDIAN}
6880 @cvindex WORDS_BIGENDIAN
6881 @cindex Endianness
6882 If words are stored with the most significant byte first (like Motorola
6883 and SPARC CPUs), execute @var{action-if-true}.  If words are stored with
6884 the least significant byte first (like Intel and VAX CPUs), execute
6885 @var{action-if-false}.
6887 This macro runs a test-case if endianness cannot be determined from the
6888 system header files.  When cross-compiling, the test-case is not run but
6889 grep'ed for some magic values.  @var{action-if-unknown} is executed if
6890 the latter case fails to determine the byte sex of the host system.
6892 In some cases a single run of a compiler can generate code for multiple
6893 architectures.  This can happen, for example, when generating Mac OS X
6894 universal binary files, which work on both PowerPC and Intel
6895 architectures.  In this case, the different variants might be for
6896 different architectures whose endiannesses differ.  If
6897 @command{configure} detects this, it executes @var{action-if-universal}
6898 instead of @var{action-if-unknown}.
6900 The default for @var{action-if-true} is to define
6901 @samp{WORDS_BIGENDIAN}.  The default for @var{action-if-false} is to do
6902 nothing.  The default for @var{action-if-unknown} is to
6903 abort configure and tell the installer how to bypass this test.
6904 And finally, the default for @var{action-if-universal} is to ensure that
6905 @samp{WORDS_BIGENDIAN} is defined if and only if a universal build is
6906 detected and the current code is big-endian; this default works only if
6907 @command{autoheader} is used (@pxref{autoheader Invocation}).
6909 If you use this macro without specifying @var{action-if-universal}, you
6910 should also use @code{AC_CONFIG_HEADERS}; otherwise
6911 @samp{WORDS_BIGENDIAN} may be set incorrectly for Mac OS X universal
6912 binary files.
6913 @end defmac
6915 @anchor{AC_C_CONST}
6916 @defmac AC_C_CONST
6917 @acindex{C_CONST}
6918 @cvindex const
6919 If the C compiler does not fully support the @code{const} keyword,
6920 define @code{const} to be empty.  Some C compilers that do
6921 not define @code{__STDC__} do support @code{const}; some compilers that
6922 define @code{__STDC__} do not completely support @code{const}.  Programs
6923 can simply use @code{const} as if every C compiler supported it; for
6924 those that don't, the makefile or configuration header file
6925 defines it as empty.
6927 Occasionally installers use a C++ compiler to compile C code, typically
6928 because they lack a C compiler.  This causes problems with @code{const},
6929 because C and C++ treat @code{const} differently.  For example:
6931 @example
6932 const int foo;
6933 @end example
6935 @noindent
6936 is valid in C but not in C++.  These differences unfortunately cannot be
6937 papered over by defining @code{const} to be empty.
6939 If @command{autoconf} detects this situation, it leaves @code{const} alone,
6940 as this generally yields better results in practice.  However, using a
6941 C++ compiler to compile C code is not recommended or supported, and
6942 installers who run into trouble in this area should get a C compiler
6943 like @acronym{GCC} to compile their C code.
6945 This macro is obsolescent, as current C compilers support @code{const}.
6946 New programs need not use this macro.
6947 @end defmac
6949 @defmac AC_C_RESTRICT
6950 @acindex{C_RESTRICT}
6951 @cvindex restrict
6952 If the C compiler recognizes a variant spelling for the @code{restrict}
6953 keyword (@code{__restrict}, @code{__restrict__}, or @code{_Restrict}),
6954 then define @code{restrict} to that; this is more likely to do the right
6955 thing with compilers that support language variants where plain
6956 @code{restrict} is not a keyword.  Otherwise, if the C compiler
6957 recognizes the @code{restrict} keyword, don't do anything.
6958 Otherwise, define @code{restrict} to be empty.
6959 Thus, programs may simply use @code{restrict} as if every C compiler
6960 supported it; for those that do not, the makefile
6961 or configuration header defines it away.
6963 Although support in C++ for the @code{restrict} keyword is not
6964 required, several C++ compilers do accept the keyword.
6965 This macro works for them, too.
6966 @end defmac
6968 @defmac AC_C_VOLATILE
6969 @acindex{C_VOLATILE}
6970 @cvindex volatile
6971 If the C compiler does not understand the keyword @code{volatile},
6972 define @code{volatile} to be empty.  Programs can simply use
6973 @code{volatile} as if every C compiler supported it; for those that do
6974 not, the makefile or configuration header defines it as
6975 empty.
6977 If the correctness of your program depends on the semantics of
6978 @code{volatile}, simply defining it to be empty does, in a sense, break
6979 your code.  However, given that the compiler does not support
6980 @code{volatile}, you are at its mercy anyway.  At least your
6981 program compiles, when it wouldn't before.
6982 @xref{Volatile Objects}, for more about @code{volatile}.
6984 In general, the @code{volatile} keyword is a standard C feature, so
6985 you might expect that @code{volatile} is available only when
6986 @code{__STDC__} is defined.  However, Ultrix 4.3's native compiler does
6987 support volatile, but does not define @code{__STDC__}.
6989 This macro is obsolescent, as current C compilers support @code{volatile}.
6990 New programs need not use this macro.
6991 @end defmac
6993 @anchor{AC_C_INLINE}
6994 @defmac AC_C_INLINE
6995 @acindex{C_INLINE}
6996 @cvindex inline
6997 If the C compiler supports the keyword @code{inline}, do nothing.
6998 Otherwise define @code{inline} to @code{__inline__} or @code{__inline}
6999 if it accepts one of those, otherwise define @code{inline} to be empty.
7000 @end defmac
7002 @anchor{AC_C_CHAR_UNSIGNED}
7003 @defmac AC_C_CHAR_UNSIGNED
7004 @acindex{C_CHAR_UNSIGNED}
7005 @cvindex __CHAR_UNSIGNED__
7006 If the C type @code{char} is unsigned, define @code{__CHAR_UNSIGNED__},
7007 unless the C compiler predefines it.
7009 These days, using this macro is not necessary.  The same information can
7010 be determined by this portable alternative, thus avoiding the use of
7011 preprocessor macros in the namespace reserved for the implementation.
7013 @example
7014 #include <limits.h>
7015 #if CHAR_MIN == 0
7016 # define CHAR_UNSIGNED 1
7017 #endif
7018 @end example
7019 @end defmac
7021 @defmac AC_C_STRINGIZE
7022 @acindex{C_STRINGIZE}
7023 @cvindex HAVE_STRINGIZE
7024 If the C preprocessor supports the stringizing operator, define
7025 @code{HAVE_STRINGIZE}.  The stringizing operator is @samp{#} and is
7026 found in macros such as this:
7028 @example
7029 #define x(y) #y
7030 @end example
7032 This macro is obsolescent, as current C compilers support the
7033 stringizing operator.  New programs need not use this macro.
7034 @end defmac
7036 @defmac AC_C_FLEXIBLE_ARRAY_MEMBER
7037 @acindex{C_FLEXIBLE_ARRAY_MEMBER}
7038 @cvindex FLEXIBLE_ARRAY_MEMBER
7039 If the C compiler supports flexible array members, define
7040 @code{FLEXIBLE_ARRAY_MEMBER} to nothing; otherwise define it to 1.
7041 That way, a declaration like this:
7043 @example
7044 struct s
7045   @{
7046     size_t n_vals;
7047     double val[FLEXIBLE_ARRAY_MEMBER];
7048   @};
7049 @end example
7051 @noindent
7052 will let applications use the ``struct hack'' even with compilers that
7053 do not support flexible array members.  To allocate and use such an
7054 object, you can use code like this:
7056 @example
7057 size_t i;
7058 size_t n = compute_value_count ();
7059 struct s *p =
7060    malloc (offsetof (struct s, val)
7061            + n * sizeof (double));
7062 p->n_vals = n;
7063 for (i = 0; i < n; i++)
7064   p->val[i] = compute_value (i);
7065 @end example
7066 @end defmac
7068 @defmac AC_C_VARARRAYS
7069 @acindex{C_VARARRAYS}
7070 @cvindex HAVE_C_VARARRAYS
7071 If the C compiler supports variable-length arrays, define
7072 @code{HAVE_C_VARARRAYS}.  A variable-length array is an array of automatic
7073 storage duration whose length is determined at run time, when the array
7074 is declared.
7075 @end defmac
7077 @defmac AC_C_TYPEOF
7078 @acindex{C_TYPEOF}
7079 @cvindex HAVE_TYPEOF
7080 @cvindex typeof
7081 If the C compiler supports @acronym{GCC}'s @code{typeof} syntax either
7082 directly or
7083 through a different spelling of the keyword (e.g., @code{__typeof__}),
7084 define @code{HAVE_TYPEOF}.  If the support is available only through a
7085 different spelling, define @code{typeof} to that spelling.
7086 @end defmac
7088 @defmac AC_C_PROTOTYPES
7089 @acindex{C_PROTOTYPES}
7090 @cvindex PROTOTYPES
7091 @cvindex __PROTOTYPES
7092 @cvindex PARAMS
7093 If function prototypes are understood by the compiler (as determined by
7094 @code{AC_PROG_CC}), define @code{PROTOTYPES} and @code{__PROTOTYPES}.
7095 Defining @code{__PROTOTYPES} is for the benefit of
7096 header files that cannot use macros that infringe on user name space.
7098 This macro is obsolescent, as current C compilers support prototypes.
7099 New programs need not use this macro.
7100 @end defmac
7102 @anchor{AC_PROG_GCC_TRADITIONAL}
7103 @defmac AC_PROG_GCC_TRADITIONAL
7104 @acindex{PROG_GCC_TRADITIONAL}
7105 @ovindex CC
7106 Add @option{-traditional} to output variable @code{CC} if using the
7107 @acronym{GNU} C compiler and @code{ioctl} does not work properly without
7108 @option{-traditional}.  That usually happens when the fixed header files
7109 have not been installed on an old system.
7111 This macro is obsolescent, since current versions of the @acronym{GNU} C
7112 compiler fix the header files automatically when installed.
7113 @end defmac
7116 @node C++ Compiler
7117 @subsection C++ Compiler Characteristics
7120 @defmac AC_PROG_CXX (@ovar{compiler-search-list})
7121 @acindex{PROG_CXX}
7122 @evindex CXX
7123 @evindex CXXFLAGS
7124 @ovindex CXX
7125 @ovindex CXXFLAGS
7126 Determine a C++ compiler to use.  Check whether the environment variable
7127 @code{CXX} or @code{CCC} (in that order) is set; if so, then set output
7128 variable @code{CXX} to its value.
7130 Otherwise, if the macro is invoked without an argument, then search for
7131 a C++ compiler under the likely names (first @code{g++} and @code{c++}
7132 then other names).  If none of those checks succeed, then as a last
7133 resort set @code{CXX} to @code{g++}.
7135 This macro may, however, be invoked with an optional first argument
7136 which, if specified, must be a blank-separated list of C++ compilers to
7137 search for.  This just gives the user an opportunity to specify an
7138 alternative search list for the C++ compiler.  For example, if you
7139 didn't like the default order, then you could invoke @code{AC_PROG_CXX}
7140 like this:
7142 @example
7143 AC_PROG_CXX([gcc cl KCC CC cxx cc++ xlC aCC c++ g++])
7144 @end example
7146 If using the @acronym{GNU} C++ compiler, set shell variable @code{GXX} to
7147 @samp{yes}.  If output variable @code{CXXFLAGS} was not already set, set
7148 it to @option{-g -O2} for the @acronym{GNU} C++ compiler (@option{-O2} on
7149 systems where G++ does not accept @option{-g}), or @option{-g} for other
7150 compilers.
7151 @end defmac
7153 @defmac AC_PROG_CXXCPP
7154 @acindex{PROG_CXXCPP}
7155 @evindex CXXCPP
7156 @ovindex CXXCPP
7157 Set output variable @code{CXXCPP} to a command that runs the C++
7158 preprocessor.  If @samp{$CXX -E} doesn't work, @file{/lib/cpp} is used.
7159 It is portable to run @code{CXXCPP} only on files with a @file{.c},
7160 @file{.C}, @file{.cc}, or @file{.cpp} extension.
7162 Some preprocessors don't indicate missing include files by the error
7163 status.  For such preprocessors an internal variable is set that causes
7164 other macros to check the standard error from the preprocessor and
7165 consider the test failed if any warnings have been reported.  However,
7166 it is not known whether such broken preprocessors exist for C++.
7167 @end defmac
7169 @defmac AC_PROG_CXX_C_O
7170 @acindex{PROG_CXX_C_O}
7171 @cvindex CXX_NO_MINUS_C_MINUS_O
7172 Test whether the C++ compiler accepts the options @option{-c} and
7173 @option{-o} simultaneously, and define @code{CXX_NO_MINUS_C_MINUS_O},
7174 if it does not.
7175 @end defmac
7178 @node Objective C Compiler
7179 @subsection Objective C Compiler Characteristics
7182 @defmac AC_PROG_OBJC (@ovar{compiler-search-list})
7183 @acindex{PROG_OBJC}
7184 @evindex OBJC
7185 @evindex OBJCFLAGS
7186 @ovindex OBJC
7187 @ovindex OBJCFLAGS
7188 Determine an Objective C compiler to use.  If @code{OBJC} is not already
7189 set in the environment, check for Objective C compilers.  Set output
7190 variable @code{OBJC} to the name of the compiler found.
7192 This macro may, however, be invoked with an optional first argument
7193 which, if specified, must be a blank-separated list of Objective C compilers to
7194 search for.  This just gives the user an opportunity to specify an
7195 alternative search list for the Objective C compiler.  For example, if you
7196 didn't like the default order, then you could invoke @code{AC_PROG_OBJC}
7197 like this:
7199 @example
7200 AC_PROG_OBJC([gcc objcc objc])
7201 @end example
7203 If using the @acronym{GNU} Objective C compiler, set shell variable
7204 @code{GOBJC} to @samp{yes}.  If output variable @code{OBJCFLAGS} was not
7205 already set, set it to @option{-g -O2} for the @acronym{GNU} Objective C
7206 compiler (@option{-O2} on systems where @command{gcc} does not accept
7207 @option{-g}), or @option{-g} for other compilers.
7208 @end defmac
7210 @defmac AC_PROG_OBJCPP
7211 @acindex{PROG_OBJCPP}
7212 @evindex OBJCPP
7213 @ovindex OBJCPP
7214 Set output variable @code{OBJCPP} to a command that runs the Objective C
7215 preprocessor.  If @samp{$OBJC -E} doesn't work, @file{/lib/cpp} is used.
7216 @end defmac
7219 @node Erlang Compiler and Interpreter
7220 @subsection Erlang Compiler and Interpreter Characteristics
7221 @cindex Erlang
7223 Autoconf defines the following macros for determining paths to the essential
7224 Erlang/OTP programs:
7226 @defmac AC_ERLANG_PATH_ERLC (@ovar{value-if-not-found}, @dvar{path, $PATH})
7227 @acindex{ERLANG_PATH_ERLC}
7228 @evindex ERLC
7229 @evindex ERLCFLAGS
7230 @ovindex ERLC
7231 @ovindex ERLCFLAGS
7232 Determine an Erlang compiler to use.  If @code{ERLC} is not already set in the
7233 environment, check for @command{erlc}.  Set output variable @code{ERLC} to the
7234 complete path of the compiler command found.  In addition, if @code{ERLCFLAGS}
7235 is not set in the environment, set it to an empty value.
7237 The two optional arguments have the same meaning as the two last arguments of
7238 macro @code{AC_PROG_PATH} for looking for the @command{erlc} program.  For
7239 example, to look for @command{erlc} only in the @file{/usr/lib/erlang/bin}
7240 directory:
7242 @example
7243 AC_ERLANG_PATH_ERLC([not found], [/usr/lib/erlang/bin])
7244 @end example
7245 @end defmac
7247 @defmac AC_ERLANG_NEED_ERLC (@dvar{path, $PATH})
7248 @acindex{ERLANG_NEED_ERLC}
7249 A simplified variant of the @code{AC_ERLANG_PATH_ERLC} macro, that prints an
7250 error message and exits the @command{configure} script if the @command{erlc}
7251 program is not found.
7252 @end defmac
7254 @defmac AC_ERLANG_PATH_ERL (@ovar{value-if-not-found}, @dvar{path, $PATH})
7255 @acindex{ERLANG_PATH_ERL}
7256 @evindex ERL
7257 @ovindex ERL
7258 Determine an Erlang interpreter to use.  If @code{ERL} is not already
7259 set in the
7260 environment, check for @command{erl}.  Set output variable @code{ERL} to the
7261 complete path of the interpreter command found.
7263 The two optional arguments have the same meaning as the two last arguments of
7264 macro @code{AC_PROG_PATH} for looking for the @command{erl} program.  For
7265 example, to look for @command{erl} only in the @file{/usr/lib/erlang/bin}
7266 directory:
7268 @example
7269 AC_ERLANG_PATH_ERL([not found], [/usr/lib/erlang/bin])
7270 @end example
7271 @end defmac
7273 @defmac AC_ERLANG_NEED_ERL (@dvar{path, $PATH})
7274 @acindex{ERLANG_NEED_ERL}
7275 A simplified variant of the @code{AC_ERLANG_PATH_ERL} macro, that prints an
7276 error message and exits the @command{configure} script if the @command{erl}
7277 program is not found.
7278 @end defmac
7281 @node Fortran Compiler
7282 @subsection Fortran Compiler Characteristics
7283 @cindex Fortran
7284 @cindex F77
7286 The Autoconf Fortran support is divided into two categories: legacy
7287 Fortran 77 macros (@code{F77}), and modern Fortran macros (@code{FC}).
7288 The former are intended for traditional Fortran 77 code, and have output
7289 variables like @code{F77}, @code{FFLAGS}, and @code{FLIBS}.  The latter
7290 are for newer programs that can (or must) compile under the newer
7291 Fortran standards, and have output variables like @code{FC},
7292 @code{FCFLAGS}, and @code{FCLIBS}.
7294 Except for two new macros @code{AC_FC_SRCEXT} and
7295 @code{AC_FC_FREEFORM} (see below), the @code{FC} and @code{F77} macros
7296 behave almost identically, and so they are documented together in this
7297 section.
7300 @defmac AC_PROG_F77 (@ovar{compiler-search-list})
7301 @acindex{PROG_F77}
7302 @evindex F77
7303 @evindex FFLAGS
7304 @ovindex F77
7305 @ovindex FFLAGS
7306 Determine a Fortran 77 compiler to use.  If @code{F77} is not already
7307 set in the environment, then check for @code{g77} and @code{f77}, and
7308 then some other names.  Set the output variable @code{F77} to the name
7309 of the compiler found.
7311 This macro may, however, be invoked with an optional first argument
7312 which, if specified, must be a blank-separated list of Fortran 77
7313 compilers to search for.  This just gives the user an opportunity to
7314 specify an alternative search list for the Fortran 77 compiler.  For
7315 example, if you didn't like the default order, then you could invoke
7316 @code{AC_PROG_F77} like this:
7318 @example
7319 AC_PROG_F77([fl32 f77 fort77 xlf g77 f90 xlf90])
7320 @end example
7322 If using @code{g77} (the @acronym{GNU} Fortran 77 compiler), then
7323 set the shell variable @code{G77} to @samp{yes}.
7324 If the output variable @code{FFLAGS} was not already set in the
7325 environment, then set it to @option{-g -02} for @code{g77} (or @option{-O2}
7326 where @code{g77} does not accept @option{-g}).  Otherwise, set
7327 @code{FFLAGS} to @option{-g} for all other Fortran 77 compilers.
7328 @end defmac
7330 @defmac AC_PROG_FC (@ovar{compiler-search-list}, @ovar{dialect})
7331 @acindex{PROG_FC}
7332 @evindex FC
7333 @evindex FCFLAGS
7334 @ovindex FC
7335 @ovindex FCFLAGS
7336 Determine a Fortran compiler to use.  If @code{FC} is not already set in
7337 the environment, then @code{dialect} is a hint to indicate what Fortran
7338 dialect to search for; the default is to search for the newest available
7339 dialect.  Set the output variable @code{FC} to the name of the compiler
7340 found.
7342 By default, newer dialects are preferred over older dialects, but if
7343 @code{dialect} is specified then older dialects are preferred starting
7344 with the specified dialect.  @code{dialect} can currently be one of
7345 Fortran 77, Fortran 90, or Fortran 95.  However, this is only a hint of
7346 which compiler @emph{name} to prefer (e.g., @code{f90} or @code{f95}),
7347 and no attempt is made to guarantee that a particular language standard
7348 is actually supported.  Thus, it is preferable that you avoid the
7349 @code{dialect} option, and use AC_PROG_FC only for code compatible with
7350 the latest Fortran standard.
7352 This macro may, alternatively, be invoked with an optional first argument
7353 which, if specified, must be a blank-separated list of Fortran
7354 compilers to search for, just as in @code{AC_PROG_F77}.
7356 If the output variable @code{FCFLAGS} was not already set in the
7357 environment, then set it to @option{-g -02} for @acronym{GNU} @code{g77} (or
7358 @option{-O2} where @code{g77} does not accept @option{-g}).  Otherwise,
7359 set @code{FCFLAGS} to @option{-g} for all other Fortran compilers.
7360 @end defmac
7362 @defmac AC_PROG_F77_C_O
7363 @defmacx AC_PROG_FC_C_O
7364 @acindex{PROG_F77_C_O}
7365 @acindex{PROG_FC_C_O}
7366 @cvindex F77_NO_MINUS_C_MINUS_O
7367 @cvindex FC_NO_MINUS_C_MINUS_O
7368 Test whether the Fortran compiler accepts the options @option{-c} and
7369 @option{-o} simultaneously, and define @code{F77_NO_MINUS_C_MINUS_O} or
7370 @code{FC_NO_MINUS_C_MINUS_O}, respectively, if it does not.
7371 @end defmac
7373 The following macros check for Fortran compiler characteristics.
7374 To check for characteristics not listed here, use
7375 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}) or
7376 @code{AC_RUN_IFELSE} (@pxref{Runtime}), making sure to first set the
7377 current language to Fortran 77 or Fortran via @code{AC_LANG([Fortran 77])}
7378 or @code{AC_LANG(Fortran)} (@pxref{Language Choice}).
7381 @defmac AC_F77_LIBRARY_LDFLAGS
7382 @defmacx AC_FC_LIBRARY_LDFLAGS
7383 @acindex{F77_LIBRARY_LDFLAGS}
7384 @ovindex FLIBS
7385 @acindex{FC_LIBRARY_LDFLAGS}
7386 @ovindex FCLIBS
7387 Determine the linker flags (e.g., @option{-L} and @option{-l}) for the
7388 @dfn{Fortran intrinsic and runtime libraries} that are required to
7389 successfully link a Fortran program or shared library.  The output
7390 variable @code{FLIBS} or @code{FCLIBS} is set to these flags (which
7391 should be included after @code{LIBS} when linking).
7393 This macro is intended to be used in those situations when it is
7394 necessary to mix, e.g., C++ and Fortran source code in a single
7395 program or shared library (@pxref{Mixing Fortran 77 With C and C++, , ,
7396 automake, @acronym{GNU} Automake}).
7398 For example, if object files from a C++ and Fortran compiler must be
7399 linked together, then the C++ compiler/linker must be used for linking
7400 (since special C++-ish things need to happen at link time like calling
7401 global constructors, instantiating templates, enabling exception
7402 support, etc.).
7404 However, the Fortran intrinsic and runtime libraries must be linked in
7405 as well, but the C++ compiler/linker doesn't know by default how to add
7406 these Fortran 77 libraries.  Hence, this macro was created to determine
7407 these Fortran libraries.
7409 The macros @code{AC_F77_DUMMY_MAIN} and @code{AC_FC_DUMMY_MAIN} or
7410 @code{AC_F77_MAIN} and @code{AC_FC_MAIN} are probably also necessary to
7411 link C/C++ with Fortran; see below.
7412 @end defmac
7414 @defmac AC_F77_DUMMY_MAIN (@ovar{action-if-found}, @ovar{action-if-not-found})
7415 @defmacx AC_FC_DUMMY_MAIN (@ovar{action-if-found}, @ovar{action-if-not-found})
7416 @acindex{F77_DUMMY_MAIN}
7417 @cvindex F77_DUMMY_MAIN
7418 With many compilers, the Fortran libraries detected by
7419 @code{AC_F77_LIBRARY_LDFLAGS} or @code{AC_FC_LIBRARY_LDFLAGS} provide
7420 their own @code{main} entry function that initializes things like
7421 Fortran I/O, and which then calls a user-provided entry function named
7422 (say) @code{MAIN__} to run the user's program.  The
7423 @code{AC_F77_DUMMY_MAIN} and @code{AC_FC_DUMMY_MAIN} or
7424 @code{AC_F77_MAIN} and @code{AC_FC_MAIN} macros figure out how to deal with
7425 this interaction.
7427 When using Fortran for purely numerical functions (no I/O, etc.)@: often
7428 one prefers to provide one's own @code{main} and skip the Fortran
7429 library initializations.  In this case, however, one may still need to
7430 provide a dummy @code{MAIN__} routine in order to prevent linking errors
7431 on some systems.  @code{AC_F77_DUMMY_MAIN} or @code{AC_FC_DUMMY_MAIN}
7432 detects whether any such routine is @emph{required} for linking, and
7433 what its name is; the shell variable @code{F77_DUMMY_MAIN} or
7434 @code{FC_DUMMY_MAIN} holds this name, @code{unknown} when no solution
7435 was found, and @code{none} when no such dummy main is needed.
7437 By default, @var{action-if-found} defines @code{F77_DUMMY_MAIN} or
7438 @code{FC_DUMMY_MAIN} to the name of this routine (e.g., @code{MAIN__})
7439 @emph{if} it is required.  @var{action-if-not-found} defaults to
7440 exiting with an error.
7442 In order to link with Fortran routines, the user's C/C++ program should
7443 then include the following code to define the dummy main if it is
7444 needed:
7446 @example
7447 #ifdef F77_DUMMY_MAIN
7448 #  ifdef __cplusplus
7449      extern "C"
7450 #  endif
7451    int F77_DUMMY_MAIN() @{ return 1; @}
7452 #endif
7453 @end example
7455 (Replace @code{F77} with @code{FC} for Fortran instead of Fortran 77.)
7457 Note that this macro is called automatically from @code{AC_F77_WRAPPERS}
7458 or @code{AC_FC_WRAPPERS}; there is generally no need to call it
7459 explicitly unless one wants to change the default actions.
7460 @end defmac
7462 @defmac AC_F77_MAIN
7463 @defmacx AC_FC_MAIN
7464 @acindex{F77_MAIN}
7465 @cvindex F77_MAIN
7466 @acindex{FC_MAIN}
7467 @cvindex FC_MAIN
7468 As discussed above, many Fortran libraries allow you to provide an entry
7469 point called (say) @code{MAIN__} instead of the usual @code{main}, which
7470 is then called by a @code{main} function in the Fortran libraries that
7471 initializes things like Fortran I/O@.  The
7472 @code{AC_F77_MAIN} and @code{AC_FC_MAIN} macros detect whether it is
7473 @emph{possible} to utilize such an alternate main function, and defines
7474 @code{F77_MAIN} and @code{FC_MAIN} to the name of the function.  (If no
7475 alternate main function name is found, @code{F77_MAIN} and @code{FC_MAIN} are
7476 simply defined to @code{main}.)
7478 Thus, when calling Fortran routines from C that perform things like I/O,
7479 one should use this macro and declare the "main" function like so:
7481 @example
7482 #ifdef __cplusplus
7483   extern "C"
7484 #endif
7485 int F77_MAIN(int argc, char *argv[]);
7486 @end example
7488 (Again, replace @code{F77} with @code{FC} for Fortran instead of Fortran 77.)
7489 @end defmac
7491 @defmac AC_F77_WRAPPERS
7492 @defmacx AC_FC_WRAPPERS
7493 @acindex{F77_WRAPPERS}
7494 @cvindex F77_FUNC
7495 @cvindex F77_FUNC_
7496 @acindex{FC_WRAPPERS}
7497 @cvindex FC_FUNC
7498 @cvindex FC_FUNC_
7499 Defines C macros @code{F77_FUNC (name, NAME)}, @code{FC_FUNC (name, NAME)},
7500 @code{F77_FUNC_(name, NAME)}, and @code{FC_FUNC_(name, NAME)} to properly
7501 mangle the names of C/C++ identifiers, and identifiers with underscores,
7502 respectively, so that they match the name-mangling scheme used by the
7503 Fortran compiler.
7505 Fortran is case-insensitive, and in order to achieve this the Fortran
7506 compiler converts all identifiers into a canonical case and format.  To
7507 call a Fortran subroutine from C or to write a C function that is
7508 callable from Fortran, the C program must explicitly use identifiers in
7509 the format expected by the Fortran compiler.  In order to do this, one
7510 simply wraps all C identifiers in one of the macros provided by
7511 @code{AC_F77_WRAPPERS} or @code{AC_FC_WRAPPERS}.  For example, suppose
7512 you have the following Fortran 77 subroutine:
7514 @example
7515       subroutine foobar (x, y)
7516       double precision x, y
7517       y = 3.14159 * x
7518       return
7519       end
7520 @end example
7522 You would then declare its prototype in C or C++ as:
7524 @example
7525 #define FOOBAR_F77 F77_FUNC (foobar, FOOBAR)
7526 #ifdef __cplusplus
7527 extern "C"  /* prevent C++ name mangling */
7528 #endif
7529 void FOOBAR_F77(double *x, double *y);
7530 @end example
7532 Note that we pass both the lowercase and uppercase versions of the
7533 function name to @code{F77_FUNC} so that it can select the right one.
7534 Note also that all parameters to Fortran 77 routines are passed as
7535 pointers (@pxref{Mixing Fortran 77 With C and C++, , , automake, @acronym{GNU}
7536 Automake}).
7538 (Replace @code{F77} with @code{FC} for Fortran instead of Fortran 77.)
7540 Although Autoconf tries to be intelligent about detecting the
7541 name-mangling scheme of the Fortran compiler, there may be Fortran
7542 compilers that it doesn't support yet.  In this case, the above code
7543 generates a compile-time error, but some other behavior
7544 (e.g., disabling Fortran-related features) can be induced by checking
7545 whether @code{F77_FUNC} or @code{FC_FUNC} is defined.
7547 Now, to call that routine from a C program, we would do something like:
7549 @example
7551     double x = 2.7183, y;
7552     FOOBAR_F77 (&x, &y);
7554 @end example
7556 If the Fortran identifier contains an underscore (e.g., @code{foo_bar}),
7557 you should use @code{F77_FUNC_} or @code{FC_FUNC_} instead of
7558 @code{F77_FUNC} or @code{FC_FUNC} (with the same arguments).  This is
7559 because some Fortran compilers mangle names differently if they contain
7560 an underscore.
7561 @end defmac
7563 @defmac AC_F77_FUNC (@var{name}, @ovar{shellvar})
7564 @defmacx AC_FC_FUNC (@var{name}, @ovar{shellvar})
7565 @acindex{F77_FUNC}
7566 @acindex{FC_FUNC}
7567 Given an identifier @var{name}, set the shell variable @var{shellvar} to
7568 hold the mangled version @var{name} according to the rules of the
7569 Fortran linker (see also @code{AC_F77_WRAPPERS} or
7570 @code{AC_FC_WRAPPERS}).  @var{shellvar} is optional; if it is not
7571 supplied, the shell variable is simply @var{name}.  The purpose of
7572 this macro is to give the caller a way to access the name-mangling
7573 information other than through the C preprocessor as above, for example,
7574 to call Fortran routines from some language other than C/C++.
7575 @end defmac
7577 @defmac AC_FC_SRCEXT (@var{ext}, @ovar{action-if-success}, @
7578   @ovar{action-if-failure})
7579 @acindex{FC_SRCEXT}
7580 By default, the @code{FC} macros perform their tests using a @file{.f}
7581 extension for source-code files.  Some compilers, however, only enable
7582 newer language features for appropriately named files, e.g., Fortran 90
7583 features only for @file{.f90} files.  On the other hand, some other
7584 compilers expect all source files to end in @file{.f} and require
7585 special flags to support other file name extensions.  The
7586 @code{AC_FC_SRCEXT} macro deals with both of these issues.
7588 The @code{AC_FC_SRCEXT} tries to get the @code{FC} compiler to accept files
7589 ending with the extension .@var{ext} (i.e., @var{ext} does @emph{not}
7590 contain the dot).  If any special compiler flags are needed for this, it
7591 stores them in the output variable @code{FCFLAGS_}@var{ext}.  This
7592 extension and these flags are then used for all subsequent @code{FC} tests
7593 (until @code{AC_FC_SRCEXT} is called again).
7595 For example, you would use @code{AC_FC_SRCEXT(f90)} to employ the
7596 @file{.f90} extension in future tests, and it would set the
7597 @code{FCFLAGS_f90} output variable with any extra flags that are needed
7598 to compile such files.
7600 The @code{FCFLAGS_}@var{ext} can @emph{not} be simply absorbed into
7601 @code{FCFLAGS}, for two reasons based on the limitations of some
7602 compilers.  First, only one @code{FCFLAGS_}@var{ext} can be used at a
7603 time, so files with different extensions must be compiled separately.
7604 Second, @code{FCFLAGS_}@var{ext} must appear @emph{immediately} before
7605 the source-code file name when compiling.  So, continuing the example
7606 above, you might compile a @file{foo.f90} file in your makefile with the
7607 command:
7609 @example
7610 foo.o: foo.f90
7611      $(FC) -c $(FCFLAGS) $(FCFLAGS_f90) '$(srcdir)/foo.f90'
7612 @end example
7614 If @code{AC_FC_SRCEXT} succeeds in compiling files with the @var{ext}
7615 extension, it calls @var{action-if-success} (defaults to nothing).  If
7616 it fails, and cannot find a way to make the @code{FC} compiler accept such
7617 files, it calls @var{action-if-failure} (defaults to exiting with an
7618 error message).
7620 @end defmac
7622 @defmac AC_FC_FREEFORM (@ovar{action-if-success}, @ovar{action-if-failure})
7623 @acindex{FC_FREEFORM}
7625 The @code{AC_FC_FREEFORM} tries to ensure that the Fortran compiler
7626 (@code{$FC}) allows free-format source code (as opposed to the older
7627 fixed-format style from Fortran 77).  If necessary, it may add some
7628 additional flags to @code{FCFLAGS}.
7630 This macro is most important if you are using the default @file{.f}
7631 extension, since many compilers interpret this extension as indicating
7632 fixed-format source unless an additional flag is supplied.  If you
7633 specify a different extension with @code{AC_FC_SRCEXT}, such as
7634 @file{.f90} or @file{.f95}, then @code{AC_FC_FREEFORM} ordinarily
7635 succeeds without modifying @code{FCFLAGS}.
7637 If @code{AC_FC_FREEFORM} succeeds in compiling free-form source, it
7638 calls @var{action-if-success} (defaults to nothing).  If it fails, it
7639 calls @var{action-if-failure} (defaults to exiting with an error
7640 message).
7641 @end defmac
7643 @node System Services
7644 @section System Services
7646 The following macros check for operating system services or capabilities.
7648 @anchor{AC_PATH_X}
7649 @defmac AC_PATH_X
7650 @acindex{PATH_X}
7651 @evindex XMKMF
7652 @cindex X Window System
7653 Try to locate the X Window System include files and libraries.  If the
7654 user gave the command line options @option{--x-includes=@var{dir}} and
7655 @option{--x-libraries=@var{dir}}, use those directories.
7657 If either or both were not given, get the missing values by running
7658 @code{xmkmf} (or an executable pointed to by the @code{XMKMF}
7659 environment variable) on a trivial @file{Imakefile} and examining the
7660 makefile that it produces.  Setting @code{XMKMF} to @samp{false}
7661 disables this method.
7663 If this method fails to find the X Window System, @command{configure}
7664 looks for the files in several directories where they often reside.
7665 If either method is successful, set the shell variables
7666 @code{x_includes} and @code{x_libraries} to their locations, unless they
7667 are in directories the compiler searches by default.
7669 If both methods fail, or the user gave the command line option
7670 @option{--without-x}, set the shell variable @code{no_x} to @samp{yes};
7671 otherwise set it to the empty string.
7672 @end defmac
7674 @anchor{AC_PATH_XTRA}
7675 @defmac AC_PATH_XTRA
7676 @acindex{PATH_XTRA}
7677 @ovindex X_CFLAGS
7678 @ovindex X_LIBS
7679 @ovindex X_EXTRA_LIBS
7680 @ovindex X_PRE_LIBS
7681 @cvindex X_DISPLAY_MISSING
7682 An enhanced version of @code{AC_PATH_X}.  It adds the C compiler flags
7683 that X needs to output variable @code{X_CFLAGS}, and the X linker flags
7684 to @code{X_LIBS}.  Define @code{X_DISPLAY_MISSING} if X is not
7685 available.
7687 This macro also checks for special libraries that some systems need in
7688 order to compile X programs.  It adds any that the system needs to
7689 output variable @code{X_EXTRA_LIBS}.  And it checks for special X11R6
7690 libraries that need to be linked with before @option{-lX11}, and adds
7691 any found to the output variable @code{X_PRE_LIBS}.
7693 @c This is an incomplete kludge.  Make a real way to do it.
7694 @c If you need to check for other X functions or libraries yourself, then
7695 @c after calling this macro, add the contents of @code{X_EXTRA_LIBS} to
7696 @c @code{LIBS} temporarily, like this: (FIXME - add example)
7697 @end defmac
7699 @anchor{AC_SYS_INTERPRETER}
7700 @defmac AC_SYS_INTERPRETER
7701 @acindex{SYS_INTERPRETER}
7702 Check whether the system supports starting scripts with a line of the
7703 form @samp{#!/bin/sh} to select the interpreter to use for the script.
7704 After running this macro, shell code in @file{configure.ac} can check
7705 the shell variable @code{interpval}; it is set to @samp{yes}
7706 if the system supports @samp{#!}, @samp{no} if not.
7707 @end defmac
7709 @defmac AC_SYS_LARGEFILE
7710 @acindex{SYS_LARGEFILE}
7711 @cvindex _FILE_OFFSET_BITS
7712 @cvindex _LARGE_FILES
7713 @ovindex CC
7714 @cindex Large file support
7715 @cindex LFS
7716 Arrange for 64-bit file offsets, known as
7717 @uref{http://@/www.unix-systems@/.org/@/version2/@/whatsnew/@/lfs20mar.html,
7718 large-file support}.  On some hosts, one must use special compiler
7719 options to build programs that can access large files.  Append any such
7720 options to the output variable @code{CC}.  Define
7721 @code{_FILE_OFFSET_BITS} and @code{_LARGE_FILES} if necessary.
7723 Large-file support can be disabled by configuring with the
7724 @option{--disable-largefile} option.
7726 If you use this macro, check that your program works even when
7727 @code{off_t} is wider than @code{long int}, since this is common when
7728 large-file support is enabled.  For example, it is not correct to print
7729 an arbitrary @code{off_t} value @code{X} with @code{printf ("%ld",
7730 (long int) X)}.
7732 The LFS introduced the @code{fseeko} and @code{ftello} functions to
7733 replace their C counterparts @code{fseek} and @code{ftell} that do not
7734 use @code{off_t}.  Take care to use @code{AC_FUNC_FSEEKO} to make their
7735 prototypes available when using them and large-file support is
7736 enabled.
7737 @end defmac
7739 @anchor{AC_SYS_LONG_FILE_NAMES}
7740 @defmac AC_SYS_LONG_FILE_NAMES
7741 @acindex{SYS_LONG_FILE_NAMES}
7742 @cvindex HAVE_LONG_FILE_NAMES
7743 If the system supports file names longer than 14 characters, define
7744 @code{HAVE_LONG_FILE_NAMES}.
7745 @end defmac
7747 @defmac AC_SYS_POSIX_TERMIOS
7748 @acindex{SYS_POSIX_TERMIOS}
7749 @cindex Posix termios headers
7750 @cindex termios Posix headers
7751 Check to see if the Posix termios headers and functions are available on the
7752 system.  If so, set the shell variable @code{ac_cv_sys_posix_termios} to
7753 @samp{yes}.  If not, set the variable to @samp{no}.
7754 @end defmac
7756 @node Posix Variants
7757 @section Posix Variants
7759 The following macro makes it possible to use features of Posix that are
7760 extensions to C, as well as platform extensions not defined by Posix.
7762 @anchor{AC_USE_SYSTEM_EXTENSIONS}
7763 @defmac AC_USE_SYSTEM_EXTENSIONS
7764 @acindex{USE_SYSTEM_EXTENSIONS}
7765 @cvindex _ALL_SOURCE
7766 @cvindex _GNU_SOURCE
7767 @cvindex _MINIX
7768 @cvindex _POSIX_1_SOURCE
7769 @cvindex _POSIX_PTHREAD_SEMANTICS
7770 @cvindex _POSIX_SOURCE
7771 @cvindex _TANDEM_SOURCE
7772 @cvindex __EXTENSIONS__
7773 This macro was introduced in Autoconf 2.60.  If possible, enable
7774 extensions to C or Posix on hosts that normally disable the extensions,
7775 typically due to standards-conformance namespace issues.  This should be
7776 called before any macros that run the C compiler.  The following
7777 preprocessor macros are defined where appropriate:
7779 @table @code
7780 @item _GNU_SOURCE
7781 Enable extensions on @acronym{GNU}/Linux.
7782 @item __EXTENSIONS__
7783 Enable general extensions on Solaris.
7784 @item _POSIX_PTHREAD_SEMANTICS
7785 Enable threading extensions on Solaris.
7786 @item _TANDEM_SOURCE
7787 Enable extensions for the @acronym{HP} NonStop platform.
7788 @item _ALL_SOURCE
7789 Enable extensions for @acronym{AIX} 3, and for Interix.
7790 @item _POSIX_SOURCE
7791 Enable Posix functions for Minix.
7792 @item _POSIX_1_SOURCE
7793 Enable additional Posix functions for Minix.
7794 @item _MINIX
7795 Identify Minix platform.  This particular preprocessor macro is
7796 obsolescent, and may be removed in a future release of Autoconf.
7797 @end table
7798 @end defmac
7801 @node Erlang Libraries
7802 @section Erlang Libraries
7803 @cindex Erlang, Library, checking
7805 The following macros check for an installation of Erlang/OTP, and for the
7806 presence of certain Erlang libraries.  All those macros require the
7807 configuration of an Erlang interpreter and an Erlang compiler
7808 (@pxref{Erlang Compiler and Interpreter}).
7810 @defmac AC_ERLANG_SUBST_ERTS_VER
7811 @acindex{ERLANG_SUBST_ERTS_VER}
7812 @ovindex ERLANG_ERTS_VER
7813 Set the output variable @code{ERLANG_ERTS_VER} to the version of the
7814 Erlang runtime system (as returned by Erlang's
7815 @code{erlang:system_info(version)} function).  The result of this test
7816 is cached if caching is enabled when running @command{configure}.  The
7817 @code{ERLANG_ERTS_VER} variable is not intended to be used for testing
7818 for features of specific ERTS versions, but to be used for substituting
7819 the ERTS version in Erlang/OTP release resource files (@code{.rel}
7820 files), as shown below.
7821 @end defmac
7823 @defmac AC_ERLANG_SUBST_ROOT_DIR
7824 @acindex{ERLANG_SUBST_ROOT_DIR}
7825 @ovindex ERLANG_ROOT_DIR
7826 Set the output variable @code{ERLANG_ROOT_DIR} to the path to the base
7827 directory in which Erlang/OTP is installed (as returned by Erlang's
7828 @code{code:root_dir/0} function).  The result of this test is cached if
7829 caching is enabled when running @command{configure}.
7830 @end defmac
7832 @defmac AC_ERLANG_SUBST_LIB_DIR
7833 @acindex{ERLANG_SUBST_LIB_DIR}
7834 @ovindex ERLANG_LIB_DIR
7835 Set the output variable @code{ERLANG_LIB_DIR} to the path of the library
7836 directory of Erlang/OTP (as returned by Erlang's
7837 @code{code:lib_dir/0} function), which subdirectories each contain an installed
7838 Erlang/OTP library.  The result of this test is cached if caching is enabled
7839 when running @command{configure}.
7840 @end defmac
7842 @defmac AC_ERLANG_CHECK_LIB (@var{library}, @ovar{action-if-found}, @
7843   @ovar{action-if-not-found})
7844 @acindex{ERLANG_CHECK_LIB}
7845 @ovindex ERLANG_LIB_DIR_@var{library}
7846 @ovindex ERLANG_LIB_VER_@var{library}
7847 Test whether the Erlang/OTP library @var{library} is installed by
7848 calling Erlang's @code{code:lib_dir/1} function.  The result of this
7849 test is cached if caching is enabled when running @command{configure}.
7850 @var{action-if-found} is a list of shell commands to run if the library
7851 is installed; @var{action-if-not-found} is a list of shell commands to
7852 run if it is not.  Additionally, if the library is installed, the output
7853 variable @samp{ERLANG_LIB_DIR_@var{library}} is set to the path to the
7854 library installation directory, and the output variable
7855 @samp{ERLANG_LIB_VER_@var{library}} is set to the version number that is
7856 part of the subdirectory name, if it is in the standard form
7857 (@code{@var{library}-@var{version}}).  If the directory name does not
7858 have a version part, @samp{ERLANG_LIB_VER_@var{library}} is set to the
7859 empty string.  If the library is not installed,
7860 @samp{ERLANG_LIB_DIR_@var{library}} and
7861 @samp{ERLANG_LIB_VER_@var{library}} are set to @code{"not found"}.  For
7862 example, to check if library @code{stdlib} is installed:
7864 @example
7865 AC_ERLANG_CHECK_LIB([stdlib],
7866   [echo "stdlib version \"$ERLANG_LIB_VER_stdlib\""
7867    echo "is installed in \"$ERLANG_LIB_DIR_stdlib\""],
7868   [AC_MSG_ERROR([stdlib was not found!])])
7869 @end example
7871 The @samp{ERLANG_LIB_VER_@var{library}} variables (set by
7872 @code{AC_ERLANG_CHECK_LIB}) and the @code{ERLANG_ERTS_VER} variable (set
7873 by @code{AC_ERLANG_SUBST_ERTS_VER}) are not intended to be used for
7874 testing for features of specific versions of libraries or of the Erlang
7875 runtime system.  Those variables are intended to be substituted in
7876 Erlang release resource files (@code{.rel} files).  For instance, to
7877 generate a @file{example.rel} file for an application depending on the
7878 @code{stdlib} library, @file{configure.ac} could contain:
7880 @example
7881 AC_ERLANG_SUBST_ERTS_VER
7882 AC_ERLANG_CHECK_LIB([stdlib],
7883   [],
7884   [AC_MSG_ERROR([stdlib was not found!])])
7885 AC_CONFIG_FILES([example.rel])
7886 @end example
7888 @noindent
7889 The @file{example.rel.in} file used to generate @file{example.rel}
7890 should contain:
7892 @example
7893 @{release,
7894     @{"@@PACKAGE@@", "@@VERSION@@"@},
7895     @{erts, "@@ERLANG_ERTS_VER@@"@},
7896     [@{stdlib, "@@ERLANG_LIB_VER_stdlib@@"@},
7897      @{@@PACKAGE@@, "@@VERSION@@"@}]@}.
7898 @end example
7899 @end defmac
7901 In addition to the above macros, which test installed Erlang libraries, the
7902 following macros determine the paths to the directories into which newly built
7903 Erlang libraries are to be installed:
7905 @defmac AC_ERLANG_SUBST_INSTALL_LIB_DIR
7906 @acindex{ERLANG_SUBST_INSTALL_LIB_DIR}
7907 @ovindex ERLANG_INSTALL_LIB_DIR
7909 Set the @code{ERLANG_INSTALL_LIB_DIR} output variable to the directory into
7910 which every built Erlang library should be installed in a separate
7911 subdirectory.
7912 If this variable is not set in the environment when @command{configure} runs,
7913 its default value is @code{$ERLANG_LIB_DIR}, which value is set by the
7914 @code{AC_ERLANG_SUBST_LIB_DIR} macro.
7915 @end defmac
7917 @defmac AC_ERLANG_SUBST_INSTALL_LIB_SUBDIR (@var{library}, @var{version})
7918 @acindex{ERLANG_SUBST_INSTALL_LIB_SUBDIR}
7919 @ovindex ERLANG_INSTALL_LIB_DIR_@var{library}
7921 Set the @samp{ERLANG_INSTALL_LIB_DIR_@var{library}} output variable to the
7922 directory into which the built Erlang library @var{library} version
7923 @var{version} should be installed.  If this variable is not set in the
7924 environment when @command{configure} runs, its default value is
7925 @samp{$ERLANG_INSTALL_LIB_DIR/@var{library}-@var{version}}, the value of the
7926 @code{ERLANG_INSTALL_LIB_DIR} variable being set by the
7927 @code{AC_ERLANG_SUBST_INSTALL_LIB_DIR} macro.
7928 @end defmac
7934 @c ========================================================= Writing Tests
7936 @node Writing Tests
7937 @chapter Writing Tests
7939 If the existing feature tests don't do something you need, you have to
7940 write new ones.  These macros are the building blocks.  They provide
7941 ways for other macros to check whether various kinds of features are
7942 available and report the results.
7944 This chapter contains some suggestions and some of the reasons why the
7945 existing tests are written the way they are.  You can also learn a lot
7946 about how to write Autoconf tests by looking at the existing ones.  If
7947 something goes wrong in one or more of the Autoconf tests, this
7948 information can help you understand the assumptions behind them, which
7949 might help you figure out how to best solve the problem.
7951 These macros check the output of the compiler system of the current
7952 language (@pxref{Language Choice}).  They do not cache the results of
7953 their tests for future use (@pxref{Caching Results}), because they don't
7954 know enough about the information they are checking for to generate a
7955 cache variable name.  They also do not print any messages, for the same
7956 reason.  The checks for particular kinds of features call these macros
7957 and do cache their results and print messages about what they're
7958 checking for.
7960 When you write a feature test that could be applicable to more than one
7961 software package, the best thing to do is encapsulate it in a new macro.
7962 @xref{Writing Autoconf Macros}, for how to do that.
7964 @menu
7965 * Language Choice::             Selecting which language to use for testing
7966 * Writing Test Programs::       Forging source files for compilers
7967 * Running the Preprocessor::    Detecting preprocessor symbols
7968 * Running the Compiler::        Detecting language or header features
7969 * Running the Linker::          Detecting library features
7970 * Runtime::                     Testing for runtime features
7971 * Systemology::                 A zoology of operating systems
7972 * Multiple Cases::              Tests for several possible values
7973 @end menu
7975 @node Language Choice
7976 @section Language Choice
7977 @cindex Language
7979 Autoconf-generated @command{configure} scripts check for the C compiler and
7980 its features by default.  Packages that use other programming languages
7981 (maybe more than one, e.g., C and C++) need to test features of the
7982 compilers for the respective languages.  The following macros determine
7983 which programming language is used in the subsequent tests in
7984 @file{configure.ac}.
7986 @anchor{AC_LANG}
7987 @defmac AC_LANG (@var{language})
7988 Do compilation tests using the compiler, preprocessor, and file
7989 extensions for the specified @var{language}.
7991 Supported languages are:
7993 @table @samp
7994 @item C
7995 Do compilation tests using @code{CC} and @code{CPP} and use extension
7996 @file{.c} for test programs.  Use compilation flags: @code{CPPFLAGS} with
7997 @code{CPP}, and both @code{CPPFLAGS} and @code{CFLAGS} with @code{CC}.
7999 @item C++
8000 Do compilation tests using @code{CXX} and @code{CXXCPP} and use
8001 extension @file{.C} for test programs.  Use compilation flags:
8002 @code{CPPFLAGS} with @code{CXXCPP}, and both @code{CPPFLAGS} and
8003 @code{CXXFLAGS} with @code{CXX}.
8005 @item Fortran 77
8006 Do compilation tests using @code{F77} and use extension @file{.f} for
8007 test programs.  Use compilation flags: @code{FFLAGS}.
8009 @item Fortran
8010 Do compilation tests using @code{FC} and use extension @file{.f} (or
8011 whatever has been set by @code{AC_FC_SRCEXT}) for test programs.  Use
8012 compilation flags: @code{FCFLAGS}.
8014 @item Erlang
8015 @ovindex ERLC
8016 @ovindex ERL
8017 @ovindex ERLCFLAGS
8018 Compile and execute tests using @code{ERLC} and @code{ERL} and use extension
8019 @file{.erl} for test Erlang modules.  Use compilation flags: @code{ERLCFLAGS}.
8021 @item Objective C
8022 Do compilation tests using @code{OBJC} and @code{OBJCPP} and use
8023 extension @file{.m} for test programs.  Use compilation flags:
8024 @code{CPPFLAGS} with @code{OBJCPP}, and both @code{CPPFLAGS} and
8025 @code{OBJCFLAGS} with @code{OBJC}.
8026 @end table
8027 @end defmac
8029 @anchor{AC_LANG_PUSH}
8030 @defmac AC_LANG_PUSH (@var{language})
8031 @acindex{LANG_PUSH}
8032 Remember the current language (as set by @code{AC_LANG}) on a stack, and
8033 then select the @var{language}.  Use this macro and @code{AC_LANG_POP}
8034 in macros that need to temporarily switch to a particular language.
8035 @end defmac
8037 @defmac AC_LANG_POP (@ovar{language})
8038 @acindex{LANG_POP}
8039 Select the language that is saved on the top of the stack, as set by
8040 @code{AC_LANG_PUSH}, and remove it from the stack.
8042 If given, @var{language} specifies the language we just @emph{quit}.  It
8043 is a good idea to specify it when it's known (which should be the
8044 case@dots{}), since Autoconf detects inconsistencies.
8046 @example
8047 AC_LANG_PUSH([Fortran 77])
8048 # Perform some tests on Fortran 77.
8049 # @dots{}
8050 AC_LANG_POP([Fortran 77])
8051 @end example
8052 @end defmac
8054 @defmac AC_LANG_ASSERT (@var{language})
8055 @acindex{LANG_ASSERT} Check statically that the current language is
8056 @var{language}.  You should use this in your language specific macros
8057 to avoid that they be called with an inappropriate language.
8059 This macro runs only at @command{autoconf} time, and incurs no cost at
8060 @command{configure} time.  Sadly enough and because Autoconf is a two
8061 layer language @footnote{Because M4 is not aware of Sh code,
8062 especially conditionals, some optimizations that look nice statically
8063 may produce incorrect results at runtime.}, the macros
8064 @code{AC_LANG_PUSH} and @code{AC_LANG_POP} cannot be ``optimizing'',
8065 therefore as much as possible you ought to avoid using them to wrap
8066 your code, rather, require from the user to run the macro with a
8067 correct current language, and check it with @code{AC_LANG_ASSERT}.
8068 And anyway, that may help the user understand she is running a Fortran
8069 macro while expecting a result about her Fortran 77 compiler@enddots{}
8070 @end defmac
8073 @defmac AC_REQUIRE_CPP
8074 @acindex{REQUIRE_CPP}
8075 Ensure that whichever preprocessor would currently be used for tests has
8076 been found.  Calls @code{AC_REQUIRE} (@pxref{Prerequisite Macros}) with an
8077 argument of either @code{AC_PROG_CPP} or @code{AC_PROG_CXXCPP},
8078 depending on which language is current.
8079 @end defmac
8082 @node Writing Test Programs
8083 @section Writing Test Programs
8085 Autoconf tests follow a common scheme: feed some program with some
8086 input, and most of the time, feed a compiler with some source file.
8087 This section is dedicated to these source samples.
8089 @menu
8090 * Guidelines::                  General rules for writing test programs
8091 * Test Functions::              Avoiding pitfalls in test programs
8092 * Generating Sources::          Source program boilerplate
8093 @end menu
8095 @node Guidelines
8096 @subsection Guidelines for Test Programs
8098 The most important rule to follow when writing testing samples is:
8100 @center @emph{Look for realism.}
8102 This motto means that testing samples must be written with the same
8103 strictness as real programs are written.  In particular, you should
8104 avoid ``shortcuts'' and simplifications.
8106 Don't just play with the preprocessor if you want to prepare a
8107 compilation.  For instance, using @command{cpp} to check whether a header is
8108 functional might let your @command{configure} accept a header which
8109 causes some @emph{compiler} error.  Do not hesitate to check a header with
8110 other headers included before, especially required headers.
8112 Make sure the symbols you use are properly defined, i.e., refrain from
8113 simply declaring a function yourself instead of including the proper
8114 header.
8116 Test programs should not write to standard output.  They
8117 should exit with status 0 if the test succeeds, and with status 1
8118 otherwise, so that success
8119 can be distinguished easily from a core dump or other failure;
8120 segmentation violations and other failures produce a nonzero exit
8121 status.  Unless you arrange for @code{exit} to be declared, test
8122 programs should @code{return}, not @code{exit}, from @code{main},
8123 because on many systems @code{exit} is not declared by default.
8125 Test programs can use @code{#if} or @code{#ifdef} to check the values of
8126 preprocessor macros defined by tests that have already run.  For
8127 example, if you call @code{AC_HEADER_STDBOOL}, then later on in
8128 @file{configure.ac} you can have a test program that includes
8129 @file{stdbool.h} conditionally:
8131 @example
8132 @group
8133 #ifdef HAVE_STDBOOL_H
8134 # include <stdbool.h>
8135 #endif
8136 @end group
8137 @end example
8139 Both @code{#if HAVE_STDBOOL_H} and @code{#ifdef HAVE_STDBOOL_H} will
8140 work with any standard C compiler.  Some developers prefer @code{#if}
8141 because it is easier to read, while others prefer @code{#ifdef} because
8142 it avoids diagnostics with picky compilers like @acronym{GCC} with the
8143 @option{-Wundef} option.
8145 If a test program needs to use or create a data file, give it a name
8146 that starts with @file{conftest}, such as @file{conftest.data}.  The
8147 @command{configure} script cleans up by running @samp{rm -f -r conftest*}
8148 after running test programs and if the script is interrupted.
8150 @node Test Functions
8151 @subsection Test Functions
8153 These days it's safe to assume support for function prototypes
8154 (introduced in C89).
8156 Functions that test programs declare should also be conditionalized for
8157 C++, which requires @samp{extern "C"} prototypes.  Make sure to not
8158 include any header files containing clashing prototypes.
8160 @example
8161 #ifdef __cplusplus
8162 extern "C"
8163 #endif
8164 void *valloc (size_t);
8165 @end example
8167 If a test program calls a function with invalid parameters (just to see
8168 whether it exists), organize the program to ensure that it never invokes
8169 that function.  You can do this by calling it in another function that is
8170 never invoked.  You can't do it by putting it after a call to
8171 @code{exit}, because @acronym{GCC} version 2 knows that @code{exit}
8172 never returns
8173 and optimizes out any code that follows it in the same block.
8175 If you include any header files, be sure to call the functions
8176 relevant to them with the correct number of arguments, even if they are
8177 just 0, to avoid compilation errors due to prototypes.  @acronym{GCC}
8178 version 2
8179 has internal prototypes for several functions that it automatically
8180 inlines; for example, @code{memcpy}.  To avoid errors when checking for
8181 them, either pass them the correct number of arguments or redeclare them
8182 with a different return type (such as @code{char}).
8185 @node Generating Sources
8186 @subsection Generating Sources
8188 Autoconf provides a set of macros that can be used to generate test
8189 source files.  They are written to be language generic, i.e., they
8190 actually depend on the current language (@pxref{Language Choice}) to
8191 ``format'' the output properly.
8194 @defmac AC_LANG_CONFTEST (@var{source})
8195 @acindex{LANG_CONFTEST}
8196 Save the @var{source} text in the current test source file:
8197 @file{conftest.@var{extension}} where the @var{extension} depends on the
8198 current language.
8200 Note that the @var{source} is evaluated exactly once, like regular
8201 Autoconf macro arguments, and therefore (i) you may pass a macro
8202 invocation, (ii) if not, be sure to double quote if needed.
8203 @end defmac
8205 @defmac AC_LANG_SOURCE (@var{source})
8206 @acindex{LANG_SOURCE}
8207 Expands into the @var{source}, with the definition of
8208 all the @code{AC_DEFINE} performed so far.
8209 @end defmac
8211 For instance executing (observe the double quotation!):
8213 @example
8214 AC_INIT([Hello], [1.0], [bug-hello@@example.org])
8215 AC_DEFINE([HELLO_WORLD], ["Hello, World\n"],
8216   [Greetings string.])
8217 AC_LANG(C)
8218 AC_LANG_CONFTEST(
8219    [AC_LANG_SOURCE([[const char hw[] = "Hello, World\n";]])])
8220 gcc -E -dD -o - conftest.c
8221 @end example
8223 @noindent
8224 results in:
8226 @example
8227 @dots{}
8228 # 1 "conftest.c"
8230 #define PACKAGE_NAME "Hello"
8231 #define PACKAGE_TARNAME "hello"
8232 #define PACKAGE_VERSION "1.0"
8233 #define PACKAGE_STRING "Hello 1.0"
8234 #define PACKAGE_BUGREPORT "bug-hello@@example.org"
8235 #define HELLO_WORLD "Hello, World\n"
8237 const char hw[] = "Hello, World\n";
8238 @end example
8240 When the test language is Fortran or Erlang, the @code{AC_DEFINE} definitions
8241 are not automatically translated into constants in the source code by this
8242 macro.
8244 @defmac AC_LANG_PROGRAM (@var{prologue}, @var{body})
8245 @acindex{LANG_PROGRAM}
8246 Expands into a source file which consists of the @var{prologue}, and
8247 then @var{body} as body of the main function (e.g., @code{main} in
8248 C).  Since it uses @code{AC_LANG_SOURCE}, the features of the latter are
8249 available.
8250 @end defmac
8252 For instance:
8254 @example
8255 AC_INIT([Hello], [1.0], [bug-hello@@example.org])
8256 AC_DEFINE([HELLO_WORLD], ["Hello, World\n"],
8257   [Greetings string.])
8258 AC_LANG_CONFTEST(
8259 [AC_LANG_PROGRAM([[const char hw[] = "Hello, World\n";]],
8260                  [[fputs (hw, stdout);]])])
8261 gcc -E -dD -o - conftest.c
8262 @end example
8264 @noindent
8265 results in:
8267 @example
8268 @dots{}
8269 # 1 "conftest.c"
8271 #define PACKAGE_NAME "Hello"
8272 #define PACKAGE_TARNAME "hello"
8273 #define PACKAGE_VERSION "1.0"
8274 #define PACKAGE_STRING "Hello 1.0"
8275 #define PACKAGE_BUGREPORT "bug-hello@@example.org"
8276 #define HELLO_WORLD "Hello, World\n"
8278 const char hw[] = "Hello, World\n";
8280 main ()
8282 fputs (hw, stdout);
8283   ;
8284   return 0;
8286 @end example
8288 In Erlang tests, the created source file is that of an Erlang module called
8289 @code{conftest} (@file{conftest.erl}).  This module defines and exports
8290 at least
8291 one @code{start/0} function, which is called to perform the test.  The
8292 @var{prologue} is optional code that is inserted between the module header and
8293 the @code{start/0} function definition.  @var{body} is the body of the
8294 @code{start/0} function without the final period (@pxref{Runtime}, about
8295 constraints on this function's behavior).
8297 For instance:
8299 @example
8300 AC_INIT([Hello], [1.0], [bug-hello@@example.org])
8301 AC_LANG(Erlang)
8302 AC_LANG_CONFTEST(
8303 [AC_LANG_PROGRAM([[-define(HELLO_WORLD, "Hello, world!").]],
8304                  [[io:format("~s~n", [?HELLO_WORLD])]])])
8305 cat conftest.erl
8306 @end example
8308 @noindent
8309 results in:
8311 @example
8312 -module(conftest).
8313 -export([start/0]).
8314 -define(HELLO_WORLD, "Hello, world!").
8315 start() ->
8316 io:format("~s~n", [?HELLO_WORLD])
8318 @end example
8320 @defmac AC_LANG_CALL (@var{prologue}, @var{function})
8321 @acindex{LANG_CALL}
8322 Expands into a source file which consists of the @var{prologue}, and
8323 then a call to the @var{function} as body of the main function (e.g.,
8324 @code{main} in C).  Since it uses @code{AC_LANG_PROGRAM}, the feature
8325 of the latter are available.
8327 This function will probably be replaced in the future by a version
8328 which would enable specifying the arguments.  The use of this macro is
8329 not encouraged, as it violates strongly the typing system.
8331 This macro cannot be used for Erlang tests.
8332 @end defmac
8334 @defmac AC_LANG_FUNC_LINK_TRY (@var{function})
8335 @acindex{LANG_FUNC_LINK_TRY}
8336 Expands into a source file which uses the @var{function} in the body of
8337 the main function (e.g., @code{main} in C).  Since it uses
8338 @code{AC_LANG_PROGRAM}, the features of the latter are available.
8340 As @code{AC_LANG_CALL}, this macro is documented only for completeness.
8341 It is considered to be severely broken, and in the future will be
8342 removed in favor of actual function calls (with properly typed
8343 arguments).
8345 This macro cannot be used for Erlang tests.
8346 @end defmac
8348 @node Running the Preprocessor
8349 @section Running the Preprocessor
8351 Sometimes one might need to run the preprocessor on some source file.
8352 @emph{Usually it is a bad idea}, as you typically need to @emph{compile}
8353 your project, not merely run the preprocessor on it; therefore you
8354 certainly want to run the compiler, not the preprocessor.  Resist the
8355 temptation of following the easiest path.
8357 Nevertheless, if you need to run the preprocessor, then use
8358 @code{AC_PREPROC_IFELSE}.
8360 The macros described in this section cannot be used for tests in Erlang or
8361 Fortran, since those languages require no preprocessor.
8363 @anchor{AC_PREPROC_IFELSE}
8364 @defmac AC_PREPROC_IFELSE (@var{input}, @ovar{action-if-true}, @
8365   @ovar{action-if-false})
8366 @acindex{PREPROC_IFELSE}
8367 Run the preprocessor of the current language (@pxref{Language Choice})
8368 on the @var{input}, run the shell commands @var{action-if-true} on
8369 success, @var{action-if-false} otherwise.  The @var{input} can be made
8370 by @code{AC_LANG_PROGRAM} and friends.
8372 This macro uses @code{CPPFLAGS}, but not @code{CFLAGS}, because
8373 @option{-g}, @option{-O}, etc.@: are not valid options to many C
8374 preprocessors.
8376 It is customary to report unexpected failures with
8377 @code{AC_MSG_FAILURE}.
8378 @end defmac
8380 For instance:
8382 @example
8383 AC_INIT([Hello], [1.0], [bug-hello@@example.org])
8384 AC_DEFINE([HELLO_WORLD], ["Hello, World\n"],
8385   [Greetings string.])
8386 AC_PREPROC_IFELSE(
8387    [AC_LANG_PROGRAM([[const char hw[] = "Hello, World\n";]],
8388                     [[fputs (hw, stdout);]])],
8389    [AC_MSG_RESULT([OK])],
8390    [AC_MSG_FAILURE([unexpected preprocessor failure])])
8391 @end example
8393 @noindent
8394 results in:
8396 @example
8397 checking for gcc... gcc
8398 checking for C compiler default output file name... a.out
8399 checking whether the C compiler works... yes
8400 checking whether we are cross compiling... no
8401 checking for suffix of executables...
8402 checking for suffix of object files... o
8403 checking whether we are using the GNU C compiler... yes
8404 checking whether gcc accepts -g... yes
8405 checking for gcc option to accept ISO C89... none needed
8406 checking how to run the C preprocessor... gcc -E
8408 @end example
8410 @sp 1
8412 The macro @code{AC_TRY_CPP} (@pxref{Obsolete Macros}) used to play the
8413 role of @code{AC_PREPROC_IFELSE}, but double quotes its argument, making
8414 it impossible to use it to elaborate sources.  You are encouraged to
8415 get rid of your old use of the macro @code{AC_TRY_CPP} in favor of
8416 @code{AC_PREPROC_IFELSE}, but, in the first place, are you sure you need
8417 to run the @emph{preprocessor} and not the compiler?
8419 @anchor{AC_EGREP_HEADER}
8420 @defmac AC_EGREP_HEADER (@var{pattern}, @var{header-file}, @
8421   @var{action-if-found}, @ovar{action-if-not-found})
8422 @acindex{EGREP_HEADER}
8423 If the output of running the preprocessor on the system header file
8424 @var{header-file} matches the extended regular expression
8425 @var{pattern}, execute shell commands @var{action-if-found}, otherwise
8426 execute @var{action-if-not-found}.
8427 @end defmac
8429 @anchor{AC_EGREP_CPP}
8430 @defmac AC_EGREP_CPP (@var{pattern}, @var{program}, @
8431   @ovar{action-if-found}, @ovar{action-if-not-found})
8432 @acindex{EGREP_CPP}
8433 @var{program} is the text of a C or C++ program, on which shell
8434 variable, back quote, and backslash substitutions are performed.  If the
8435 output of running the preprocessor on @var{program} matches the
8436 extended regular expression @var{pattern}, execute shell commands
8437 @var{action-if-found}, otherwise execute @var{action-if-not-found}.
8438 @end defmac
8442 @node Running the Compiler
8443 @section Running the Compiler
8445 To check for a syntax feature of the current language's (@pxref{Language
8446 Choice}) compiler, such as whether it recognizes a certain keyword, or
8447 simply to try some library feature, use @code{AC_COMPILE_IFELSE} to try
8448 to compile a small program that uses that feature.
8450 @defmac AC_COMPILE_IFELSE (@var{input}, @ovar{action-if-true}, @
8451   @ovar{action-if-false})
8452 @acindex{COMPILE_IFELSE}
8453 Run the compiler and compilation flags of the current language
8454 (@pxref{Language Choice}) on the @var{input}, run the shell commands
8455 @var{action-if-true} on success, @var{action-if-false} otherwise.  The
8456 @var{input} can be made by @code{AC_LANG_PROGRAM} and friends.
8458 It is customary to report unexpected failures with
8459 @code{AC_MSG_FAILURE}.  This macro does not try to link; use
8460 @code{AC_LINK_IFELSE} if you need to do that (@pxref{Running the
8461 Linker}).
8463 This macro uses @code{AC_REQUIRE} for the compiler associated with the
8464 current language, which means that if the compiler has not yet been
8465 determined, the compiler determination will be made prior to the body of
8466 the outermust @code{AC_DEFUN} macro that triggered this macro to
8467 expand (@pxref{Expanded Before Required}).
8468 @end defmac
8470 @ovindex ERL
8471 For tests in Erlang, the @var{input} must be the source code of a module named
8472 @code{conftest}.  @code{AC_COMPILE_IFELSE} generates a @file{conftest.beam}
8473 file that can be interpreted by the Erlang virtual machine (@code{ERL}).  It is
8474 recommended to use @code{AC_LANG_PROGRAM} to specify the test program,
8475 to ensure that the Erlang module has the right name.
8477 @node Running the Linker
8478 @section Running the Linker
8480 To check for a library, a function, or a global variable, Autoconf
8481 @command{configure} scripts try to compile and link a small program that
8482 uses it.  This is unlike Metaconfig, which by default uses @code{nm} or
8483 @code{ar} on the C library to try to figure out which functions are
8484 available.  Trying to link with the function is usually a more reliable
8485 approach because it avoids dealing with the variations in the options
8486 and output formats of @code{nm} and @code{ar} and in the location of the
8487 standard libraries.  It also allows configuring for cross-compilation or
8488 checking a function's runtime behavior if needed.  On the other hand,
8489 it can be slower than scanning the libraries once, but accuracy is more
8490 important than speed.
8492 @code{AC_LINK_IFELSE} is used to compile test programs to test for
8493 functions and global variables.  It is also used by @code{AC_CHECK_LIB}
8494 to check for libraries (@pxref{Libraries}), by adding the library being
8495 checked for to @code{LIBS} temporarily and trying to link a small
8496 program.
8498 @anchor{AC_LINK_IFELSE}
8499 @defmac AC_LINK_IFELSE (@var{input}, @ovar{action-if-true}, @
8500   @ovar{action-if-false})
8501 @acindex{LINK_IFELSE}
8502 Run the compiler (and compilation flags) and the linker of the current
8503 language (@pxref{Language Choice}) on the @var{input}, run the shell
8504 commands @var{action-if-true} on success, @var{action-if-false}
8505 otherwise.  The @var{input} can be made by @code{AC_LANG_PROGRAM} and
8506 friends.
8508 @code{LDFLAGS} and @code{LIBS} are used for linking, in addition to the
8509 current compilation flags.
8511 It is customary to report unexpected failures with
8512 @code{AC_MSG_FAILURE}.  This macro does not try to execute the program;
8513 use @code{AC_RUN_IFELSE} if you need to do that (@pxref{Runtime}).
8514 @end defmac
8516 The @code{AC_LINK_IFELSE} macro cannot be used for Erlang tests, since Erlang
8517 programs are interpreted and do not require linking.
8521 @node Runtime
8522 @section Checking Runtime Behavior
8524 Sometimes you need to find out how a system performs at runtime, such
8525 as whether a given function has a certain capability or bug.  If you
8526 can, make such checks when your program runs instead of when it is
8527 configured.  You can check for things like the machine's endianness when
8528 your program initializes itself.
8530 If you really need to test for a runtime behavior while configuring,
8531 you can write a test program to determine the result, and compile and
8532 run it using @code{AC_RUN_IFELSE}.  Avoid running test programs if
8533 possible, because this prevents people from configuring your package for
8534 cross-compiling.
8536 @anchor{AC_RUN_IFELSE}
8537 @defmac AC_RUN_IFELSE (@var{input}, @ovar{action-if-true}, @
8538   @ovar{action-if-false}, @ovar{action-if-cross-compiling})
8539 @acindex{RUN_IFELSE}
8540 If @var{program} compiles and links successfully and returns an exit
8541 status of 0 when executed, run shell commands @var{action-if-true}.
8542 Otherwise, run shell commands @var{action-if-false}.
8544 The @var{input} can be made by @code{AC_LANG_PROGRAM} and friends.
8545 @code{LDFLAGS} and @code{LIBS} are used for linking, in addition to the
8546 compilation flags of the current language (@pxref{Language Choice}).
8548 If the compiler being used does not produce executables that run on the
8549 system where @command{configure} is being run, then the test program is
8550 not run.  If the optional shell commands @var{action-if-cross-compiling}
8551 are given, they are run instead.  Otherwise, @command{configure} prints
8552 an error message and exits.
8554 In the @var{action-if-false} section, the failing exit status is
8555 available in the shell variable @samp{$?}.  This exit status might be
8556 that of a failed compilation, or it might be that of a failed program
8557 execution.
8559 It is customary to report unexpected failures with
8560 @code{AC_MSG_FAILURE}.
8561 @end defmac
8563 Try to provide a pessimistic default value to use when cross-compiling
8564 makes runtime tests impossible.  You do this by passing the optional
8565 last argument to @code{AC_RUN_IFELSE}.  @command{autoconf} prints a
8566 warning message when creating @command{configure} each time it
8567 encounters a call to @code{AC_RUN_IFELSE} with no
8568 @var{action-if-cross-compiling} argument given.  You may ignore the
8569 warning, though users cannot configure your package for
8570 cross-compiling.  A few of the macros distributed with Autoconf produce
8571 this warning message.
8573 To configure for cross-compiling you can also choose a value for those
8574 parameters based on the canonical system name (@pxref{Manual
8575 Configuration}).  Alternatively, set up a test results cache file with
8576 the correct values for the host system (@pxref{Caching Results}).
8578 @ovindex cross_compiling
8579 To provide a default for calls of @code{AC_RUN_IFELSE} that are embedded
8580 in other macros, including a few of the ones that come with Autoconf,
8581 you can test whether the shell variable @code{cross_compiling} is set to
8582 @samp{yes}, and then use an alternate method to get the results instead
8583 of calling the macros.
8585 It is also permissible to temporarily assign to @code{cross_compiling}
8586 in order to force tests to behave as though they are in a
8587 cross-compilation environment, particularly since this provides a way to
8588 test your @var{action-if-cross-compiling} even when you are not using a
8589 cross-compiler.
8591 @example
8592 # We temporarily set cross-compile mode to force AC_COMPUTE_INT
8593 # to use the slow link-only method
8594 save_cross_compiling=$cross_compiling
8595 cross_compiling=yes
8596 AC_COMPUTE_INT([@dots{}])
8597 cross_compiling=$save_cross_compiling
8598 @end example
8600 A C or C++ runtime test should be portable.
8601 @xref{Portable C and C++}.
8603 Erlang tests must exit themselves the Erlang VM by calling the @code{halt/1}
8604 function: the given status code is used to determine the success of the test
8605 (status is @code{0}) or its failure (status is different than @code{0}), as
8606 explained above.  It must be noted that data output through the standard output
8607 (e.g., using @code{io:format/2}) may be truncated when halting the VM.
8608 Therefore, if a test must output configuration information, it is recommended
8609 to create and to output data into the temporary file named @file{conftest.out},
8610 using the functions of module @code{file}.  The @code{conftest.out} file is
8611 automatically deleted by the @code{AC_RUN_IFELSE} macro.  For instance, a
8612 simplified implementation of Autoconf's @code{AC_ERLANG_SUBST_LIB_DIR}
8613 macro is:
8615 @example
8616 AC_INIT([LibdirTest], [1.0], [bug-libdirtest@@example.org])
8617 AC_ERLANG_NEED_ERL
8618 AC_LANG(Erlang)
8619 AC_RUN_IFELSE(
8620   [AC_LANG_PROGRAM([], [dnl
8621     file:write_file("conftest.out", code:lib_dir()),
8622     halt(0)])],
8623   [echo "code:lib_dir() returned: `cat conftest.out`"],
8624   [AC_MSG_FAILURE([test Erlang program execution failed])])
8625 @end example
8628 @node Systemology
8629 @section Systemology
8630 @cindex Systemology
8632 This section aims at presenting some systems and pointers to
8633 documentation.  It may help you addressing particular problems reported
8634 by users.
8636 @uref{http://@/www.opengroup.org/@/susv3, Posix-conforming systems} are
8637 derived from the @uref{http://@/www.bell-labs.com/@/history/@/unix/, Unix
8638 operating system}.
8640 The @uref{http://@/bhami.com/@/rosetta.html, Rosetta Stone for Unix}
8641 contains a table correlating the features of various Posix-conforming
8642 systems.  @uref{http://@/www.levenez.com/@/unix/, Unix History} is a
8643 simplified diagram of how many Unix systems were derived from each
8644 other.
8646 @uref{http://@/heirloom.sourceforge.net/, The Heirloom Project}
8647 provides some variants of traditional implementations of Unix utilities.
8649 @table @asis
8650 @item Darwin
8651 @cindex Darwin
8652 Darwin is also known as Mac OS X@.  Beware that the file system @emph{can} be
8653 case-preserving, but case insensitive.  This can cause nasty problems,
8654 since for instance the installation attempt for a package having an
8655 @file{INSTALL} file can result in @samp{make install} report that
8656 nothing was to be done!
8658 That's all dependent on whether the file system is a UFS (case
8659 sensitive) or HFS+ (case preserving).  By default Apple wants you to
8660 install the OS on HFS+.  Unfortunately, there are some pieces of
8661 software which really need to be built on UFS@.  We may want to rebuild
8662 Darwin to have both UFS and HFS+ available (and put the /local/build
8663 tree on the UFS).
8665 @item @acronym{QNX} 4.25
8666 @cindex @acronym{QNX} 4.25
8667 @c FIXME: Please, if you feel like writing something more precise,
8668 @c it'd be great.  In particular, I can't understand the difference with
8669 @c QNX Neutrino.
8670 @acronym{QNX} is a realtime operating system running on Intel architecture
8671 meant to be scalable from the small embedded systems to the hundred
8672 processor super-computer.  It claims to be Posix certified.  More
8673 information is available on the
8674 @uref{http://@/www.qnx.com/, @acronym{QNX} home page}.
8676 @item Tru64
8677 @cindex Tru64
8678 @uref{http://@/h30097.www3.hp.com/@/docs/,
8679 Documentation of several versions of Tru64} is available in different
8680 formats.
8682 @item Unix version 7
8683 @cindex Unix version 7
8684 @cindex V7
8685 Officially this was called the ``Seventh Edition'' of ``the @sc{unix}
8686 time-sharing system'' but we use the more-common name ``Unix version 7''.
8687 Documentation is available in the
8688 @uref{http://@/plan9.bell-labs.com/@/7thEdMan/, Unix Seventh Edition Manual}.
8689 Previous versions of Unix are called ``Unix version 6'', etc., but
8690 they were not as widely used.
8691 @end table
8694 @node Multiple Cases
8695 @section Multiple Cases
8697 Some operations are accomplished in several possible ways, depending on
8698 the OS variant.  Checking for them essentially requires a ``case
8699 statement''.  Autoconf does not directly provide one; however, it is
8700 easy to simulate by using a shell variable to keep track of whether a
8701 way to perform the operation has been found yet.
8703 Here is an example that uses the shell variable @code{fstype} to keep
8704 track of whether the remaining cases need to be checked.  Note that
8705 since the value of @code{fstype} is under our control, we don't have to
8706 use the longer @samp{test "x$fstype" = xno}.
8708 @example
8709 @group
8710 AC_MSG_CHECKING([how to get file system type])
8711 fstype=no
8712 # The order of these tests is important.
8713 AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <sys/statvfs.h>
8714 #include <sys/fstyp.h>]])],
8715                   [AC_DEFINE([FSTYPE_STATVFS], [1],
8716                      [Define if statvfs exists.])
8717                    fstype=SVR4])
8718 if test $fstype = no; then
8719   AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <sys/statfs.h>
8720 #include <sys/fstyp.h>]])],
8721                   [AC_DEFINE([FSTYPE_USG_STATFS], [1],
8722                      [Define if USG statfs.])
8723                    fstype=SVR3])
8725 if test $fstype = no; then
8726   AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <sys/statfs.h>
8727 #include <sys/vmount.h>]])]),
8728                   [AC_DEFINE([FSTYPE_AIX_STATFS], [1],
8729                      [Define if AIX statfs.])
8730                    fstype=AIX])
8732 # (more cases omitted here)
8733 AC_MSG_RESULT([$fstype])
8734 @end group
8735 @end example
8737 @c ====================================================== Results of Tests.
8739 @node Results
8740 @chapter Results of Tests
8742 Once @command{configure} has determined whether a feature exists, what can
8743 it do to record that information?  There are four sorts of things it can
8744 do: define a C preprocessor symbol, set a variable in the output files,
8745 save the result in a cache file for future @command{configure} runs, and
8746 print a message letting the user know the result of the test.
8748 @menu
8749 * Defining Symbols::            Defining C preprocessor symbols
8750 * Setting Output Variables::    Replacing variables in output files
8751 * Special Chars in Variables::  Characters to beware of in variables
8752 * Caching Results::             Speeding up subsequent @command{configure} runs
8753 * Printing Messages::           Notifying @command{configure} users
8754 @end menu
8756 @node Defining Symbols
8757 @section Defining C Preprocessor Symbols
8759 A common action to take in response to a feature test is to define a C
8760 preprocessor symbol indicating the results of the test.  That is done by
8761 calling @code{AC_DEFINE} or @code{AC_DEFINE_UNQUOTED}.
8763 By default, @code{AC_OUTPUT} places the symbols defined by these macros
8764 into the output variable @code{DEFS}, which contains an option
8765 @option{-D@var{symbol}=@var{value}} for each symbol defined.  Unlike in
8766 Autoconf version 1, there is no variable @code{DEFS} defined while
8767 @command{configure} is running.  To check whether Autoconf macros have
8768 already defined a certain C preprocessor symbol, test the value of the
8769 appropriate cache variable, as in this example:
8771 @example
8772 AC_CHECK_FUNC([vprintf], [AC_DEFINE([HAVE_VPRINTF], [1],
8773                           [Define if vprintf exists.])])
8774 if test "x$ac_cv_func_vprintf" != xyes; then
8775   AC_CHECK_FUNC([_doprnt], [AC_DEFINE([HAVE_DOPRNT], [1],
8776                             [Define if _doprnt exists.])])
8778 @end example
8780 If @code{AC_CONFIG_HEADERS} has been called, then instead of creating
8781 @code{DEFS}, @code{AC_OUTPUT} creates a header file by substituting the
8782 correct values into @code{#define} statements in a template file.
8783 @xref{Configuration Headers}, for more information about this kind of
8784 output.
8786 @defmac AC_DEFINE (@var{variable}, @var{value}, @ovar{description})
8787 @defmacx AC_DEFINE (@var{variable})
8788 @cvindex @var{variable}
8789 @acindex{DEFINE}
8790 Define @var{variable} to @var{value} (verbatim), by defining a C
8791 preprocessor macro for @var{variable}.  @var{variable} should be a C
8792 identifier, optionally suffixed by a parenthesized argument list to
8793 define a C preprocessor macro with arguments.  The macro argument list,
8794 if present, should be a comma-separated list of C identifiers, possibly
8795 terminated by an ellipsis @samp{...} if C99 syntax is employed.
8796 @var{variable} should not contain comments, white space, trigraphs,
8797 backslash-newlines, universal character names, or non-@acronym{ASCII}
8798 characters.
8800 @var{value} may contain backslash-escaped newlines, which will be
8801 preserved if you use @code{AC_CONFIG_HEADERS} but flattened if passed
8802 via @code{@@DEFS@@} (with no effect on the compilation, since the
8803 preprocessor sees only one line in the first place).  @var{value} should
8804 not contain raw newlines.  If you are not using
8805 @code{AC_CONFIG_HEADERS}, @var{value} should not contain any @samp{#}
8806 characters, as @command{make} tends to eat them.  To use a shell
8807 variable, use @code{AC_DEFINE_UNQUOTED} instead.
8809 @var{description} is only useful if you are using
8810 @code{AC_CONFIG_HEADERS}.  In this case, @var{description} is put into
8811 the generated @file{config.h.in} as the comment before the macro define.
8812 The following example defines the C preprocessor variable
8813 @code{EQUATION} to be the string constant @samp{"$a > $b"}:
8815 @example
8816 AC_DEFINE([EQUATION], ["$a > $b"],
8817   [Equation string.])
8818 @end example
8820 If neither @var{value} nor @var{description} are given, then
8821 @var{value} defaults to 1 instead of to the empty string.  This is for
8822 backwards compatibility with older versions of Autoconf, but this usage
8823 is obsolescent and may be withdrawn in future versions of Autoconf.
8825 If the @var{variable} is a literal string, it is passed to
8826 @code{m4_pattern_allow} (@pxref{Forbidden Patterns}).
8828 If multiple @code{AC_DEFINE} statements are executed for the same
8829 @var{variable} name (not counting any parenthesized argument list),
8830 the last one wins.
8831 @end defmac
8833 @defmac AC_DEFINE_UNQUOTED (@var{variable}, @var{value}, @ovar{description})
8834 @defmacx AC_DEFINE_UNQUOTED (@var{variable})
8835 @acindex{DEFINE_UNQUOTED}
8836 @cvindex @var{variable}
8837 Like @code{AC_DEFINE}, but three shell expansions are
8838 performed---once---on @var{variable} and @var{value}: variable expansion
8839 (@samp{$}), command substitution (@samp{`}), and backslash escaping
8840 (@samp{\}), as if in an unquoted here-document.  Single and double quote
8841 characters in the value have no
8842 special meaning.  Use this macro instead of @code{AC_DEFINE} when
8843 @var{variable} or @var{value} is a shell variable.  Examples:
8845 @example
8846 AC_DEFINE_UNQUOTED([config_machfile], ["$machfile"],
8847   [Configuration machine file.])
8848 AC_DEFINE_UNQUOTED([GETGROUPS_T], [$ac_cv_type_getgroups],
8849   [getgroups return type.])
8850 AC_DEFINE_UNQUOTED([$ac_tr_hdr], [1],
8851   [Translated header name.])
8852 @end example
8853 @end defmac
8855 Due to a syntactical bizarreness of the Bourne shell, do not use
8856 semicolons to separate @code{AC_DEFINE} or @code{AC_DEFINE_UNQUOTED}
8857 calls from other macro calls or shell code; that can cause syntax errors
8858 in the resulting @command{configure} script.  Use either blanks or
8859 newlines.  That is, do this:
8861 @example
8862 AC_CHECK_HEADER([elf.h],
8863   [AC_DEFINE([SVR4], [1], [System V Release 4]) LIBS="-lelf $LIBS"])
8864 @end example
8866 @noindent
8867 or this:
8869 @example
8870 AC_CHECK_HEADER([elf.h],
8871   [AC_DEFINE([SVR4], [1], [System V Release 4])
8872    LIBS="-lelf $LIBS"])
8873 @end example
8875 @noindent
8876 instead of this:
8878 @example
8879 AC_CHECK_HEADER([elf.h],
8880   [AC_DEFINE([SVR4], [1], [System V Release 4]); LIBS="-lelf $LIBS"])
8881 @end example
8883 @node Setting Output Variables
8884 @section Setting Output Variables
8885 @cindex Output variables
8887 Another way to record the results of tests is to set @dfn{output
8888 variables}, which are shell variables whose values are substituted into
8889 files that @command{configure} outputs.  The two macros below create new
8890 output variables.  @xref{Preset Output Variables}, for a list of output
8891 variables that are always available.
8893 @defmac AC_SUBST (@var{variable}, @ovar{value})
8894 @acindex{SUBST}
8895 Create an output variable from a shell variable.  Make @code{AC_OUTPUT}
8896 substitute the variable @var{variable} into output files (typically one
8897 or more makefiles).  This means that @code{AC_OUTPUT}
8898 replaces instances of @samp{@@@var{variable}@@} in input files with the
8899 value that the shell variable @var{variable} has when @code{AC_OUTPUT}
8900 is called.  The value can contain any non-@code{NUL} character, including
8901 newline.  If you are using Automake 1.11 or newer, for newlines in values
8902 you might want to consider using @code{AM_SUBST_NOTMAKE} to prevent
8903 @command{automake} from adding a line @code{@var{variable} =
8904 @@@var{variable}@@} to the @file{Makefile.in} files (@pxref{Optional, ,
8905 Automake, automake, Other things Automake recognizes}).
8907 Variable occurrences should not overlap: e.g., an input file should
8908 not contain @samp{@@@var{var1}@@@var{var2}@@} if @var{var1} and @var{var2}
8909 are variable names.
8910 The substituted value is not rescanned for more output variables;
8911 occurrences of @samp{@@@var{variable}@@} in the value are inserted
8912 literally into the output file.  (The algorithm uses the special marker
8913 @code{|#_!!_#|} internally, so neither the substituted value nor the
8914 output file may contain @code{|#_!!_#|}.)
8916 If @var{value} is given, in addition assign it to @var{variable}.
8918 The string @var{variable} is passed to @code{m4_pattern_allow}
8919 (@pxref{Forbidden Patterns}).
8920 @end defmac
8922 @defmac AC_SUBST_FILE (@var{variable})
8923 @acindex{SUBST_FILE}
8924 Another way to create an output variable from a shell variable.  Make
8925 @code{AC_OUTPUT} insert (without substitutions) the contents of the file
8926 named by shell variable @var{variable} into output files.  This means
8927 that @code{AC_OUTPUT} replaces instances of
8928 @samp{@@@var{variable}@@} in output files (such as @file{Makefile.in})
8929 with the contents of the file that the shell variable @var{variable}
8930 names when @code{AC_OUTPUT} is called.  Set the variable to
8931 @file{/dev/null} for cases that do not have a file to insert.
8932 This substitution occurs only when the @samp{@@@var{variable}@@} is on a
8933 line by itself, optionally surrounded by spaces and tabs.  The
8934 substitution replaces the whole line, including the spaces, tabs, and
8935 the terminating newline.
8937 This macro is useful for inserting makefile fragments containing
8938 special dependencies or other @command{make} directives for particular host
8939 or target types into makefiles.  For example, @file{configure.ac}
8940 could contain:
8942 @example
8943 AC_SUBST_FILE([host_frag])
8944 host_frag=$srcdir/conf/sun4.mh
8945 @end example
8947 @noindent
8948 and then a @file{Makefile.in} could contain:
8950 @example
8951 @@host_frag@@
8952 @end example
8954 The string @var{variable} is passed to @code{m4_pattern_allow}
8955 (@pxref{Forbidden Patterns}).
8956 @end defmac
8958 @cindex Precious Variable
8959 @cindex Variable, Precious
8960 Running @command{configure} in varying environments can be extremely
8961 dangerous.  If for instance the user runs @samp{CC=bizarre-cc
8962 ./configure}, then the cache, @file{config.h}, and many other output
8963 files depend upon @command{bizarre-cc} being the C compiler.  If
8964 for some reason the user runs @command{./configure} again, or if it is
8965 run via @samp{./config.status --recheck}, (@xref{Automatic Remaking},
8966 and @pxref{config.status Invocation}), then the configuration can be
8967 inconsistent, composed of results depending upon two different
8968 compilers.
8970 Environment variables that affect this situation, such as @samp{CC}
8971 above, are called @dfn{precious variables}, and can be declared as such
8972 by @code{AC_ARG_VAR}.
8974 @defmac AC_ARG_VAR (@var{variable}, @var{description})
8975 @acindex{ARG_VAR}
8976 Declare @var{variable} is a precious variable, and include its
8977 @var{description} in the variable section of @samp{./configure --help}.
8979 Being precious means that
8980 @itemize @minus
8981 @item
8982 @var{variable} is substituted via @code{AC_SUBST}.
8984 @item
8985 The value of @var{variable} when @command{configure} was launched is
8986 saved in the cache, including if it was not specified on the command
8987 line but via the environment.  Indeed, while @command{configure} can
8988 notice the definition of @code{CC} in @samp{./configure CC=bizarre-cc},
8989 it is impossible to notice it in @samp{CC=bizarre-cc ./configure},
8990 which, unfortunately, is what most users do.
8992 We emphasize that it is the @emph{initial} value of @var{variable} which
8993 is saved, not that found during the execution of @command{configure}.
8994 Indeed, specifying @samp{./configure FOO=foo} and letting
8995 @samp{./configure} guess that @code{FOO} is @code{foo} can be two
8996 different things.
8998 @item
8999 @var{variable} is checked for consistency between two
9000 @command{configure} runs.  For instance:
9002 @example
9003 $ @kbd{./configure --silent --config-cache}
9004 $ @kbd{CC=cc ./configure --silent --config-cache}
9005 configure: error: `CC' was not set in the previous run
9006 configure: error: changes in the environment can compromise \
9007 the build
9008 configure: error: run `make distclean' and/or \
9009 `rm config.cache' and start over
9010 @end example
9012 @noindent
9013 and similarly if the variable is unset, or if its content is changed.
9014 If the content has white space changes only, then the error is degraded
9015 to a warning only, but the old value is reused.
9017 @item
9018 @var{variable} is kept during automatic reconfiguration
9019 (@pxref{config.status Invocation}) as if it had been passed as a command
9020 line argument, including when no cache is used:
9022 @example
9023 $ @kbd{CC=/usr/bin/cc ./configure var=raboof --silent}
9024 $ @kbd{./config.status --recheck}
9025 running CONFIG_SHELL=/bin/sh /bin/sh ./configure var=raboof \
9026   CC=/usr/bin/cc  --no-create --no-recursion
9027 @end example
9028 @end itemize
9029 @end defmac
9031 @node Special Chars in Variables
9032 @section Special Characters in Output Variables
9033 @cindex Output variables, special characters in
9035 Many output variables are intended to be evaluated both by
9036 @command{make} and by the shell.  Some characters are expanded
9037 differently in these two contexts, so to avoid confusion these
9038 variables' values should not contain any of the following characters:
9040 @example
9041 " # $ & ' ( ) * ; < > ? [ \ ^ ` |
9042 @end example
9044 Also, these variables' values should neither contain newlines, nor start
9045 with @samp{~}, nor contain white space or @samp{:} immediately followed
9046 by @samp{~}.  The values can contain nonempty sequences of white space
9047 characters like tabs and spaces, but each such sequence might
9048 arbitrarily be replaced by a single space during substitution.
9050 These restrictions apply both to the values that @command{configure}
9051 computes, and to the values set directly by the user.  For example, the
9052 following invocations of @command{configure} are problematic, since they
9053 attempt to use special characters within @code{CPPFLAGS} and white space
9054 within @code{$(srcdir)}:
9056 @example
9057 CPPFLAGS='-DOUCH="&\"#$*?"' '../My Source/ouch-1.0/configure'
9059 '../My Source/ouch-1.0/configure' CPPFLAGS='-DOUCH="&\"#$*?"'
9060 @end example
9062 @node Caching Results
9063 @section Caching Results
9064 @cindex Cache
9066 To avoid checking for the same features repeatedly in various
9067 @command{configure} scripts (or in repeated runs of one script),
9068 @command{configure} can optionally save the results of many checks in a
9069 @dfn{cache file} (@pxref{Cache Files}).  If a @command{configure} script
9070 runs with caching enabled and finds a cache file, it reads the results
9071 of previous runs from the cache and avoids rerunning those checks.  As a
9072 result, @command{configure} can then run much faster than if it had to
9073 perform all of the checks every time.
9075 @defmac AC_CACHE_VAL (@var{cache-id}, @var{commands-to-set-it})
9076 @acindex{CACHE_VAL}
9077 Ensure that the results of the check identified by @var{cache-id} are
9078 available.  If the results of the check were in the cache file that was
9079 read, and @command{configure} was not given the @option{--quiet} or
9080 @option{--silent} option, print a message saying that the result was
9081 cached; otherwise, run the shell commands @var{commands-to-set-it}.  If
9082 the shell commands are run to determine the value, the value is
9083 saved in the cache file just before @command{configure} creates its output
9084 files.  @xref{Cache Variable Names}, for how to choose the name of the
9085 @var{cache-id} variable.
9087 The @var{commands-to-set-it} @emph{must have no side effects} except for
9088 setting the variable @var{cache-id}, see below.
9089 @end defmac
9091 @defmac AC_CACHE_CHECK (@var{message}, @var{cache-id}, @
9092   @var{commands-to-set-it})
9093 @acindex{CACHE_CHECK}
9094 A wrapper for @code{AC_CACHE_VAL} that takes care of printing the
9095 messages.  This macro provides a convenient shorthand for the most
9096 common way to use these macros.  It calls @code{AC_MSG_CHECKING} for
9097 @var{message}, then @code{AC_CACHE_VAL} with the @var{cache-id} and
9098 @var{commands} arguments, and @code{AC_MSG_RESULT} with @var{cache-id}.
9100 The @var{commands-to-set-it} @emph{must have no side effects} except for
9101 setting the variable @var{cache-id}, see below.
9102 @end defmac
9104 It is common to find buggy macros using @code{AC_CACHE_VAL} or
9105 @code{AC_CACHE_CHECK}, because people are tempted to call
9106 @code{AC_DEFINE} in the @var{commands-to-set-it}.  Instead, the code that
9107 @emph{follows} the call to @code{AC_CACHE_VAL} should call
9108 @code{AC_DEFINE}, by examining the value of the cache variable.  For
9109 instance, the following macro is broken:
9111 @example
9112 @group
9113 AC_DEFUN([AC_SHELL_TRUE],
9114 [AC_CACHE_CHECK([whether true(1) works], [my_cv_shell_true_works],
9115                 [my_cv_shell_true_works=no
9116                  (true) 2>/dev/null && my_cv_shell_true_works=yes
9117                  if test "x$my_cv_shell_true_works" = xyes; then
9118                    AC_DEFINE([TRUE_WORKS], [1],
9119                              [Define if `true(1)' works properly.])
9120                  fi])
9122 @end group
9123 @end example
9125 @noindent
9126 This fails if the cache is enabled: the second time this macro is run,
9127 @code{TRUE_WORKS} @emph{will not be defined}.  The proper implementation
9130 @example
9131 @group
9132 AC_DEFUN([AC_SHELL_TRUE],
9133 [AC_CACHE_CHECK([whether true(1) works], [my_cv_shell_true_works],
9134                 [my_cv_shell_true_works=no
9135                  (true) 2>/dev/null && my_cv_shell_true_works=yes])
9136  if test "x$my_cv_shell_true_works" = xyes; then
9137    AC_DEFINE([TRUE_WORKS], [1],
9138              [Define if `true(1)' works properly.])
9139  fi
9141 @end group
9142 @end example
9144 Also, @var{commands-to-set-it} should not print any messages, for
9145 example with @code{AC_MSG_CHECKING}; do that before calling
9146 @code{AC_CACHE_VAL}, so the messages are printed regardless of whether
9147 the results of the check are retrieved from the cache or determined by
9148 running the shell commands.
9150 @menu
9151 * Cache Variable Names::        Shell variables used in caches
9152 * Cache Files::                 Files @command{configure} uses for caching
9153 * Cache Checkpointing::         Loading and saving the cache file
9154 @end menu
9156 @node Cache Variable Names
9157 @subsection Cache Variable Names
9158 @cindex Cache variable
9160 The names of cache variables should have the following format:
9162 @example
9163 @var{package-prefix}_cv_@var{value-type}_@var{specific-value}_@ovar{additional-options}
9164 @end example
9166 @noindent
9167 for example, @samp{ac_cv_header_stat_broken} or
9168 @samp{ac_cv_prog_gcc_traditional}.  The parts of the variable name are:
9170 @table @asis
9171 @item @var{package-prefix}
9172 An abbreviation for your package or organization; the same prefix you
9173 begin local Autoconf macros with, except lowercase by convention.
9174 For cache values used by the distributed Autoconf macros, this value is
9175 @samp{ac}.
9177 @item @code{_cv_}
9178 Indicates that this shell variable is a cache value.  This string
9179 @emph{must} be present in the variable name, including the leading
9180 underscore.
9182 @item @var{value-type}
9183 A convention for classifying cache values, to produce a rational naming
9184 system.  The values used in Autoconf are listed in @ref{Macro Names}.
9186 @item @var{specific-value}
9187 Which member of the class of cache values this test applies to.
9188 For example, which function (@samp{alloca}), program (@samp{gcc}), or
9189 output variable (@samp{INSTALL}).
9191 @item @var{additional-options}
9192 Any particular behavior of the specific member that this test applies to.
9193 For example, @samp{broken} or @samp{set}.  This part of the name may
9194 be omitted if it does not apply.
9195 @end table
9197 The values assigned to cache variables may not contain newlines.
9198 Usually, their values are Boolean (@samp{yes} or @samp{no}) or the
9199 names of files or functions; so this is not an important restriction.
9201 @node Cache Files
9202 @subsection Cache Files
9204 A cache file is a shell script that caches the results of configure
9205 tests run on one system so they can be shared between configure scripts
9206 and configure runs.  It is not useful on other systems.  If its contents
9207 are invalid for some reason, the user may delete or edit it.
9209 By default, @command{configure} uses no cache file,
9210 to avoid problems caused by accidental
9211 use of stale cache files.
9213 To enable caching, @command{configure} accepts @option{--config-cache} (or
9214 @option{-C}) to cache results in the file @file{config.cache}.
9215 Alternatively, @option{--cache-file=@var{file}} specifies that
9216 @var{file} be the cache file.  The cache file is created if it does not
9217 exist already.  When @command{configure} calls @command{configure} scripts in
9218 subdirectories, it uses the @option{--cache-file} argument so that they
9219 share the same cache.  @xref{Subdirectories}, for information on
9220 configuring subdirectories with the @code{AC_CONFIG_SUBDIRS} macro.
9222 @file{config.status} only pays attention to the cache file if it is
9223 given the @option{--recheck} option, which makes it rerun
9224 @command{configure}.
9226 It is wrong to try to distribute cache files for particular system types.
9227 There is too much room for error in doing that, and too much
9228 administrative overhead in maintaining them.  For any features that
9229 can't be guessed automatically, use the standard method of the canonical
9230 system type and linking files (@pxref{Manual Configuration}).
9232 The site initialization script can specify a site-wide cache file to
9233 use, instead of the usual per-program cache.  In this case, the cache
9234 file gradually accumulates information whenever someone runs a new
9235 @command{configure} script.  (Running @command{configure} merges the new cache
9236 results with the existing cache file.)  This may cause problems,
9237 however, if the system configuration (e.g., the installed libraries or
9238 compilers) changes and the stale cache file is not deleted.
9240 @node Cache Checkpointing
9241 @subsection Cache Checkpointing
9243 If your configure script, or a macro called from @file{configure.ac}, happens
9244 to abort the configure process, it may be useful to checkpoint the cache
9245 a few times at key points using @code{AC_CACHE_SAVE}.  Doing so
9246 reduces the amount of time it takes to rerun the configure script with
9247 (hopefully) the error that caused the previous abort corrected.
9249 @c FIXME: Do we really want to document this guy?
9250 @defmac AC_CACHE_LOAD
9251 @acindex{CACHE_LOAD}
9252 Loads values from existing cache file, or creates a new cache file if a
9253 cache file is not found.  Called automatically from @code{AC_INIT}.
9254 @end defmac
9256 @defmac AC_CACHE_SAVE
9257 @acindex{CACHE_SAVE}
9258 Flushes all cached values to the cache file.  Called automatically from
9259 @code{AC_OUTPUT}, but it can be quite useful to call
9260 @code{AC_CACHE_SAVE} at key points in @file{configure.ac}.
9261 @end defmac
9263 For instance:
9265 @example
9266 @r{ @dots{} AC_INIT, etc. @dots{}}
9267 @group
9268 # Checks for programs.
9269 AC_PROG_CC
9270 AC_PROG_AWK
9271 @r{ @dots{} more program checks @dots{}}
9272 AC_CACHE_SAVE
9273 @end group
9275 @group
9276 # Checks for libraries.
9277 AC_CHECK_LIB([nsl], [gethostbyname])
9278 AC_CHECK_LIB([socket], [connect])
9279 @r{ @dots{} more lib checks @dots{}}
9280 AC_CACHE_SAVE
9281 @end group
9283 @group
9284 # Might abort@dots{}
9285 AM_PATH_GTK([1.0.2], [], [AC_MSG_ERROR([GTK not in path])])
9286 AM_PATH_GTKMM([0.9.5], [], [AC_MSG_ERROR([GTK not in path])])
9287 @end group
9288 @r{ @dots{} AC_OUTPUT, etc. @dots{}}
9289 @end example
9291 @node Printing Messages
9292 @section Printing Messages
9293 @cindex Messages, from @command{configure}
9295 @command{configure} scripts need to give users running them several kinds
9296 of information.  The following macros print messages in ways appropriate
9297 for each kind.  The arguments to all of them get enclosed in shell
9298 double quotes, so the shell performs variable and back-quote
9299 substitution on them.
9301 These macros are all wrappers around the @command{echo} shell command.
9302 They direct output to the appropriate file descriptor (@pxref{File
9303 Descriptor Macros}).
9304 @command{configure} scripts should rarely need to run @command{echo} directly
9305 to print messages for the user.  Using these macros makes it easy to
9306 change how and when each kind of message is printed; such changes need
9307 only be made to the macro definitions and all the callers change
9308 automatically.
9310 To diagnose static issues, i.e., when @command{autoconf} is run, see
9311 @ref{Diagnostic Macros}.
9313 @defmac AC_MSG_CHECKING (@var{feature-description})
9314 @acindex{MSG_CHECKING}
9315 Notify the user that @command{configure} is checking for a particular
9316 feature.  This macro prints a message that starts with @samp{checking }
9317 and ends with @samp{...} and no newline.  It must be followed by a call
9318 to @code{AC_MSG_RESULT} to print the result of the check and the
9319 newline.  The @var{feature-description} should be something like
9320 @samp{whether the Fortran compiler accepts C++ comments} or @samp{for
9321 c89}.
9323 This macro prints nothing if @command{configure} is run with the
9324 @option{--quiet} or @option{--silent} option.
9325 @end defmac
9327 @anchor{AC_MSG_RESULT}
9328 @defmac AC_MSG_RESULT (@var{result-description})
9329 @acindex{MSG_RESULT}
9330 Notify the user of the results of a check.  @var{result-description} is
9331 almost always the value of the cache variable for the check, typically
9332 @samp{yes}, @samp{no}, or a file name.  This macro should follow a call
9333 to @code{AC_MSG_CHECKING}, and the @var{result-description} should be
9334 the completion of the message printed by the call to
9335 @code{AC_MSG_CHECKING}.
9337 This macro prints nothing if @command{configure} is run with the
9338 @option{--quiet} or @option{--silent} option.
9339 @end defmac
9341 @anchor{AC_MSG_NOTICE}
9342 @defmac AC_MSG_NOTICE (@var{message})
9343 @acindex{MSG_NOTICE}
9344 Deliver the @var{message} to the user.  It is useful mainly to print a
9345 general description of the overall purpose of a group of feature checks,
9346 e.g.,
9348 @example
9349 AC_MSG_NOTICE([checking if stack overflow is detectable])
9350 @end example
9352 This macro prints nothing if @command{configure} is run with the
9353 @option{--quiet} or @option{--silent} option.
9354 @end defmac
9356 @anchor{AC_MSG_ERROR}
9357 @defmac AC_MSG_ERROR (@var{error-description}, @dvar{exit-status, $?/1})
9358 @acindex{MSG_ERROR}
9359 Notify the user of an error that prevents @command{configure} from
9360 completing.  This macro prints an error message to the standard error
9361 output and exits @command{configure} with @var{exit-status} (@samp{$?}
9362 by default, except that @samp{0} is converted to @samp{1}).
9363 @var{error-description} should be something like @samp{invalid value
9364 $HOME for \$HOME}.
9366 The @var{error-description} should start with a lower-case letter, and
9367 ``cannot'' is preferred to ``can't''.
9368 @end defmac
9370 @defmac AC_MSG_FAILURE (@var{error-description}, @ovar{exit-status})
9371 @acindex{MSG_FAILURE}
9372 This @code{AC_MSG_ERROR} wrapper notifies the user of an error that
9373 prevents @command{configure} from completing @emph{and} that additional
9374 details are provided in @file{config.log}.  This is typically used when
9375 abnormal results are found during a compilation.
9376 @end defmac
9378 @anchor{AC_MSG_WARN}
9379 @defmac AC_MSG_WARN (@var{problem-description})
9380 @acindex{MSG_WARN}
9381 Notify the @command{configure} user of a possible problem.  This macro
9382 prints the message to the standard error output; @command{configure}
9383 continues running afterward, so macros that call @code{AC_MSG_WARN} should
9384 provide a default (back-up) behavior for the situations they warn about.
9385 @var{problem-description} should be something like @samp{ln -s seems to
9386 make hard links}.
9387 @end defmac
9391 @c ====================================================== Programming in M4.
9393 @node Programming in M4
9394 @chapter Programming in M4
9395 @cindex M4
9397 Autoconf is written on top of two layers: @dfn{M4sugar}, which provides
9398 convenient macros for pure M4 programming, and @dfn{M4sh}, which
9399 provides macros dedicated to shell script generation.
9401 As of this version of Autoconf, these two layers still contain
9402 experimental macros, whose interface might change in the future.  As a
9403 matter of fact, @emph{anything that is not documented must not be used}.
9405 @menu
9406 * M4 Quotation::                Protecting macros from unwanted expansion
9407 * Using autom4te::              The Autoconf executables backbone
9408 * Programming in M4sugar::      Convenient pure M4 macros
9409 @end menu
9411 @node M4 Quotation
9412 @section M4 Quotation
9413 @cindex M4 quotation
9414 @cindex quotation
9416 The most common problem with existing macros is an improper quotation.
9417 This section, which users of Autoconf can skip, but which macro writers
9418 @emph{must} read, first justifies the quotation scheme that was chosen
9419 for Autoconf and then ends with a rule of thumb.  Understanding the
9420 former helps one to follow the latter.
9422 @menu
9423 * Active Characters::           Characters that change the behavior of M4
9424 * One Macro Call::              Quotation and one macro call
9425 * Quoting and Parameters::      M4 vs. shell parameters
9426 * Quotation and Nested Macros::  Macros calling macros
9427 * Changequote is Evil::         Worse than INTERCAL: M4 + changequote
9428 * Quadrigraphs::                Another way to escape special characters
9429 * Balancing Parentheses::       Dealing with unbalanced parentheses
9430 * Quotation Rule Of Thumb::     One parenthesis, one quote
9431 @end menu
9433 @node Active Characters
9434 @subsection Active Characters
9436 To fully understand where proper quotation is important, you first need
9437 to know what the special characters are in Autoconf: @samp{#} introduces
9438 a comment inside which no macro expansion is performed, @samp{,}
9439 separates arguments, @samp{[} and @samp{]} are the quotes themselves,
9440 @samp{(} and @samp{)} (which M4 tries to match by pairs), and finally
9441 @samp{$} inside a macro definition.
9443 In order to understand the delicate case of macro calls, we first have
9444 to present some obvious failures.  Below they are ``obvious-ified'',
9445 but when you find them in real life, they are usually in disguise.
9447 Comments, introduced by a hash and running up to the newline, are opaque
9448 tokens to the top level: active characters are turned off, and there is
9449 no macro expansion:
9451 @example
9452 # define([def], ine)
9453 @result{}# define([def], ine)
9454 @end example
9456 Each time there can be a macro expansion, there is a quotation
9457 expansion, i.e., one level of quotes is stripped:
9459 @example
9460 int tab[10];
9461 @result{}int tab10;
9462 [int tab[10];]
9463 @result{}int tab[10];
9464 @end example
9466 Without this in mind, the reader might try hopelessly to use her macro
9467 @code{array}:
9469 @example
9470 define([array], [int tab[10];])
9471 array
9472 @result{}int tab10;
9473 [array]
9474 @result{}array
9475 @end example
9477 @noindent
9478 How can you correctly output the intended results@footnote{Using
9479 @code{defn}.}?
9482 @node One Macro Call
9483 @subsection One Macro Call
9485 Let's proceed on the interaction between active characters and macros
9486 with this small macro, which just returns its first argument:
9488 @example
9489 define([car], [$1])
9490 @end example
9492 @noindent
9493 The two pairs of quotes above are not part of the arguments of
9494 @code{define}; rather, they are understood by the top level when it
9495 tries to find the arguments of @code{define}.  Therefore, assuming
9496 @code{car} is not already defined, it is equivalent to write:
9498 @example
9499 define(car, $1)
9500 @end example
9502 @noindent
9503 But, while it is acceptable for a @file{configure.ac} to avoid unnecessary
9504 quotes, it is bad practice for Autoconf macros which must both be more
9505 robust and also advocate perfect style.
9507 At the top level, there are only two possibilities: either you
9508 quote or you don't:
9510 @example
9511 car(foo, bar, baz)
9512 @result{}foo
9513 [car(foo, bar, baz)]
9514 @result{}car(foo, bar, baz)
9515 @end example
9517 Let's pay attention to the special characters:
9519 @example
9520 car(#)
9521 @error{}EOF in argument list
9522 @end example
9524 The closing parenthesis is hidden in the comment; with a hypothetical
9525 quoting, the top level understood it this way:
9527 @example
9528 car([#)]
9529 @end example
9531 @noindent
9532 Proper quotation, of course, fixes the problem:
9534 @example
9535 car([#])
9536 @result{}#
9537 @end example
9539 Here are more examples:
9541 @example
9542 car(foo, bar)
9543 @result{}foo
9544 car([foo, bar])
9545 @result{}foo, bar
9546 car((foo, bar))
9547 @result{}(foo, bar)
9548 car([(foo], [bar)])
9549 @result{}(foo
9550 define([a], [b])
9551 @result{}
9552 car(a)
9553 @result{}b
9554 car([a])
9555 @result{}b
9556 car([[a]])
9557 @result{}a
9558 car([[[a]]])
9559 @result{}[a]
9560 @end example
9562 @node Quoting and Parameters
9563 @subsection Quoting and Parameters
9565 When M4 encounters @samp{$} within a macro definition, followed
9566 immediately by a character it recognizes (@samp{0}@dots{}@samp{9},
9567 @samp{#}, @samp{@@}, or @samp{*}), it will perform M4 parameter
9568 expansion.  This happens regardless of how many layers of quotes the
9569 parameter expansion is nested within, or even if it occurs in text that
9570 will be rescanned as a comment.
9572 @example
9573 define([none], [$1])
9574 @result{}
9575 define([one], [[$1]])
9576 @result{}
9577 define([two], [[[$1]]])
9578 @result{}
9579 define([comment], [# $1])
9580 @result{}
9581 define([active], [ACTIVE])
9582 @result{}
9583 none([active])
9584 @result{}ACTIVE
9585 one([active])
9586 @result{}active
9587 two([active])
9588 @result{}[active]
9589 comment([active])
9590 @result{}# active
9591 @end example
9593 On the other hand, since autoconf generates shell code, you often want
9594 to output shell variable expansion, rather than performing M4 parameter
9595 expansion.  To do this, you must use M4 quoting to separate the @samp{$}
9596 from the next character in the definition of your macro.  If the macro
9597 definition occurs in single-quoted text, then insert another level of
9598 quoting; if the usage is already inside a double-quoted string, then
9599 split it into concatenated strings.
9601 @example
9602 define([single], [a single-quoted $[]1 definition])
9603 @result{}
9604 define([double], [[a double-quoted $][1 definition]])
9605 @result{}
9606 single
9607 @result{}a single-quoted $1 definition
9608 double
9609 @result{}a double-quoted $1 definition
9610 @end example
9612 Posix states that M4 implementations are free to provide implementation
9613 extensions when @samp{$@{} is encountered in a macro definition.
9614 Autoconf reserves the longer sequence @samp{$@{@{} for use with planned
9615 extensions that will be available in the future @acronym{GNU} M4 2.0,
9616 but guarantees that all other instances of @samp{$@{} will be output
9617 literally.  Therefore, this idiom can also be used to output shell code
9618 parameter references:
9620 @example
9621 define([first], [$@{1@}])first
9622 @result{}$@{1@}
9623 @end example
9625 Posix also states that @samp{$11} should expand to the first parameter
9626 concatenated with a literal @samp{1}, although some versions of
9627 @acronym{GNU} M4 expand the eleventh parameter instead.  For
9628 portability, you should only use single-digit M4 parameter expansion.
9630 With this in mind, we can explore the cases where macros invoke
9631 macros@enddots{}
9633 @node Quotation and Nested Macros
9634 @subsection Quotation and Nested Macros
9636 The examples below use the following macros:
9638 @example
9639 define([car], [$1])
9640 define([active], [ACT, IVE])
9641 define([array], [int tab[10]])
9642 @end example
9644 Each additional embedded macro call introduces other possible
9645 interesting quotations:
9647 @example
9648 car(active)
9649 @result{}ACT
9650 car([active])
9651 @result{}ACT, IVE
9652 car([[active]])
9653 @result{}active
9654 @end example
9656 In the first case, the top level looks for the arguments of @code{car},
9657 and finds @samp{active}.  Because M4 evaluates its arguments
9658 before applying the macro, @samp{active} is expanded, which results in:
9660 @example
9661 car(ACT, IVE)
9662 @result{}ACT
9663 @end example
9665 @noindent
9666 In the second case, the top level gives @samp{active} as first and only
9667 argument of @code{car}, which results in:
9669 @example
9670 active
9671 @result{}ACT, IVE
9672 @end example
9674 @noindent
9675 i.e., the argument is evaluated @emph{after} the macro that invokes it.
9676 In the third case, @code{car} receives @samp{[active]}, which results in:
9678 @example
9679 [active]
9680 @result{}active
9681 @end example
9683 @noindent
9684 exactly as we already saw above.
9686 The example above, applied to a more realistic example, gives:
9688 @example
9689 car(int tab[10];)
9690 @result{}int tab10;
9691 car([int tab[10];])
9692 @result{}int tab10;
9693 car([[int tab[10];]])
9694 @result{}int tab[10];
9695 @end example
9697 @noindent
9698 Huh?  The first case is easily understood, but why is the second wrong,
9699 and the third right?  To understand that, you must know that after
9700 M4 expands a macro, the resulting text is immediately subjected
9701 to macro expansion and quote removal.  This means that the quote removal
9702 occurs twice---first before the argument is passed to the @code{car}
9703 macro, and second after the @code{car} macro expands to the first
9704 argument.
9706 As the author of the Autoconf macro @code{car}, you then consider it to
9707 be incorrect that your users have to double-quote the arguments of
9708 @code{car}, so you ``fix'' your macro.  Let's call it @code{qar} for
9709 quoted car:
9711 @example
9712 define([qar], [[$1]])
9713 @end example
9715 @noindent
9716 and check that @code{qar} is properly fixed:
9718 @example
9719 qar([int tab[10];])
9720 @result{}int tab[10];
9721 @end example
9723 @noindent
9724 Ahhh!  That's much better.
9726 But note what you've done: now that the result of @code{qar} is always
9727 a literal string, the only time a user can use nested macros is if she
9728 relies on an @emph{unquoted} macro call:
9730 @example
9731 qar(active)
9732 @result{}ACT
9733 qar([active])
9734 @result{}active
9735 @end example
9737 @noindent
9738 leaving no way for her to reproduce what she used to do with @code{car}:
9740 @example
9741 car([active])
9742 @result{}ACT, IVE
9743 @end example
9745 @noindent
9746 Worse yet: she wants to use a macro that produces a set of @code{cpp}
9747 macros:
9749 @example
9750 define([my_includes], [#include <stdio.h>])
9751 car([my_includes])
9752 @result{}#include <stdio.h>
9753 qar(my_includes)
9754 @error{}EOF in argument list
9755 @end example
9757 This macro, @code{qar}, because it double quotes its arguments, forces
9758 its users to leave their macro calls unquoted, which is dangerous.
9759 Commas and other active symbols are interpreted by M4 before
9760 they are given to the macro, often not in the way the users expect.
9761 Also, because @code{qar} behaves differently from the other macros,
9762 it's an exception that should be avoided in Autoconf.
9764 @node Changequote is Evil
9765 @subsection @code{changequote} is Evil
9766 @cindex @code{changequote}
9768 The temptation is often high to bypass proper quotation, in particular
9769 when it's late at night.  Then, many experienced Autoconf hackers
9770 finally surrender to the dark side of the force and use the ultimate
9771 weapon: @code{changequote}.
9773 The M4 builtin @code{changequote} belongs to a set of primitives that
9774 allow one to adjust the syntax of the language to adjust it to one's
9775 needs.  For instance, by default M4 uses @samp{`} and @samp{'} as
9776 quotes, but in the context of shell programming (and actually of most
9777 programming languages), that's about the worst choice one can make:
9778 because of strings and back-quoted expressions in shell code (such as
9779 @samp{'this'} and @samp{`that`}), and because of literal characters in usual
9780 programming languages (as in @samp{'0'}), there are many unbalanced
9781 @samp{`} and @samp{'}.  Proper M4 quotation then becomes a nightmare, if
9782 not impossible.  In order to make M4 useful in such a context, its
9783 designers have equipped it with @code{changequote}, which makes it
9784 possible to choose another pair of quotes.  M4sugar, M4sh, Autoconf, and
9785 Autotest all have chosen to use @samp{[} and @samp{]}.  Not especially
9786 because they are unlikely characters, but @emph{because they are
9787 characters unlikely to be unbalanced}.
9789 There are other magic primitives, such as @code{changecom} to specify
9790 what syntactic forms are comments (it is common to see
9791 @samp{changecom(<!--, -->)} when M4 is used to produce HTML pages),
9792 @code{changeword} and @code{changesyntax} to change other syntactic
9793 details (such as the character to denote the @var{n}th argument, @samp{$} by
9794 default, the parentheses around arguments, etc.).
9796 These primitives are really meant to make M4 more useful for specific
9797 domains: they should be considered like command line options:
9798 @option{--quotes}, @option{--comments}, @option{--words}, and
9799 @option{--syntax}.  Nevertheless, they are implemented as M4 builtins, as
9800 it makes M4 libraries self contained (no need for additional options).
9802 There lies the problem@enddots{}
9804 @sp 1
9806 The problem is that it is then tempting to use them in the middle of an
9807 M4 script, as opposed to its initialization.  This, if not carefully
9808 thought out, can lead to disastrous effects: @emph{you are changing the
9809 language in the middle of the execution}.  Changing and restoring the
9810 syntax is often not enough: if you happened to invoke macros in between,
9811 these macros are lost, as the current syntax is probably not
9812 the one they were implemented with.
9814 @c FIXME: I've been looking for a short, real case example, but I
9815 @c lost them all :(
9818 @node Quadrigraphs
9819 @subsection Quadrigraphs
9820 @cindex quadrigraphs
9821 @cindex @samp{@@S|@@}
9822 @cindex @samp{@@&t@@}
9823 @c Info cannot handle `:' in index entries.
9824 @c @cindex @samp{@@<:@@}
9825 @c @cindex @samp{@@:>@@}
9826 @c @cindex @samp{@@%:@@}
9827 @c @cindex @samp{@@@{:@@}
9828 @c @cindex @samp{@@:@}@@}
9830 When writing an Autoconf macro you may occasionally need to generate
9831 special characters that are difficult to express with the standard
9832 Autoconf quoting rules.  For example, you may need to output the regular
9833 expression @samp{[^[]}, which matches any character other than @samp{[}.
9834 This expression contains unbalanced brackets so it cannot be put easily
9835 into an M4 macro.
9837 Additionally, there are a few m4sugar macros (such as @code{m4_split}
9838 and @code{m4_expand}) which internally use special markers in addition
9839 to the regular quoting characters.  If the arguments to these macros
9840 contain the literal strings @samp{-=<@{(} or @samp{)@}>=-}, the macros
9841 might behave incorrectly.
9843 You can work around these problems by using one of the following
9844 @dfn{quadrigraphs}:
9846 @table @samp
9847 @item @@<:@@
9848 @samp{[}
9849 @item @@:>@@
9850 @samp{]}
9851 @item @@S|@@
9852 @samp{$}
9853 @item @@%:@@
9854 @samp{#}
9855 @item @@@{:@@
9856 @samp{(}
9857 @item @@:@}@@
9858 @samp{)}
9859 @item @@&t@@
9860 Expands to nothing.
9861 @end table
9863 Quadrigraphs are replaced at a late stage of the translation process,
9864 after @command{m4} is run, so they do not get in the way of M4 quoting.
9865 For example, the string @samp{^@@<:@@}, independently of its quotation,
9866 appears as @samp{^[} in the output.
9868 The empty quadrigraph can be used:
9870 @itemize @minus
9871 @item to mark trailing spaces explicitly
9873 Trailing spaces are smashed by @command{autom4te}.  This is a feature.
9875 @item to produce quadrigraphs and other strings reserved by m4sugar
9877 For instance @samp{@@<@@&t@@:@@} produces @samp{@@<:@@}.  For a more
9878 contrived example:
9880 @example
9881 m4_define([a], [A])m4_define([b], [B])m4_define([c], [C])dnl
9882 m4_split([a )@}>=- b -=<@{( c])
9883 @result{}[a], [], [B], [], [c]
9884 m4_split([a )@}@@&t@@>=- b -=<@@&t@@@{( c])
9885 @result{}[a], [)@}>=-], [b], [-=<@{(], [c]
9886 @end example
9888 @item to escape @emph{occurrences} of forbidden patterns
9890 For instance you might want to mention @code{AC_FOO} in a comment, while
9891 still being sure that @command{autom4te} still catches unexpanded
9892 @samp{AC_*}.  Then write @samp{AC@@&t@@_FOO}.
9893 @end itemize
9895 The name @samp{@@&t@@} was suggested by Paul Eggert:
9897 @quotation
9898 I should give some credit to the @samp{@@&t@@} pun.  The @samp{&} is my
9899 own invention, but the @samp{t} came from the source code of the
9900 @sc{algol68c} compiler, written by Steve Bourne (of Bourne shell fame),
9901 and which used @samp{mt} to denote the empty string.  In C, it would
9902 have looked like something like:
9904 @example
9905 char const mt[] = "";
9906 @end example
9908 @noindent
9909 but of course the source code was written in Algol 68.
9911 I don't know where he got @samp{mt} from: it could have been his own
9912 invention, and I suppose it could have been a common pun around the
9913 Cambridge University computer lab at the time.
9914 @end quotation
9917 @node Balancing Parentheses
9918 @subsection Dealing with unbalanced parentheses
9919 @cindex balancing parentheses
9920 @cindex parentheses, balancing
9921 @cindex unbalanced parentheses, managing
9923 One of the pitfalls of portable shell programming is that @command{case}
9924 statements require unbalanced parentheses (@pxref{case, , Limitations of
9925 Shell Builtins}).  With syntax highlighting
9926 editors, the presence of unbalanced @samp{)} can interfere with editors
9927 that perform syntax highlighting of macro contents based on finding the
9928 matching @samp{(}.  Another concern is how much editing must be done
9929 when transferring code snippets between shell scripts and macro
9930 definitions.  But most importantly, the presence of unbalanced
9931 parentheses can introduce expansion bugs.
9933 For an example, here is an underquoted attempt to use the macro
9934 @code{my_case}, which happens to expand to a portable @command{case}
9935 statement:
9937 @example
9938 AC_DEFUN([my_case],
9939 [case $file_name in
9940   *.c) echo "C source code";;
9941 esac])
9942 AS_IF(:, my_case)
9943 @end example
9945 @noindent
9946 In the above example, the @code{AS_IF} call underquotes its arguments.
9947 As a result, the unbalanced @samp{)} generated by the premature
9948 expansion of @code{my_case} results in expanding @code{AS_IF} with a
9949 truncated parameter, and the expansion is syntactically invalid:
9951 @example
9952 if :; then
9953   case $file_name in
9954   *.c
9955 fi echo "C source code";;
9956 esac)
9957 @end example
9959 If nothing else, this should emphasize the importance of the quoting
9960 arguments to macro calls.  On the other hand, there are several
9961 variations for defining @code{my_case} to be more robust, even when used
9962 without proper quoting, each with some benefits and some drawbacks.
9964 @itemize @w{}
9965 @item Creative literal shell comment
9966 @example
9967 AC_DEFUN([my_case],
9968 [case $file_name in #(
9969   *.c) echo "C source code";;
9970 esac])
9971 @end example
9972 @noindent
9973 This version provides balanced parentheses to several editors, and can
9974 be copied and pasted into a terminal as is.  Unfortunately, it is still
9975 unbalanced as an Autoconf argument, since @samp{#(} is an M4 comment
9976 that masks the normal properties of @samp{(}.
9978 @item Quadrigraph shell comment
9979 @example
9980 AC_DEFUN([my_case],
9981 [case $file_name in @@%:@@(
9982   *.c) echo "C source code";;
9983 esac])
9984 @end example
9985 @noindent
9986 This version provides balanced parentheses to even more editors, and can
9987 be used as a balanced Autoconf argument.  Unfortunately, it requires
9988 some editing before it can be copied and pasted into a terminal, and the
9989 use of the quadrigraph @samp{@@%:@@} for @samp{#} reduces readability.
9991 @item Quoting just the parenthesis
9992 @example
9993 AC_DEFUN([my_case],
9994 [case $file_name in
9995   *.c[)] echo "C source code";;
9996 esac])
9997 @end example
9998 @noindent
9999 This version quotes the @samp{)}, so that it can be used as a balanced
10000 Autoconf argument.  As written, this is not balanced to an editor, but
10001 it can be coupled with @samp{[#(]} to meet that need, too.  However, it
10002 still requires some edits before it can be copied and pasted into a
10003 terminal.
10005 @item Double-quoting the entire statement
10006 @example
10007 AC_DEFUN([my_case],
10008 [[case $file_name in #(
10009   *.c) echo "C source code";;
10010 esac]])
10011 @end example
10012 @noindent
10013 Since the entire macro is double-quoted, there is no problem with using
10014 this as an Autoconf argument; and since the double-quoting is over the
10015 entire statement, this code can be easily copied and pasted into a
10016 terminal.  However, the double quoting prevents the expansion of any
10017 macros inside the case statement, which may cause its own set of
10018 problems.
10020 @item Using @code{AS_CASE}
10021 @example
10022 AC_DEFUN([my_case],
10023 [AS_CASE([$file_name],
10024   [*.c], [echo "C source code"])])
10025 @end example
10026 @noindent
10027 This version avoids the balancing issue altogether, by relying on
10028 @code{AS_CASE} (@pxref{Common Shell Constructs}); it also allows for the
10029 expansion of @code{AC_REQUIRE} to occur prior to the entire case
10030 statement, rather than within a branch of the case statement that might
10031 not be taken.  However, the abstraction comes with a penalty that it is
10032 no longer a quick copy, paste, and edit to get back to shell code.
10033 @end itemize
10036 @node Quotation Rule Of Thumb
10037 @subsection Quotation Rule Of Thumb
10039 To conclude, the quotation rule of thumb is:
10041 @center @emph{One pair of quotes per pair of parentheses.}
10043 Never over-quote, never under-quote, in particular in the definition of
10044 macros.  In the few places where the macros need to use brackets
10045 (usually in C program text or regular expressions), properly quote
10046 @emph{the arguments}!
10048 It is common to read Autoconf programs with snippets like:
10050 @example
10051 AC_TRY_LINK(
10052 changequote(<<, >>)dnl
10053 <<#include <time.h>
10054 #ifndef tzname /* For SGI.  */
10055 extern char *tzname[]; /* RS6000 and others reject char **tzname.  */
10056 #endif>>,
10057 changequote([, ])dnl
10058 [atoi (*tzname);], ac_cv_var_tzname=yes, ac_cv_var_tzname=no)
10059 @end example
10061 @noindent
10062 which is incredibly useless since @code{AC_TRY_LINK} is @emph{already}
10063 double quoting, so you just need:
10065 @example
10066 AC_TRY_LINK(
10067 [#include <time.h>
10068 #ifndef tzname /* For SGI.  */
10069 extern char *tzname[]; /* RS6000 and others reject char **tzname.  */
10070 #endif],
10071             [atoi (*tzname);],
10072             [ac_cv_var_tzname=yes],
10073             [ac_cv_var_tzname=no])
10074 @end example
10076 @noindent
10077 The M4-fluent reader might note that these two examples are rigorously
10078 equivalent, since M4 swallows both the @samp{changequote(<<, >>)}
10079 and @samp{<<} @samp{>>} when it @dfn{collects} the arguments: these
10080 quotes are not part of the arguments!
10082 Simplified, the example above is just doing this:
10084 @example
10085 changequote(<<, >>)dnl
10086 <<[]>>
10087 changequote([, ])dnl
10088 @end example
10090 @noindent
10091 instead of simply:
10093 @example
10094 [[]]
10095 @end example
10097 With macros that do not double quote their arguments (which is the
10098 rule), double-quote the (risky) literals:
10100 @example
10101 AC_LINK_IFELSE([AC_LANG_PROGRAM(
10102 [[#include <time.h>
10103 #ifndef tzname /* For SGI.  */
10104 extern char *tzname[]; /* RS6000 and others reject char **tzname.  */
10105 #endif]],
10106                                 [atoi (*tzname);])],
10107                [ac_cv_var_tzname=yes],
10108                [ac_cv_var_tzname=no])
10109 @end example
10111 Please note that the macro @code{AC_TRY_LINK} is obsolete, so you really
10112 should be using @code{AC_LINK_IFELSE} instead.
10114 @xref{Quadrigraphs}, for what to do if you run into a hopeless case
10115 where quoting does not suffice.
10117 When you create a @command{configure} script using newly written macros,
10118 examine it carefully to check whether you need to add more quotes in
10119 your macros.  If one or more words have disappeared in the M4
10120 output, you need more quotes.  When in doubt, quote.
10122 However, it's also possible to put on too many layers of quotes.  If
10123 this happens, the resulting @command{configure} script may contain
10124 unexpanded macros.  The @command{autoconf} program checks for this problem
10125 by looking for the string @samp{AC_} in @file{configure}.  However, this
10126 heuristic does not work in general: for example, it does not catch
10127 overquoting in @code{AC_DEFINE} descriptions.
10130 @c ---------------------------------------- Using autom4te
10132 @node Using autom4te
10133 @section Using @command{autom4te}
10135 The Autoconf suite, including M4sugar, M4sh, and Autotest, in addition
10136 to Autoconf per se, heavily rely on M4.  All these different uses
10137 revealed common needs factored into a layer over M4:
10138 @command{autom4te}@footnote{
10140 Yet another great name from Lars J. Aas.
10144 @command{autom4te} is a preprocessor that is like @command{m4}.
10145 It supports M4 extensions designed for use in tools like Autoconf.
10147 @menu
10148 * autom4te Invocation::         A @acronym{GNU} M4 wrapper
10149 * Customizing autom4te::        Customizing the Autoconf package
10150 @end menu
10152 @node autom4te Invocation
10153 @subsection Invoking @command{autom4te}
10155 The command line arguments are modeled after M4's:
10157 @example
10158 autom4te @var{options} @var{files}
10159 @end example
10161 @noindent
10162 @evindex M4
10163 where the @var{files} are directly passed to @command{m4}.  By default,
10164 @acronym{GNU} M4 is found during configuration, but the environment
10165 variable
10166 @env{M4} can be set to tell @command{autom4te} where to look.  In addition
10167 to the regular expansion, it handles the replacement of the quadrigraphs
10168 (@pxref{Quadrigraphs}), and of @samp{__oline__}, the current line in the
10169 output.  It supports an extended syntax for the @var{files}:
10171 @table @file
10172 @item @var{file}.m4f
10173 This file is an M4 frozen file.  Note that @emph{all the previous files
10174 are ignored}.  See the option @option{--melt} for the rationale.
10176 @item @var{file}?
10177 If found in the library path, the @var{file} is included for expansion,
10178 otherwise it is ignored instead of triggering a failure.
10179 @end table
10181 @sp 1
10183 Of course, it supports the Autoconf common subset of options:
10185 @table @option
10186 @item --help
10187 @itemx -h
10188 Print a summary of the command line options and exit.
10190 @item --version
10191 @itemx -V
10192 Print the version number of Autoconf and exit.
10194 @item --verbose
10195 @itemx -v
10196 Report processing steps.
10198 @item --debug
10199 @itemx -d
10200 Don't remove the temporary files and be even more verbose.
10202 @item --include=@var{dir}
10203 @itemx -I @var{dir}
10204 Also look for input files in @var{dir}.  Multiple invocations
10205 accumulate.
10207 @item --output=@var{file}
10208 @itemx -o @var{file}
10209 Save output (script or trace) to @var{file}.  The file @option{-} stands
10210 for the standard output.
10211 @end table
10213 @sp 1
10215 As an extension of @command{m4}, it includes the following options:
10217 @table @option
10218 @item --warnings=@var{category}
10219 @itemx -W @var{category}
10220 @evindex WARNINGS
10221 @c FIXME: Point to the M4sugar macros, not Autoconf's.
10222 Report the warnings related to @var{category} (which can actually be a
10223 comma separated list).  @xref{Reporting Messages}, macro
10224 @code{AC_DIAGNOSE}, for a comprehensive list of categories.  Special
10225 values include:
10227 @table @samp
10228 @item all
10229 report all the warnings
10231 @item none
10232 report none
10234 @item error
10235 treats warnings as errors
10237 @item no-@var{category}
10238 disable warnings falling into @var{category}
10239 @end table
10241 Warnings about @samp{syntax} are enabled by default, and the environment
10242 variable @env{WARNINGS}, a comma separated list of categories, is
10243 honored.  @samp{autom4te -W @var{category}} actually
10244 behaves as if you had run:
10246 @example
10247 autom4te --warnings=syntax,$WARNINGS,@var{category}
10248 @end example
10250 @noindent
10251 For example, if you want to disable defaults and @env{WARNINGS}
10252 of @command{autom4te}, but enable the warnings about obsolete
10253 constructs, you would use @option{-W none,obsolete}.
10255 @cindex Back trace
10256 @cindex Macro invocation stack
10257 @command{autom4te} displays a back trace for errors, but not for
10258 warnings; if you want them, just pass @option{-W error}.
10260 @item --melt
10261 @itemx -M
10262 Do not use frozen files.  Any argument @code{@var{file}.m4f} is
10263 replaced by @code{@var{file}.m4}.  This helps tracing the macros which
10264 are executed only when the files are frozen, typically
10265 @code{m4_define}.  For instance, running:
10267 @example
10268 autom4te --melt 1.m4 2.m4f 3.m4 4.m4f input.m4
10269 @end example
10271 @noindent
10272 is roughly equivalent to running:
10274 @example
10275 m4 1.m4 2.m4 3.m4 4.m4 input.m4
10276 @end example
10278 @noindent
10279 while
10281 @example
10282 autom4te 1.m4 2.m4f 3.m4 4.m4f input.m4
10283 @end example
10285 @noindent
10286 is equivalent to:
10288 @example
10289 m4 --reload-state=4.m4f input.m4
10290 @end example
10292 @item --freeze
10293 @itemx -F
10294 Produce a frozen state file.  @command{autom4te} freezing is stricter
10295 than M4's: it must produce no warnings, and no output other than empty
10296 lines (a line with white space is @emph{not} empty) and comments
10297 (starting with @samp{#}).  Unlike @command{m4}'s similarly-named option,
10298 this option takes no argument:
10300 @example
10301 autom4te 1.m4 2.m4 3.m4 --freeze --output=3.m4f
10302 @end example
10304 @noindent
10305 corresponds to
10307 @example
10308 m4 1.m4 2.m4 3.m4 --freeze-state=3.m4f
10309 @end example
10311 @item --mode=@var{octal-mode}
10312 @itemx -m @var{octal-mode}
10313 Set the mode of the non-traces output to @var{octal-mode}; by default
10314 @samp{0666}.
10315 @end table
10317 @sp 1
10319 @cindex @file{autom4te.cache}
10320 As another additional feature over @command{m4}, @command{autom4te}
10321 caches its results.  @acronym{GNU} M4 is able to produce a regular
10322 output and traces at the same time.  Traces are heavily used in the
10323 @acronym{GNU} Build System: @command{autoheader} uses them to build
10324 @file{config.h.in}, @command{autoreconf} to determine what
10325 @acronym{GNU} Build System components are used, @command{automake} to
10326 ``parse'' @file{configure.ac} etc.  To avoid recomputation,
10327 traces are cached while performing regular expansion,
10328 and conversely.  This cache is (actually, the caches are) stored in
10329 the directory @file{autom4te.cache}.  @emph{It can safely be removed}
10330 at any moment (especially if for some reason @command{autom4te}
10331 considers it trashed).
10333 @table @option
10334 @item --cache=@var{directory}
10335 @itemx -C @var{directory}
10336 Specify the name of the directory where the result should be cached.
10337 Passing an empty value disables caching.  Be sure to pass a relative
10338 file name, as for the time being, global caches are not supported.
10340 @item --no-cache
10341 Don't cache the results.
10343 @item --force
10344 @itemx -f
10345 If a cache is used, consider it obsolete (but update it anyway).
10346 @end table
10348 @sp 1
10350 Because traces are so important to the @acronym{GNU} Build System,
10351 @command{autom4te} provides high level tracing features as compared to
10352 M4, and helps exploiting the cache:
10354 @table @option
10355 @item --trace=@var{macro}[:@var{format}]
10356 @itemx -t @var{macro}[:@var{format}]
10357 Trace the invocations of @var{macro} according to the @var{format}.
10358 Multiple @option{--trace} arguments can be used to list several macros.
10359 Multiple @option{--trace} arguments for a single macro are not
10360 cumulative; instead, you should just make @var{format} as long as
10361 needed.
10363 The @var{format} is a regular string, with newlines if desired, and
10364 several special escape codes.  It defaults to @samp{$f:$l:$n:$%}.  It can
10365 use the following special escapes:
10367 @table @samp
10368 @item $$
10369 The character @samp{$}.
10371 @item $f
10372 The file name from which @var{macro} is called.
10374 @item $l
10375 The line number from which @var{macro} is called.
10377 @item $d
10378 The depth of the @var{macro} call.  This is an M4 technical detail that
10379 you probably don't want to know about.
10381 @item $n
10382 The name of the @var{macro}.
10384 @item $@var{num}
10385 The @var{num}th argument of the call to @var{macro}.
10387 @item $@@
10388 @itemx $@var{sep}@@
10389 @itemx $@{@var{separator}@}@@
10390 All the arguments passed to @var{macro}, separated by the character
10391 @var{sep} or the string @var{separator} (@samp{,} by default).  Each
10392 argument is quoted, i.e., enclosed in a pair of square brackets.
10394 @item $*
10395 @itemx $@var{sep}*
10396 @itemx $@{@var{separator}@}*
10397 As above, but the arguments are not quoted.
10399 @item $%
10400 @itemx $@var{sep}%
10401 @itemx $@{@var{separator}@}%
10402 As above, but the arguments are not quoted, all new line characters in
10403 the arguments are smashed, and the default separator is @samp{:}.
10405 The escape @samp{$%} produces single-line trace outputs (unless you put
10406 newlines in the @samp{separator}), while @samp{$@@} and @samp{$*} do
10407 not.
10408 @end table
10410 @xref{autoconf Invocation}, for examples of trace uses.
10412 @item --preselect=@var{macro}
10413 @itemx -p @var{macro}
10414 Cache the traces of @var{macro}, but do not enable traces.  This is
10415 especially important to save CPU cycles in the future.  For instance,
10416 when invoked, @command{autoconf} preselects all the macros that
10417 @command{autoheader}, @command{automake}, @command{autoreconf}, etc.,
10418 trace, so that running @command{m4} is not needed to trace them: the
10419 cache suffices.  This results in a huge speed-up.
10420 @end table
10422 @sp 1
10424 @cindex Autom4te Library
10425 Finally, @command{autom4te} introduces the concept of @dfn{Autom4te
10426 libraries}.  They consists in a powerful yet extremely simple feature:
10427 sets of combined command line arguments:
10429 @table @option
10430 @item --language=@var{language}
10431 @itemx -l @var{language}
10432 Use the @var{language} Autom4te library.  Current languages include:
10434 @table @code
10435 @item M4sugar
10436 create M4sugar output.
10438 @item M4sh
10439 create M4sh executable shell scripts.
10441 @item Autotest
10442 create Autotest executable test suites.
10444 @item Autoconf-without-aclocal-m4
10445 create Autoconf executable configure scripts without
10446 reading @file{aclocal.m4}.
10448 @item Autoconf
10449 create Autoconf executable configure scripts.  This language inherits
10450 all the characteristics of @code{Autoconf-without-aclocal-m4} and
10451 additionally reads @file{aclocal.m4}.
10452 @end table
10454 @item --prepend-include=@var{dir}
10455 @itemx -B @var{dir}
10456 Prepend directory @var{dir} to the search path.  This is used to include
10457 the language-specific files before any third-party macros.
10459 @end table
10461 @cindex @file{autom4te.cfg}
10462 As an example, if Autoconf is installed in its default location,
10463 @file{/usr/local}, the command @samp{autom4te -l m4sugar foo.m4} is
10464 strictly equivalent to the command:
10466 @example
10467 autom4te --prepend-include /usr/local/share/autoconf \
10468   m4sugar/m4sugar.m4f --warnings syntax foo.m4
10469 @end example
10471 @noindent
10472 Recursive expansion applies here: the command @samp{autom4te -l m4sh foo.m4}
10473 is the same as @samp{autom4te --language M4sugar m4sugar/m4sh.m4f
10474 foo.m4}, i.e.:
10476 @example
10477 autom4te --prepend-include /usr/local/share/autoconf \
10478   m4sugar/m4sugar.m4f m4sugar/m4sh.m4f --mode 777 foo.m4
10479 @end example
10481 @noindent
10482 The definition of the languages is stored in @file{autom4te.cfg}.
10484 @node Customizing autom4te
10485 @subsection Customizing @command{autom4te}
10487 One can customize @command{autom4te} via @file{~/.autom4te.cfg} (i.e.,
10488 as found in the user home directory), and @file{./.autom4te.cfg} (i.e.,
10489 as found in the directory from which @command{autom4te} is run).  The
10490 order is first reading @file{autom4te.cfg}, then @file{~/.autom4te.cfg},
10491 then @file{./.autom4te.cfg}, and finally the command line arguments.
10493 In these text files, comments are introduced with @code{#}, and empty
10494 lines are ignored.  Customization is performed on a per-language basis,
10495 wrapped in between a @samp{begin-language: "@var{language}"},
10496 @samp{end-language: "@var{language}"} pair.
10498 Customizing a language stands for appending options (@pxref{autom4te
10499 Invocation}) to the current definition of the language.  Options, and
10500 more generally arguments, are introduced by @samp{args:
10501 @var{arguments}}.  You may use the traditional shell syntax to quote the
10502 @var{arguments}.
10504 As an example, to disable Autoconf caches (@file{autom4te.cache})
10505 globally, include the following lines in @file{~/.autom4te.cfg}:
10507 @verbatim
10508 ## ------------------ ##
10509 ## User Preferences.  ##
10510 ## ------------------ ##
10512 begin-language: "Autoconf-without-aclocal-m4"
10513 args: --no-cache
10514 end-language: "Autoconf-without-aclocal-m4"
10515 @end verbatim
10518 @node Programming in M4sugar
10519 @section Programming in M4sugar
10521 @cindex M4sugar
10522 M4 by itself provides only a small, but sufficient, set of all-purpose
10523 macros.  M4sugar introduces additional generic macros.  Its name was
10524 coined by Lars J. Aas: ``Readability And Greater Understanding Stands 4
10525 M4sugar''.
10527 M4sugar reserves the macro namespace @samp{^_m4_} for internal use, and
10528 the macro namespace @samp{^m4_} for M4sugar macros.  You should not
10529 define your own macros into these namespaces.
10531 @menu
10532 * Redefined M4 Macros::         M4 builtins changed in M4sugar
10533 * Diagnostic Macros::           Diagnostic messages from M4sugar
10534 * Diversion support::           Diversions in M4sugar
10535 * Conditional constructs::      Conditions in M4
10536 * Looping constructs::          Iteration in M4
10537 * Evaluation Macros::           More quotation and evaluation control
10538 * Text processing Macros::      String manipulation in M4
10539 * Number processing Macros::    Arithmetic computation in M4
10540 * Set manipulation Macros::     Set manipulation in M4
10541 * Forbidden Patterns::          Catching unexpanded macros
10542 @end menu
10544 @node Redefined M4 Macros
10545 @subsection Redefined M4 Macros
10547 @msindex{builtin}
10548 @msindex{changecom}
10549 @msindex{changequote}
10550 @msindex{debugfile}
10551 @msindex{debugmode}
10552 @msindex{decr}
10553 @msindex{define}
10554 @msindex{divnum}
10555 @msindex{errprint}
10556 @msindex{esyscmd}
10557 @msindex{eval}
10558 @msindex{format}
10559 @msindex{ifdef}
10560 @msindex{incr}
10561 @msindex{index}
10562 @msindex{indir}
10563 @msindex{len}
10564 @msindex{pushdef}
10565 @msindex{shift}
10566 @msindex{substr}
10567 @msindex{syscmd}
10568 @msindex{sysval}
10569 @msindex{traceoff}
10570 @msindex{traceon}
10571 @msindex{translit}
10572 With a few exceptions, all the M4 native macros are moved in the
10573 @samp{m4_} pseudo-namespace, e.g., M4sugar renames @code{define} as
10574 @code{m4_define} etc.
10576 The list of macros unchanged from M4, except for their name, is:
10577 @itemize @minus
10578 @item m4_builtin
10579 @item m4_changecom
10580 @item m4_changequote
10581 @item m4_debugfile
10582 @item m4_debugmode
10583 @item m4_decr
10584 @item m4_define
10585 @item m4_divnum
10586 @item m4_errprint
10587 @item m4_esyscmd
10588 @item m4_eval
10589 @item m4_format
10590 @item m4_ifdef
10591 @item m4_incr
10592 @item m4_index
10593 @item m4_indir
10594 @item m4_len
10595 @item m4_pushdef
10596 @item m4_shift
10597 @item m4_substr
10598 @item m4_syscmd
10599 @item m4_sysval
10600 @item m4_traceoff
10601 @item m4_traceon
10602 @item m4_translit
10603 @end itemize
10605 Some M4 macros are redefined, and are slightly incompatible with their
10606 native equivalent.
10608 @defmac __file__
10609 @defmacx __line__
10610 @MSindex __file__
10611 @MSindex __line__
10612 All M4 macros starting with @samp{__} retain their original name: for
10613 example, no @code{m4__file__} is defined.
10614 @end defmac
10616 @defmac __oline__
10617 @MSindex __oline__
10618 This is not technically a macro, but a feature of Autom4te.  The
10619 sequence @code{__oline__} can be used similarly to the other m4sugar
10620 location macros, but rather than expanding to the location of the input
10621 file, it is translated to the line number where it appears in the output
10622 file after all other M4 expansions.
10623 @end defmac
10625 @defmac dnl
10626 @MSindex dnl
10627 This macro kept its original name: no @code{m4_dnl} is defined.
10628 @end defmac
10630 @defmac m4_bpatsubst (@var{string}, @var{regexp}, @ovar{replacement})
10631 @msindex{bpatsubst}
10632 This macro corresponds to @code{patsubst}.  The name @code{m4_patsubst}
10633 is kept for future versions of M4sugar, once @acronym{GNU} M4 2.0 is
10634 released and supports extended regular expression syntax.
10635 @end defmac
10637 @defmac m4_bregexp (@var{string}, @var{regexp}, @ovar{replacement})
10638 @msindex{bregexp}
10639 This macro corresponds to @code{regexp}.  The name @code{m4_regexp}
10640 is kept for future versions of M4sugar, once @acronym{GNU} M4 2.0 is
10641 released and supports extended regular expression syntax.
10642 @end defmac
10644 @defmac m4_copy (@var{source}, @var{dest})
10645 @defmacx m4_copy_force (@var{source}, @var{dest})
10646 @defmacx m4_rename (@var{source}, @var{dest})
10647 @defmacx m4_rename_force (@var{source}, @var{dest})
10648 @msindex{copy}
10649 @msindex{copy_force}
10650 @msindex{rename}
10651 @msindex{rename_force}
10652 These macros aren't directly builtins, but are closely related to
10653 @code{m4_pushdef} and @code{m4_defn}.  @code{m4_copy} and
10654 @code{m4_rename} ensure that @var{dest} is undefined, while
10655 @code{m4_copy_force} and @code{m4_rename_force} overwrite any existing
10656 definition.  All four macros then proceed to copy the entire pushdef
10657 stack of definitions of @var{source} over to @var{dest}.  @code{m4_copy}
10658 and @code{m4_copy_force} preserve the source (including in the special
10659 case where @var{source} is undefined), while @code{m4_rename} and
10660 @code{m4_rename_force} undefine the original macro name (making it an
10661 error to rename an undefined @var{source}).
10663 Note that attempting to invoke a renamed macro might not work, since the
10664 macro may have a dependence on helper macros accessed via composition of
10665 @samp{$0} but that were not also renamed; likewise, other macros may
10666 have a hard-coded dependence on @var{source} and could break if
10667 @var{source} has been deleted.  On the other hand, it is always safe to
10668 rename a macro to temporarily move it out of the way, then rename it
10669 back later to restore original semantics.
10670 @end defmac
10672 @defmac m4_defn (@var{macro}@dots{})
10673 @msindex{defn}
10674 This macro fails if @var{macro} is not defined, even when using older
10675 versions of M4 that did not warn.  See @code{m4_undefine}.
10676 Unfortunately, in order to support these older versions of M4, there are
10677 some situations involving unbalanced quotes where concatenating multiple
10678 macros together will work in newer M4 but not in m4sugar; use
10679 quadrigraphs to work around this.
10680 @end defmac
10682 @defmac m4_divert (@var{diversion})
10683 @msindex{divert}
10684 M4sugar relies heavily on diversions, so rather than behaving as a
10685 primitive, @code{m4_divert} behaves like:
10686 @example
10687 m4_divert_pop()m4_divert_push([@var{diversion}])
10688 @end example
10689 @noindent
10690 @xref{Diversion support}, for more details about the use of the
10691 diversion stack.
10692 @end defmac
10694 @defmac m4_dumpdef (@var{name}@dots{})
10695 @defmacx m4_dumpdefs (@var{name}@dots{})
10696 @msindex{dumpdef}
10697 @msindex{dumpdefs}
10698 @code{m4_dumpdef} is like the M4 builtin, except that this version
10699 requires at least one argument, output always goes to standard error
10700 rather than the current debug file, no sorting is done on multiple
10701 arguments, and an error is issued if any
10702 @var{name} is undefined.  @code{m4_dumpdefs} is a convenience macro that
10703 calls @code{m4_dumpdef} for all of the
10704 @code{m4_pushdef} stack of definitions, starting with the current, and
10705 silently does nothing if @var{name} is undefined.
10707 Unfortunately, due to a limitation in M4 1.4.x, any macro defined as a
10708 builtin is output as the empty string.  This behavior is rectified by
10709 using M4 1.6 or newer.  However, this behavior difference means that
10710 @code{m4_dumpdef} should only be used while developing m4sugar macros,
10711 and never in the final published form of a macro.
10712 @end defmac
10714 @defmac m4_esyscmd_s (@var{command})
10715 @msindex{esyscmd_s}
10716 Like @code{m4_esyscmd}, this macro expands to the result of running
10717 @var{command} in a shell.  The difference is that any trailing newlines
10718 are removed, so that the output behaves more like shell command
10719 substitution.
10720 @end defmac
10722 @defmac m4_exit (@var{exit-status})
10723 @msindex{exit}
10724 This macro corresponds to @code{m4exit}.
10725 @end defmac
10727 @defmac m4_if (@var{comment})
10728 @defmacx m4_if (@var{string-1}, @var{string-2}, @var{equal}, @ovar{not-equal})
10729 @defmacx m4_if (@var{string-1}, @var{string-2}, @var{equal-1}, @
10730   @var{string-3}, @var{string-4}, @var{equal-2}, @dots{}, @ovar{not-equal})
10731 @msindex{if}
10732 This macro corresponds to @code{ifelse}.  @var{string-1} and
10733 @var{string-2} are compared literally, so usually one of the two
10734 arguments is passed unquoted.  @xref{Conditional constructs}, for more
10735 conditional idioms.
10736 @end defmac
10738 @defmac m4_include (@var{file})
10739 @defmacx m4_sinclude (@var{file})
10740 @msindex{include}
10741 @msindex{sinclude}
10742 Like the M4 builtins, but warn against multiple inclusions of @var{file}.
10743 @end defmac
10745 @defmac m4_mkstemp (@var{template})
10746 @defmacx m4_maketemp (@var{template})
10747 @msindex{maketemp}
10748 @msindex{mkstemp}
10749 Posix requires @code{maketemp} to replace the trailing @samp{X}
10750 characters in @var{template} with the process id, without regards to the
10751 existence of a file by that name, but this a security hole.  When this
10752 was pointed out to the Posix folks, they agreed to invent a new macro
10753 @code{mkstemp} that always creates a uniquely named file, but not all
10754 versions of @acronym{GNU} M4 support the new macro.  In M4sugar,
10755 @code{m4_maketemp} and @code{m4_mkstemp} are synonyms for each other,
10756 and both have the secure semantics regardless of which macro the
10757 underlying M4 provides.
10758 @end defmac
10760 @defmac m4_popdef (@var{macro}@dots{})
10761 @msindex{popdef}
10762 This macro fails if @var{macro} is not defined, even when using older
10763 versions of M4 that did not warn.  See @code{m4_undefine}.
10764 @end defmac
10766 @defmac m4_undefine (@var{macro}@dots{})
10767 @msindex{undefine}
10768 This macro fails if @var{macro} is not defined, even when using older
10769 versions of M4 that did not warn.  Use
10771 @example
10772 m4_ifdef([@var{macro}], [m4_undefine([@var{macro}])])
10773 @end example
10775 @noindent
10776 if you are not sure whether @var{macro} is defined.
10777 @end defmac
10779 @defmac m4_undivert (@var{diversion}@dots{})
10780 @msindex{undivert}
10781 Unlike the M4 builtin, at least one @var{diversion} must be specified.
10782 Also, since the M4sugar diversion stack prefers named
10783 diversions, the use of @code{m4_undivert} to include files is risky.
10784 @xref{Diversion support}, for more details about the use of the
10785 diversion stack.
10786 @end defmac
10788 @defmac m4_wrap (@var{text})
10789 @defmacx m4_wrap_lifo (@var{text})
10790 @msindex{wrap}
10791 @msindex{wrap_lifo}
10792 These macros correspond to @code{m4wrap}.  Posix requires arguments of
10793 multiple wrap calls to be reprocessed at @acronym{EOF} in the same order
10794 as the original calls (first-in, first-out).  @acronym{GNU} M4 versions
10795 through 1.4.10, however, reprocess them in reverse order (last-in,
10796 first-out).  Both orders are useful, therefore, you can rely on
10797 @code{m4_wrap} to provide FIFO semantics and @code{m4_wrap_lifo} for
10798 LIFO semantics, regardless of the underlying @acronym{GNU} M4 version.
10800 Unlike the @acronym{GNU} M4 builtin, these macros only recognize one
10801 argument, and avoid token pasting between consecutive invocations.  On
10802 the other hand, nested calls to @code{m4_wrap} from within wrapped text
10803 work just as in the builtin.
10804 @end defmac
10807 @node Diagnostic Macros
10808 @subsection Diagnostic messages from M4sugar
10809 @cindex Messages, from @command{M4sugar}
10811 When macros statically diagnose abnormal situations, benign or fatal,
10812 they should report them using these macros.  For issuing dynamic issues,
10813 i.e., when @command{configure} is run, see @ref{Printing Messages}.
10815 @defmac m4_assert (@var{expression}, @dvar{exit-status, 1})
10816 @msindex{assert}
10817 Assert that the arithmetic @var{expression} evaluates to non-zero.
10818 Otherwise, issue a fatal error, and exit @command{autom4te} with
10819 @var{exit-status}.
10820 @end defmac
10822 @defmac m4_errprintn (@var{message})
10823 @msindex{errprintn}
10824 Similar to the builtin @code{m4_errprint}, except that a newline is
10825 guaranteed after @var{message}.
10826 @end defmac
10828 @anchor{m4_fatal}
10829 @defmac m4_fatal (@var{message})
10830 @msindex{fatal}
10831 Report a severe error @var{message} prefixed with the current location,
10832 and have @command{autom4te} die.
10833 @end defmac
10835 @defmac m4_location
10836 @msindex{location}
10837 Useful as a prefix in a message line.  Short for:
10838 @example
10839 __file__:__line__
10840 @end example
10841 @end defmac
10843 @anchor{m4_warn}
10844 @defmac m4_warn (@var{category}, @var{message})
10845 @msindex{warn}
10846 Report @var{message} as a warning (or as an error if requested by the
10847 user) if warnings of the @var{category} are turned on.  If the message
10848 is emitted, it is prefixed with the current location, and followed by a
10849 call trace of all macros defined via @code{AC_DEFUN} used to get to the
10850 current expansion.  You are encouraged to use standard categories, which
10851 currently include:
10853 @table @samp
10854 @item all
10855 messages that don't fall into one of the following categories.  Use of an
10856 empty @var{category} is equivalent.
10858 @item cross
10859 related to cross compilation issues.
10861 @item obsolete
10862 use of an obsolete construct.
10864 @item syntax
10865 dubious syntactic constructs, incorrectly ordered macro calls.
10866 @end table
10867 @end defmac
10870 @node Diversion support
10871 @subsection Diversion support
10873 M4sugar makes heavy use of diversions, because it is often the case that
10874 text that must appear early in the output is not discovered until late
10875 in the input.  Additionally, some of the topological sorting algorithms
10876 used in resolving macro dependencies use diversions.  However, most
10877 macros should not need to change diversions directly, but rather rely on
10878 higher-level M4sugar macros to manage diversions transparently.
10880 In the rare case that it is necessary to write a macro that explicitly
10881 outputs text to a different diversion, it is important to be aware of an
10882 M4 limitation regarding diversions: text only goes to a diversion if it
10883 is not part of argument collection.  Therefore, any macro that changes
10884 the current diversion cannot be used as an unquoted argument to another
10885 macro, but must be expanded at the top level.  The macro
10886 @code{m4_expand} will diagnose any attempt to change diversions, since
10887 it is generally useful only as an argument to another macro.  The
10888 following example shows what happens when diversion manipulation is
10889 attempted within macro arguments:
10891 @example
10892 m4_do([normal text]
10893 m4_divert_push([KILL])unwanted[]m4_divert_pop([KILL])
10894 [m4_divert_push([KILL])discarded[]m4_divert_pop([KILL])])dnl
10895 @result{}normal text
10896 @result{}unwanted
10897 @end example
10899 @noindent
10900 Notice that the unquoted text @code{unwanted} is output, even though it
10901 was processed while the current diversion was @code{KILL}, because it
10902 was collected as part of the argument to @code{m4_do}.  However, the
10903 text @code{discarded} disappeared as desired, because the diversion
10904 changes were single-quoted, and were not expanded until the top-level
10905 rescan of the output of @code{m4_do}.
10907 To make diversion management easier, M4sugar uses the concept of named
10908 diversions.  Rather than using diversion numbers directly, it is nicer
10909 to associate a name with each diversion; the diversion number associated
10910 with a particular diversion name is an implementation detail, so you
10911 should only use diversion names.  In general, you should not output text
10912 to a named diversion until after calling the appropriate initialization
10913 routine for your language (@code{m4_init}, @code{AS_INIT},
10914 @code{AT_INIT}, @dots{}), although there are some exceptions documented
10915 below.
10917 M4sugar defines two named diversions.
10918 @table @code
10919 @item KILL
10920 Text written to this diversion is discarded.  This is the default
10921 diversion once M4sugar is initialized.
10922 @item GROW
10923 This diversion is used behind the scenes by topological sorting macros,
10924 such as @code{AC_REQUIRE}.
10925 @end table
10927 M4sh adds several more named diversions.
10928 @table @code
10929 @item BINSH
10930 This diversion is reserved for the @samp{#!} interpreter line.
10931 @item HEADER-REVISION
10932 This diversion holds text from @code{AC_REVISION}.
10933 @item HEADER-COMMENT
10934 This diversion holds comments about the purpose of a file.
10935 @item HEADER-COPYRIGHT
10936 This diversion is managed by @code{AC_COPYRIGHT}.
10937 @item M4SH-SANITIZE
10938 This diversion contains M4sh sanitization code, used to ensure M4sh is
10939 executing in a reasonable shell environment.
10940 @item M4SH-INIT
10941 This diversion contains M4sh initialization code, initializing variables
10942 that are required by other M4sh macros.
10943 @item BODY
10944 This diversion contains the body of the shell code, and is the default
10945 diversion once M4sh is initialized.
10946 @end table
10948 Autotest inherits diversions from M4sh, and changes the default
10949 diversion from @code{BODY} back to @code{KILL}.  It also adds several
10950 more named diversions, with the following subset designed for developer
10951 use.
10952 @table @code
10953 @item PREPARE_TESTS
10954 This diversion contains initialization sequences which are executed
10955 after @file{atconfig} and @file{atlocal}, and after all command line
10956 arguments have been parsed, but prior to running any tests.  It can be
10957 used to set up state that is required across all tests.  This diversion
10958 will work even before @code{AT_INIT}.
10959 @end table
10961 For now, the named diversions of Autoconf and Autoheader, and the
10962 remaining diversions of Autotest, are not documented.  In other words,
10963 intentionally outputting text into an undocumented diversion is subject
10964 to breakage in a future release of Autoconf.
10966 @defmac m4_cleardivert (@var{diversion}@dots{})
10967 @msindex{cleardivert}
10968 Permanently discard any text that has been diverted into
10969 @var{diversion}.
10970 @end defmac
10972 @defmac m4_divert_once (@var{diversion}, @ovar{content})
10973 @msindex{divert_once}
10974 Similar to @code{m4_divert_text}, except that @var{content} is only
10975 output to @var{diversion} if this is the first time that
10976 @code{m4_divert_once} has been called with its particular arguments.
10977 @end defmac
10979 @defmac m4_divert_pop (@ovar{diversion})
10980 @msindex{divert_pop}
10981 If provided, check that the current diversion is indeed @var{diversion}.
10982 Then change to the diversion located earlier on the stack, giving an
10983 error if an attempt is made to pop beyond the initial m4sugar diversion
10984 of @code{KILL}.
10985 @end defmac
10987 @defmac m4_divert_push (@var{diversion})
10988 @msindex{divert_push}
10989 Remember the former diversion on the diversion stack, and output
10990 subsequent text into @var{diversion}.  M4sugar maintains a diversion
10991 stack, and issues an error if there is not a matching pop for every
10992 push.
10993 @end defmac
10995 @defmac m4_divert_text (@var{diversion}, @ovar{content})
10996 @msindex{divert_text}
10997 Output @var{content} and a newline into @var{diversion}, without
10998 affecting the current diversion.  Shorthand for:
10999 @example
11000 m4_divert_push([@var{diversion}])@var{content}
11001 m4_divert_pop([@var{diversion}])dnl
11002 @end example
11003 @end defmac
11005 @defmac m4_init
11006 @msindex{init}
11007 Initialize the M4sugar environment, setting up the default named
11008 diversion to be @code{KILL}.
11009 @end defmac
11011 @node Conditional constructs
11012 @subsection Conditional constructs
11014 The following macros provide additional conditional constructs as
11015 convenience wrappers around @code{m4_if}.
11017 @defmac m4_bmatch (@var{string}, @var{regex-1}, @var{value-1}, @
11018   @ovar{regex-2}, @ovar{value-2}, @dots{}, @ovar{default})
11019 @msindex{bmatch}
11020 The string @var{string} is repeatedly compared against a series of
11021 @var{regex} arguments; if a match is found, the expansion is the
11022 corresponding @var{value}, otherwise, the macro moves on to the next
11023 @var{regex}.  If no @var{regex} match, then the result is the optional
11024 @var{default}, or nothing.
11025 @end defmac
11027 @defmac m4_bpatsubsts (@var{string}, @var{regex-1}, @var{subst-1}, @
11028   @ovar{regex-2}, @ovar{subst-2}, @dots{})
11029 @msindex{bpatsubsts}
11030 The string @var{string} is altered by @var{regex-1} and @var{subst-1},
11031 as if by:
11032 @example
11033 m4_bpatsubst([[@var{string}]], [@var{regex}], [@var{subst}])
11034 @end example
11036 @noindent
11037 The result of the substitution is then passed through the next set of
11038 @var{regex} and @var{subst}, and so forth.  An empty @var{subst} implies
11039 deletion of any matched portions in the current string.  Note that this
11040 macro over-quotes @var{string}; this behavior is intentional, so that
11041 the result of each step of the recursion remains as a quoted string.
11042 However, it means that anchors (@samp{^} and @samp{$} in the @var{regex}
11043 will line up with the extra quotations, and not the characters of the
11044 original string.  The overquoting is removed after the final
11045 substitution.
11046 @end defmac
11048 @defmac m4_case (@var{string}, @var{value-1}, @var{if-value-1}, @
11049   @ovar{value-2}, @ovar{if-value-2}, @dots{}, @ovar{default})
11050 @msindex{case}
11051 Test @var{string} against multiple @var{value} possibilities, resulting
11052 in the first @var{if-value} for a match, or in the optional
11053 @var{default}.  This is shorthand for:
11054 @example
11055 m4_if([@var{string}], [@var{value-1}], [@var{if-value-1}],
11056       [@var{string}], [@var{value-2}], [@var{if-value-2}], @dots{},
11057       [@var{default}])
11058 @end example
11059 @end defmac
11061 @defmac m4_cond (@var{test-1}, @var{value-1}, @var{if-value-1}, @
11062   @ovar{test-2}, @ovar{value-2}, @ovar{if-value-2}, @dots{}, @ovar{default})
11063 @msindex{cond}
11064 This macro was introduced in Autoconf 2.62.  Similar to @code{m4_if},
11065 except that each @var{test} is expanded only when it is encountered.
11066 This is useful for short-circuiting expensive tests; while @code{m4_if}
11067 requires all its strings to be expanded up front before doing
11068 comparisons, @code{m4_cond} only expands a @var{test} when all earlier
11069 tests have failed.
11071 For an example, these two sequences give the same result, but in the
11072 case where @samp{$1} does not contain a backslash, the @code{m4_cond}
11073 version only expands @code{m4_index} once, instead of five times, for
11074 faster computation if this is a common case for @samp{$1}.  Notice that
11075 every third argument is unquoted for @code{m4_if}, and quoted for
11076 @code{m4_cond}:
11078 @example
11079 m4_if(m4_index([$1], [\]), [-1], [$2],
11080       m4_eval(m4_index([$1], [\\]) >= 0), [1], [$2],
11081       m4_eval(m4_index([$1], [\$]) >= 0), [1], [$2],
11082       m4_eval(m4_index([$1], [\`]) >= 0), [1], [$3],
11083       m4_eval(m4_index([$1], [\"]) >= 0), [1], [$3],
11084       [$2])
11085 m4_cond([m4_index([$1], [\])], [-1], [$2],
11086         [m4_eval(m4_index([$1], [\\]) >= 0)], [1], [$2],
11087         [m4_eval(m4_index([$1], [\$]) >= 0)], [1], [$2],
11088         [m4_eval(m4_index([$1], [\`]) >= 0)], [1], [$3],
11089         [m4_eval(m4_index([$1], [\"]) >= 0)], [1], [$3],
11090         [$2])
11091 @end example
11092 @end defmac
11094 @defmac m4_default (@var{expr-1}, @var{expr-2})
11095 @defmacx m4_default_quoted (@var{expr-1}, @var{expr-2})
11096 @defmacx m4_default_nblank (@var{expr-1}, @ovar{expr-2})
11097 @defmacx m4_default_nblank_quoted (@var{expr-1}, @ovar{expr-2})
11098 @msindex{default}
11099 @msindex{default_quoted}
11100 @msindex{default_nblank}
11101 @msindex{default_nblank_quoted}
11102 If @var{expr-1} contains text, use it.  Otherwise, select @var{expr-2}.
11103 @code{m4_default} expands the result, while @code{m4_default_quoted}
11104 does not.  Useful for providing a fixed default if the expression that
11105 results in @var{expr-1} would otherwise be empty.  The difference
11106 between @code{m4_default} and @code{m4_default_nblank} is whether an
11107 argument consisting of just blanks (space, tab, newline) is
11108 significant.  When using the expanding versions, note that an argument
11109 may contain text but still expand to an empty string.
11111 @example
11112 m4_define([active], [ACTIVE])dnl
11113 m4_define([empty], [])dnl
11114 m4_define([demo1], [m4_default([$1], [$2])])dnl
11115 m4_define([demo2], [m4_default_quoted([$1], [$2])])dnl
11116 m4_define([demo3], [m4_default_nblank([$1], [$2])])dnl
11117 m4_define([demo4], [m4_default_nblank_quoted([$1], [$2])])dnl
11118 demo1([active], [default])
11119 @result{}ACTIVE
11120 demo1([], [active])
11121 @result{}ACTIVE
11122 demo1([empty], [text])
11123 @result{}
11124 -demo1([ ], [active])-
11125 @result{}- -
11126 demo2([active], [default])
11127 @result{}active
11128 demo2([], [active])
11129 @result{}active
11130 demo2([empty], [text])
11131 @result{}empty
11132 -demo2([ ], [active])-
11133 @result{}- -
11134 demo3([active], [default])
11135 @result{}ACTIVE
11136 demo3([], [active])
11137 @result{}ACTIVE
11138 demo3([empty], [text])
11139 @result{}
11140 -demo3([ ], [active])-
11141 @result{}-ACTIVE-
11142 demo4([active], [default])
11143 @result{}active
11144 demo4([], [active])
11145 @result{}active
11146 demo4([empty], [text])
11147 @result{}empty
11148 -demo4([ ], [active])-
11149 @result{}-active-
11150 @end example
11151 @end defmac
11153 @defmac m4_ifblank (@var{cond}, @ovar{if-blank}, @ovar{if-text})
11154 @defmacx m4_ifnblank (@var{cond}, @ovar{if-text}, @ovar{if-blank})
11155 @msindex{ifblank}
11156 @msindex{ifnblank}
11157 If @var{cond} is empty or consists only of blanks (space, tab, newline),
11158 then expand @var{if-blank}; otherwise, expand @var{if-text}.  Two
11159 variants exist, in order to make it easier to select the correct logical
11160 sense when using only two parameters.  Note that this is more efficient
11161 than the equivalent behavior of:
11162 @example
11163 m4_ifval(m4_normalize([@var{cond}]), @var{if-text}, @var{if-cond})
11164 @end example
11165 @end defmac
11167 @defmac m4_ifndef (@var{macro}, @var{if-not-defined}, @ovar{if-defined})
11168 @msindex{ifndef}
11169 This is shorthand for:
11170 @example
11171 m4_ifdef([@var{macro}], [@var{if-defined}], [@var{if-not-defined}])
11172 @end example
11173 @end defmac
11175 @defmac m4_ifset (@var{macro}, @ovar{if-true}, @ovar{if-false})
11176 @msindex{ifset}
11177 If @var{macro} is undefined, or is defined as the empty string, expand
11178 to @var{if-false}.  Otherwise, expands to @var{if-true}.  Similar to:
11179 @example
11180 m4_ifval(m4_defn([@var{macro}]), [@var{if-true}], [@var{if-false}])
11181 @end example
11182 @noindent
11183 except that it is not an error if @var{macro} is undefined.
11184 @end defmac
11186 @defmac m4_ifval (@var{cond}, @ovar{if-true}, @ovar{if-false})
11187 @msindex{ifval}
11188 Expands to @var{if-true} if @var{cond} is not empty, otherwise to
11189 @var{if-false}.  This is shorthand for:
11190 @example
11191 m4_if([@var{cond}], [], [@var{if-true}], [@var{if-false}])
11192 @end example
11193 @end defmac
11195 @defmac m4_ifvaln (@var{cond}, @ovar{if-true}, @ovar{if-false})
11196 @msindex{ifvaln}
11197 Similar to @code{m4_ifval}, except guarantee that a newline is present
11198 after any non-empty expansion.  Often followed by @code{dnl}.
11199 @end defmac
11201 @defmac m4_n (@var{text})
11202 @msindex{n}
11203 Expand to @var{text}, and add a newline if @var{text} is not empty.
11204 Often followed by @code{dnl}.
11205 @end defmac
11208 @node Looping constructs
11209 @subsection Looping constructs
11211 The following macros are useful in implementing recursive algorithms in
11212 M4, including loop operations.  An M4 list is formed by quoting a list
11213 of quoted elements; generally the lists are comma-separated, although
11214 @code{m4_foreach_w} is whitespace-separated.  For example, the list
11215 @samp{[[a], [b,c]]} contains two elements: @samp{[a]} and @samp{[b,c]}.
11216 It is common to see lists with unquoted elements when those elements are
11217 not likely to be macro names, as in @samp{[fputc_unlocked,
11218 fgetc_unlocked]}.
11220 Although not generally recommended, it is possible for quoted lists to
11221 have side effects; all side effects are expanded only once, and prior to
11222 visiting any list element.  On the other hand, the fact that unquoted
11223 macros are expanded exactly once means that macros without side effects
11224 can be used to generate lists.  For example,
11226 @example
11227 m4_foreach([i], [[1], [2], [3]m4_errprintn([hi])], [i])
11228 @error{}hi
11229 @result{}123
11230 m4_define([list], [[1], [2], [3]])
11231 @result{}
11232 m4_foreach([i], [list], [i])
11233 @result{}123
11234 @end example
11236 @defmac m4_argn (@var{n}, @ovar{arg}@dots{})
11237 @msindex{argn}
11238 Extracts argument @var{n} (larger than 0) from the remaining arguments.
11239 If there are too few arguments, the empty string is used.  For any
11240 @var{n} besides 1, this is more efficient than the similar
11241 @samp{m4_car(m4_shiftn([@var{n}], [], [@var{arg}@dots{}]))}.
11242 @end defmac
11244 @defmac m4_car (@var{arg}@dots{})
11245 @msindex{car}
11246 Expands to the quoted first @var{arg}.  Can be used with @code{m4_cdr}
11247 to recursively iterate
11248 through a list.  Generally, when using quoted lists of quoted elements,
11249 @code{m4_car} should be called without any extra quotes.
11250 @end defmac
11252 @defmac m4_cdr (@var{arg}@dots{})
11253 @msindex{cdr}
11254 Expands to a quoted list of all but the first @var{arg}, or the empty
11255 string if there was only one argument.  Generally, when using quoted
11256 lists of quoted elements, @code{m4_cdr} should be called without any
11257 extra quotes.
11259 For example, this is a simple implementation of @code{m4_map}; note how
11260 each iteration checks for the end of recursion, then merely applies the
11261 first argument to the first element of the list, then repeats with the
11262 rest of the list.  (The actual implementation in M4sugar is a bit more
11263 involved, to gain some speed and share code with @code{m4_map_sep}, and
11264 also to avoid expanding side effects in @samp{$2} twice).
11265 @example
11266 m4_define([m4_map], [m4_ifval([$2],
11267   [m4_apply([$1], m4_car($2))[]$0([$1], m4_cdr($2))])])dnl
11268 m4_map([ m4_eval], [[[1]], [[1+1]], [[10],[16]]])
11269 @result{} 1 2 a
11270 @end example
11271 @end defmac
11273 @defmac m4_for (@var{var}, @var{first}, @var{last}, @ovar{step}, @
11274   @var{expression})
11275 @msindex{for}
11276 Loop over the numeric values between @var{first} and @var{last}
11277 including bounds by increments of @var{step}.  For each iteration,
11278 expand @var{expression} with the numeric value assigned to @var{var}.
11279 If @var{step} is omitted, it defaults to @samp{1} or @samp{-1} depending
11280 on the order of the limits.  If given, @var{step} has to match this
11281 order.  The number of iterations is determined independently from
11282 definition of @var{var}; iteration cannot be short-circuited or
11283 lengthened by modifying @var{var} from within @var{expression}.
11284 @end defmac
11286 @defmac m4_foreach (@var{var}, @var{list}, @var{expression})
11287 @msindex{foreach}
11288 Loop over the comma-separated M4 list @var{list}, assigning each value
11289 to @var{var}, and expand @var{expression}.  The following example
11290 outputs two lines:
11292 @example
11293 m4_foreach([myvar], [[foo], [bar, baz]],
11294            [echo myvar
11295 ])dnl
11296 @result{}echo foo
11297 @result{}echo bar, baz
11298 @end example
11300 Note that for some forms of @var{expression}, it may be faster to use
11301 @code{m4_map_args}.
11302 @end defmac
11304 @anchor{m4_foreach_w}
11305 @defmac m4_foreach_w (@var{var}, @var{list}, @var{expression})
11306 @msindex{foreach_w}
11307 Loop over the white-space-separated list @var{list}, assigning each value
11308 to @var{var}, and expand @var{expression}.  If @var{var} is only
11309 referenced once in @var{expression}, it is more efficient to use
11310 @code{m4_map_args_w}.
11312 The deprecated macro @code{AC_FOREACH} is an alias of
11313 @code{m4_foreach_w}.
11314 @end defmac
11316 @defmac m4_map (@var{macro}, @var{list})
11317 @defmacx m4_mapall (@var{macro}, @var{list})
11318 @defmacx m4_map_sep (@var{macro}, @var{separator}, @var{list})
11319 @defmacx m4_mapall_sep (@var{macro}, @var{separator}, @var{list})
11320 @msindex{map}
11321 @msindex{mapall}
11322 @msindex{map_sep}
11323 @msindex{mapall_sep}
11324 Loop over the comma separated quoted list of argument descriptions in
11325 @var{list}, and invoke @var{macro} with the arguments.  An argument
11326 description is in turn a comma-separated quoted list of quoted elements,
11327 suitable for @code{m4_apply}.  The macros @code{m4_map} and
11328 @code{m4_map_sep} ignore empty argument descriptions, while
11329 @code{m4_mapall} and @code{m4_mapall_sep} invoke @var{macro} with no
11330 arguments.  The macros @code{m4_map_sep} and @code{m4_mapall_sep}
11331 additionally expand @var{separator} between invocations of @var{macro}.
11333 Note that @var{separator} is expanded, unlike in @code{m4_join}.  When
11334 separating output with commas, this means that the map result can be
11335 used as a series of arguments, by using a single-quoted comma as
11336 @var{separator}, or as a single string, by using a double-quoted comma.
11338 @example
11339 m4_map([m4_count], [])
11340 @result{}
11341 m4_map([ m4_count], [[],
11342                      [[1]],
11343                      [[1], [2]]])
11344 @result{} 1 2
11345 m4_mapall([ m4_count], [[],
11346                         [[1]],
11347                         [[1], [2]]])
11348 @result{} 0 1 2
11349 m4_map_sep([m4_eval], [,], [[[1+2]],
11350                             [[10], [16]]])
11351 @result{}3,a
11352 m4_map_sep([m4_echo], [,], [[[a]], [[b]]])
11353 @result{}a,b
11354 m4_count(m4_map_sep([m4_echo], [,], [[[a]], [[b]]]))
11355 @result{}2
11356 m4_map_sep([m4_echo], [[,]], [[[a]], [[b]]])
11357 @result{}a,b
11358 m4_count(m4_map_sep([m4_echo], [[,]], [[[a]], [[b]]]))
11359 @result{}1
11360 @end example
11361 @end defmac
11363 @defmac m4_map_args (@var{macro}, @var{arg}@dots{})
11364 @msindex{map_args}
11365 Repeatedly invoke @var{macro} with each successive @var{arg} as its only
11366 argument.  In the following example, three solutions are presented with
11367 the same expansion; the solution using @code{m4_map_args} is the most
11368 efficient.
11369 @example
11370 m4_define([active], [ACTIVE])dnl
11371 m4_foreach([var], [[plain], [active]], [ m4_echo(m4_defn([var]))])
11372 @result{} plain active
11373 m4_map([ m4_echo], [[[plain]], [[active]]])
11374 @result{} plain active
11375 m4_map_args([ m4_echo], [plain], [active])
11376 @result{} plain active
11377 @end example
11379 In cases where it is useful to operate on additional parameters besides
11380 the list elements, the macro @code{m4_curry} can be used in @var{macro}
11381 to supply the argument currying necessary to generate the desired
11382 argument list.  In the following example, @code{list_add_n} is more
11383 efficient than @code{list_add_x}.  On the other hand, using
11384 @code{m4_map_args_sep} can be even more efficient.
11386 @example
11387 m4_define([list], [[1], [2], [3]])dnl
11388 m4_define([add], [m4_eval(([$1]) + ([$2]))])dnl
11389 dnl list_add_n(N, ARG...)
11390 dnl Output a list consisting of each ARG added to N
11391 m4_define([list_add_n],
11392 [m4_shift(m4_map_args([,m4_curry([add], [$1])], m4_shift($@@)))])dnl
11393 list_add_n([1], list)
11394 @result{}2,3,4
11395 list_add_n([2], list)
11396 @result{}3,4,5
11397 m4_define([list_add_x],
11398 [m4_shift(m4_foreach([var], m4_dquote(m4_shift($@@)),
11399   [,add([$1],m4_defn([var]))]))])dnl
11400 list_add_x([1], list)
11401 @result{}2,3,4
11402 @end example
11403 @end defmac
11405 @defmac m4_map_args_pair (@var{macro}, @dvar{macro-end, macro}, @
11406   @var{arg}@dots{})
11407 @msindex{map_args_pair}
11408 For every pair of arguments @var{arg}, invoke @var{macro} with two
11409 arguments.  If there is an odd number of arguments, invoke
11410 @var{macro-end}, which defaults to @var{macro}, with the remaining
11411 argument.
11413 @example
11414 m4_map_args_pair([, m4_reverse], [], [1], [2], [3])
11415 @result{}, 2, 1, 3
11416 m4_map_args_pair([, m4_reverse], [, m4_dquote], [1], [2], [3])
11417 @result{}, 2, 1, [3]
11418 m4_map_args_pair([, m4_reverse], [, m4_dquote], [1], [2], [3], [4])
11419 @result{}, 2, 1, 4, 3
11420 @end example
11421 @end defmac
11423 @defmac m4_map_args_sep (@ovar{pre}, @ovar{post}, @ovar{sep}, @var{arg}@dots{})
11424 @msindex{map_args_sep}
11425 Expand the sequence @code{@var{pre}[@var{arg}]@var{post}} for each
11426 argument, additionally expanding @var{sep} between arguments.  One
11427 common use of this macro is constructing a macro call, where the opening
11428 and closing parentheses are split between @var{pre} and @var{post}; in
11429 particular, @code{m4_map_args([@var{macro}], [@var{arg}])} is equivalent
11430 to @code{m4_map_args_sep([@var{macro}(], [)], [], [@var{arg}])}.  This
11431 macro provides the most efficient means for iterating over an arbitrary
11432 list of arguments, particularly when repeatedly constructing a macro
11433 call with more arguments than @var{arg}.
11434 @end defmac
11436 @defmac m4_map_args_w (@var{string}, @ovar{pre}, @ovar{post}, @ovar{sep})
11437 @msindex{map_args_w}
11438 Expand the sequence @code{@var{pre}[word]@var{post}} for each word in
11439 the whitespace-separated @var{string}, additionally expanding @var{sep}
11440 between words.  This macro provides the most efficient means for
11441 iterating over a whitespace-separated string.  In particular,
11442 @code{m4_map_args_w([@var{string}], [@var{action}(], [)])} is more
11443 efficient than @code{m4_foreach_w([var], [@var{string}],
11444 [@var{action}(m4_defn([var]))])}.
11445 @end defmac
11447 @defmac m4_shiftn (@var{count}, @dots{})
11448 @defmacx m4_shift2 (@dots{})
11449 @defmacx m4_shift3 (@dots{})
11450 @msindex{shift2}
11451 @msindex{shift3}
11452 @msindex{shiftn}
11453 @code{m4_shiftn} performs @var{count} iterations of @code{m4_shift},
11454 along with validation that enough arguments were passed in to match the
11455 shift count, and that the count is positive.  @code{m4_shift2} and
11456 @code{m4_shift3} are specializations
11457 of @code{m4_shiftn}, introduced in Autoconf 2.62, and are more efficient
11458 for two and three shifts, respectively.
11459 @end defmac
11461 @defmac m4_stack_foreach (@var{macro}, @var{action})
11462 @defmacx m4_stack_foreach_lifo (@var{macro}, @var{action})
11463 @msindex{stack_foreach}
11464 @msindex{stack_foreach_lifo}
11465 For each of the @code{m4_pushdef} definitions of @var{macro}, expand
11466 @var{action} with the single argument of a definition of @var{macro}.
11467 @code{m4_stack_foreach} starts with the oldest definition, while
11468 @code{m4_stack_foreach_lifo} starts with the current definition.
11469 @var{action} should not push or pop definitions of @var{macro}, nor is
11470 there any guarantee that the current definition of @var{macro} matches
11471 the argument that was passed to @var{action}.  The macro @code{m4_curry}
11472 can be used if @var{action} needs more than one argument, although in
11473 that case it is more efficient to use @var{m4_stack_foreach_sep}.
11475 Due to technical limitations, there are a few low-level m4sugar
11476 functions, such as @code{m4_pushdef}, that cannot be used as the
11477 @var{macro} argument.
11479 @example
11480 m4_pushdef([a], [1])m4_pushdef([a], [2])dnl
11481 m4_stack_foreach([a], [ m4_incr])
11482 @result{} 2 3
11483 m4_stack_foreach_lifo([a], [ m4_curry([m4_substr], [abcd])])
11484 @result{} cd bcd
11485 @end example
11486 @end defmac
11488 @defmac m4_stack_foreach_sep (@var{macro}, @ovar{pre}, @ovar{post}, @ovar{sep})
11489 @defmacx m4_stack_foreach_sep_lifo (@var{macro}, @ovar{pre}, @ovar{post}, @
11490   @ovar{sep})
11491 @msindex{stack_foreach_sep}
11492 @msindex{stack_foreach_sep_lifo}
11493 Expand the sequence @code{@var{pre}[definition]@var{post}} for each
11494 @code{m4_pushdef} definition of @var{macro}, additionally expanding
11495 @var{sep} between definitions.  @code{m4_stack_foreach_sep} visits the
11496 oldest definition first, while @code{m4_stack_foreach_sep_lifo} visits
11497 the current definition first.  This macro provides the most efficient
11498 means for iterating over a pushdef stack.  In particular,
11499 @code{m4_stack_foreach([@var{macro}], [@var{action}])} is short for
11500 @code{m4_stack_foreach_sep([@var{macro}], [@var{action}(], [)])}.
11501 @end defmac
11503 @node Evaluation Macros
11504 @subsection Evaluation Macros
11506 The following macros give some control over the order of the evaluation
11507 by adding or removing levels of quotes.
11509 @defmac m4_apply (@var{macro}, @var{list})
11510 @msindex{apply}
11511 Apply the elements of the quoted, comma-separated @var{list} as the
11512 arguments to @var{macro}.  If @var{list} is empty, invoke @var{macro}
11513 without arguments.  Note the difference between @code{m4_indir}, which
11514 expects its first argument to be a macro name but can use names that are
11515 otherwise invalid, and @code{m4_apply}, where @var{macro} can contain
11516 other text, but must end in a valid macro name.
11517 @example
11518 m4_apply([m4_count], [])
11519 @result{}0
11520 m4_apply([m4_count], [[]])
11521 @result{}1
11522 m4_apply([m4_count], [[1], [2]])
11523 @result{}2
11524 m4_apply([m4_join], [[|], [1], [2]])
11525 @result{}1|2
11526 @end example
11527 @end defmac
11529 @defmac m4_count (@var{arg}, @dots{})
11530 @msindex{count}
11531 This macro returns the decimal count of the number of arguments it was
11532 passed.
11533 @end defmac
11535 @defmac m4_curry (@var{macro}, @var{arg}@dots{})
11536 @msindex{curry}
11537 This macro performs argument currying.  The expansion of this macro is
11538 another macro name that expects exactly one argument; that argument is
11539 then appended to the @var{arg} list, and then @var{macro} is expanded
11540 with the resulting argument list.
11542 @example
11543 m4_curry([m4_curry], [m4_reverse], [1])([2])([3])
11544 @result{}3, 2, 1
11545 @end example
11547 Unfortunately, due to a limitation in M4 1.4.x, it is not possible to
11548 pass the definition of a builtin macro as the argument to the output of
11549 @code{m4_curry}; the empty string is used instead of the builtin token.
11550 This behavior is rectified by using M4 1.6 or newer.
11551 @end defmac
11553 @defmac m4_do (@var{arg}, @dots{})
11554 @msindex{do}
11555 This macro loops over its arguments and expands each @var{arg} in
11556 sequence.  Its main use is for readability; it allows the use of
11557 indentation and fewer @code{dnl} to result in the same expansion.  This
11558 macro guarantees that no expansion will be concatenated with subsequent
11559 text; to achieve full concatenation, use @code{m4_unquote(m4_join([],
11560 @var{arg@dots{}}))}.
11562 @example
11563 m4_define([ab],[1])m4_define([bc],[2])m4_define([abc],[3])dnl
11564 m4_do([a],[b])c
11565 @result{}abc
11566 m4_unquote(m4_join([],[a],[b]))c
11567 @result{}3
11568 m4_define([a],[A])m4_define([b],[B])m4_define([c],[C])dnl
11569 m4_define([AB],[4])m4_define([BC],[5])m4_define([ABC],[6])dnl
11570 m4_do([a],[b])c
11571 @result{}ABC
11572 m4_unquote(m4_join([],[a],[b]))c
11573 @result{}3
11574 @end example
11575 @end defmac
11577 @defmac m4_dquote (@var{arg}, @dots{})
11578 @msindex{dquote}
11579 Return the arguments as a quoted list of quoted arguments.
11580 Conveniently, if there is just one @var{arg}, this effectively adds a
11581 level of quoting.
11582 @end defmac
11584 @defmac m4_dquote_elt (@var{arg}, @dots{})
11585 @msindex{dquote_elt}
11586 Return the arguments as a series of double-quoted arguments.  Whereas
11587 @code{m4_dquote} returns a single argument, @code{m4_dquote_elt} returns
11588 as many arguments as it was passed.
11589 @end defmac
11591 @defmac m4_echo (@var{arg}, @dots{})
11592 @msindex{echo}
11593 Return the arguments, with the same level of quoting.  Other than
11594 discarding whitespace after unquoted commas, this macro is a no-op.
11595 @end defmac
11597 @defmac m4_expand (@var{arg})
11598 @msindex{expand}
11599 Return the expansion of @var{arg} as a quoted string.  Whereas
11600 @code{m4_quote} is designed to collect expanded text into a single
11601 argument, @code{m4_expand} is designed to perform one level of expansion
11602 on quoted text.  One distinction is in the treatment of whitespace
11603 following a comma in the original @var{arg}.  Any time multiple
11604 arguments are collected into one with @code{m4_quote}, the M4 argument
11605 collection rules discard the whitespace.  However, with @code{m4_expand},
11606 whitespace is preserved, even after the expansion of macros contained in
11607 @var{arg}.  Additionally, @code{m4_expand} is able to expand text that
11608 would involve an unterminated comment, whereas expanding that same text
11609 as the argument to @code{m4_quote} runs into difficulty in finding the
11610 end of the argument.  Since manipulating diversions during argument
11611 collection is inherently unsafe, @code{m4_expand} issues an error if
11612 @var{arg} attempts to change the current diversion (@pxref{Diversion
11613 support}).
11615 @example
11616 m4_define([active], [ACT, IVE])dnl
11617 m4_define([active2], [[ACT, IVE]])dnl
11618 m4_quote(active, active)
11619 @result{}ACT,IVE,ACT,IVE
11620 m4_expand([active, active])
11621 @result{}ACT, IVE, ACT, IVE
11622 m4_quote(active2, active2)
11623 @result{}ACT, IVE,ACT, IVE
11624 m4_expand([active2, active2])
11625 @result{}ACT, IVE, ACT, IVE
11626 m4_expand([# m4_echo])
11627 @result{}# m4_echo
11628 m4_quote(# m4_echo)
11630 @result{}# m4_echo)
11631 @result{}
11632 @end example
11634 Note that @code{m4_expand} cannot handle an @var{arg} that expands to
11635 literal unbalanced quotes, but that quadrigraphs can be used when
11636 unbalanced output is necessary.  Likewise, unbalanced parentheses should
11637 be supplied with double quoting or a quadrigraph.
11639 @example
11640 m4_define([pattern], [[!@@<:@@]])dnl
11641 m4_define([bar], [BAR])dnl
11642 m4_expand([case $foo in
11643   m4_defn([pattern])@@:@}@@ bar ;;
11644   *[)] blah ;;
11645 esac])
11646 @result{}case $foo in
11647 @result{}  [![]) BAR ;;
11648 @result{}  *) blah ;;
11649 @result{}esac
11650 @end example
11651 @end defmac
11653 @defmac m4_ignore (@dots{})
11654 @msindex{ignore}
11655 This macro was introduced in Autoconf 2.62.  Expands to nothing,
11656 ignoring all of its arguments.  By itself, this isn't very useful.
11657 However, it can be used to conditionally ignore an arbitrary number of
11658 arguments, by deciding which macro name to apply to a list of arguments.
11659 @example
11660 dnl foo outputs a message only if [debug] is defined.
11661 m4_define([foo],
11662 [m4_ifdef([debug],[AC_MSG_NOTICE],[m4_ignore])([debug message])])
11663 @end example
11665 Note that for earlier versions of Autoconf, the macro @code{__gnu__} can
11666 serve the same purpose, although it is less readable.
11667 @end defmac
11669 @defmac m4_make_list (@var{arg}, @dots{})
11670 @msindex{make_list}
11671 This macro exists to aid debugging of M4sugar algorithms.  Its net
11672 effect is similar to @code{m4_dquote}---it produces a quoted list of
11673 quoted arguments, for each @var{arg}.  The difference is that this
11674 version uses a comma-newline separator instead of just comma, to improve
11675 readability of the list; with the result that it is less efficient than
11676 @code{m4_dquote}.
11677 @example
11678 m4_define([zero],[0])m4_define([one],[1])m4_define([two],[2])dnl
11679 m4_dquote(zero, [one], [[two]])
11680 @result{}[0],[one],[[two]]
11681 m4_make_list(zero, [one], [[two]])
11682 @result{}[0],
11683 @result{}[one],
11684 @result{}[[two]]
11685 m4_foreach([number], m4_dquote(zero, [one], [[two]]), [ number])
11686 @result{} 0 1 two
11687 m4_foreach([number], m4_make_list(zero, [one], [[two]]), [ number])
11688 @result{} 0 1 two
11689 @end example
11690 @end defmac
11692 @c m4_noquote is too dangerous to document - it invokes macros that
11693 @c probably rely on @samp{[]} nested quoting for proper operation.  The
11694 @c user should generally prefer m4_unquote instead.
11696 @defmac m4_quote (@var{arg}, @dots{})
11697 @msindex{quote}
11698 Return the arguments as a single entity, i.e., wrap them into a pair of
11699 quotes.  This effectively collapses multiple arguments into one,
11700 although it loses whitespace after unquoted commas in the process.
11701 @end defmac
11703 @defmac m4_reverse (@var{arg}, @dots{})
11704 @msindex{reverse}
11705 Outputs each argument with the same level of quoting, but in reverse
11706 order, and with space following each comma for readability.
11708 @example
11709 m4_define([active], [ACT,IVE])
11710 @result{}
11711 m4_reverse(active, [active])
11712 @result{}active, IVE, ACT
11713 @end example
11714 @end defmac
11716 @defmac m4_unquote (@var{arg}, @dots{})
11717 @msindex{unquote}
11718 This macro was introduced in Autoconf 2.62.  Expand each argument,
11719 separated by commas.  For a single @var{arg}, this effectively removes a
11720 layer of quoting, and @code{m4_unquote([@var{arg}])} is more efficient
11721 than the equivalent @code{m4_do([@var{arg}])}.  For multiple arguments,
11722 this results in an unquoted list of expansions.  This is commonly used
11723 with @code{m4_split}, in order to convert a single quoted list into a
11724 series of quoted elements.
11725 @end defmac
11727 The following example aims at emphasizing the difference between several
11728 scenarios: not using these macros, using @code{m4_defn}, using
11729 @code{m4_quote}, using @code{m4_dquote}, and using @code{m4_expand}.
11731 @example
11732 $ @kbd{cat example.m4}
11733 dnl Overquote, so that quotes are visible.
11734 m4_define([show], [$[]1 = [$1], $[]@@ = [$@@]])
11735 m4_define([a], [A])
11736 m4_define([mkargs], [1, 2[,] 3])
11737 m4_define([arg1], [[$1]])
11738 m4_divert([0])dnl
11739 show(a, b)
11740 show([a, b])
11741 show(m4_quote(a, b))
11742 show(m4_dquote(a, b))
11743 show(m4_expand([a, b]))
11745 arg1(mkargs)
11746 arg1([mkargs])
11747 arg1(m4_defn([mkargs]))
11748 arg1(m4_quote(mkargs))
11749 arg1(m4_dquote(mkargs))
11750 arg1(m4_expand([mkargs]))
11751 $ @kbd{autom4te -l m4sugar example.m4}
11752 $1 = A, $@@ = [A],[b]
11753 $1 = a, b, $@@ = [a, b]
11754 $1 = A,b, $@@ = [A,b]
11755 $1 = [A],[b], $@@ = [[A],[b]]
11756 $1 = A, b, $@@ = [A, b]
11759 mkargs
11760 1, 2[,] 3
11761 1,2, 3
11762 [1],[2, 3]
11763 1, 2, 3
11764 @end example
11767 @node Text processing Macros
11768 @subsection String manipulation in M4
11770 The following macros may be used to manipulate strings in M4.  Many of
11771 the macros in this section intentionally result in quoted strings as
11772 output, rather than subjecting the arguments to further expansions.  As
11773 a result, if you are manipulating text that contains active M4
11774 characters, the arguments are passed with single quoting rather than
11775 double.
11777 @defmac m4_append (@var{macro-name}, @var{string}, @ovar{separator})
11778 @defmacx m4_append_uniq (@var{macro-name}, @var{string}, @ovar{separator} @
11779   @ovar{if-uniq}, @ovar{if-duplicate})
11780 @msindex{append}
11781 @msindex{append_uniq}
11782 Redefine @var{macro-name} to its former contents with @var{separator}
11783 and @var{string} added at the end.  If @var{macro-name} was undefined
11784 before (but not if it was defined but empty), then no @var{separator} is
11785 added.  As of Autoconf 2.62, neither @var{string} nor @var{separator}
11786 are expanded during this macro; instead, they are expanded when
11787 @var{macro-name} is invoked.
11789 @code{m4_append} can be used to grow strings, and @code{m4_append_uniq}
11790 to grow strings without duplicating substrings.  Additionally,
11791 @code{m4_append_uniq} takes two optional parameters as of Autoconf 2.62;
11792 @var{if-uniq} is expanded if @var{string} was appended, and
11793 @var{if-duplicate} is expanded if @var{string} was already present.
11794 Also, @code{m4_append_uniq} warns if @var{separator} is not empty, but
11795 occurs within @var{string}, since that can lead to duplicates.
11797 Note that @code{m4_append} can scale linearly in the length of the final
11798 string, depending on the quality of the underlying M4 implementation,
11799 while @code{m4_append_uniq} has an inherent quadratic scaling factor.
11800 If an algorithm can tolerate duplicates in the final string, use the
11801 former for speed.  If duplicates must be avoided, consider using
11802 @code{m4_set_add} instead (@pxref{Set manipulation Macros}).
11804 @example
11805 m4_define([active], [ACTIVE])dnl
11806 m4_append([sentence], [This is an])dnl
11807 m4_append([sentence], [ active ])dnl
11808 m4_append([sentence], [symbol.])dnl
11809 sentence
11810 @result{}This is an ACTIVE symbol.
11811 m4_undefine([active])dnl
11812 @result{}This is an active symbol.
11813 m4_append_uniq([list], [one], [, ], [new], [existing])
11814 @result{}new
11815 m4_append_uniq([list], [one], [, ], [new], [existing])
11816 @result{}existing
11817 m4_append_uniq([list], [two], [, ], [new], [existing])
11818 @result{}new
11819 m4_append_uniq([list], [three], [, ], [new], [existing])
11820 @result{}new
11821 m4_append_uniq([list], [two], [, ], [new], [existing])
11822 @result{}existing
11823 list
11824 @result{}one, two, three
11825 m4_dquote(list)
11826 @result{}[one],[two],[three]
11827 m4_append([list2], [one], [[, ]])dnl
11828 m4_append_uniq([list2], [two], [[, ]])dnl
11829 m4_append([list2], [three], [[, ]])dnl
11830 list2
11831 @result{}one, two, three
11832 m4_dquote(list2)
11833 @result{}[one, two, three]
11834 @end example
11835 @end defmac
11837 @defmac m4_append_uniq_w (@var{macro-name}, @var{strings})
11838 @msindex{append_uniq_w}
11839 This macro was introduced in Autoconf 2.62.  It is similar to
11840 @code{m4_append_uniq}, but treats @var{strings} as a whitespace
11841 separated list of words to append, and only appends unique words.
11842 @var{macro-name} is updated with a single space between new words.
11843 @example
11844 m4_append_uniq_w([numbers], [1 1 2])dnl
11845 m4_append_uniq_w([numbers], [ 2 3 ])dnl
11846 numbers
11847 @result{}1 2 3
11848 @end example
11849 @end defmac
11851 @defmac m4_chomp (@var{string})
11852 @defmacx m4_chomp_all (@var{string})
11853 @msindex{chomp}
11854 @msindex{chomp_all}
11855 Output @var{string} in quotes, but without a trailing newline.  The
11856 macro @code{m4_chomp} is slightly faster, and removes at most one
11857 newline; the macro @code{m4_chomp_all} removes all consecutive trailing
11858 newlines.  Unlike @code{m4_flatten}, embedded newlines are left intact,
11859 and backslash does not influence the result.
11860 @end defmac
11862 @defmac m4_combine (@ovar{separator}, @var{prefix-list}, @ovar{infix}, @
11863   @var{suffix-1}, @ovar{suffix-2}, @dots{})
11864 @msindex{combine}
11865 This macro produces a quoted string containing the pairwise combination
11866 of every element of the quoted, comma-separated @var{prefix-list}, and
11867 every element from the @var{suffix} arguments.  Each pairwise
11868 combination is joined with @var{infix} in the middle, and successive
11869 pairs are joined by @var{separator}.  No expansion occurs on any of the
11870 arguments.  No output occurs if either the @var{prefix} or @var{suffix}
11871 list is empty, but the lists can contain empty elements.
11872 @example
11873 m4_define([a], [oops])dnl
11874 m4_combine([, ], [[a], [b], [c]], [-], [1], [2], [3])
11875 @result{}a-1, a-2, a-3, b-1, b-2, b-3, c-1, c-2, c-3
11876 m4_combine([, ], [[a], [b]], [-])
11877 @result{}
11878 m4_combine([, ], [[a], [b]], [-], [])
11879 @result{}a-, b-
11880 m4_combine([, ], [], [-], [1], [2])
11881 @result{}
11882 m4_combine([, ], [[]], [-], [1], [2])
11883 @result{}-1, -2
11884 @end example
11885 @end defmac
11887 @defmac m4_flatten (@var{string})
11888 @msindex{flatten}
11889 Flatten @var{string} into a single line.  Delete all backslash-newline
11890 pairs, and replace all remaining newlines with a space.  The result is
11891 still a quoted string.
11892 @end defmac
11894 @defmac m4_join (@ovar{separator}, @var{args}@dots{})
11895 @defmacx m4_joinall (@ovar{separator}, @var{args}@dots{})
11896 @msindex{join}
11897 @msindex{joinall}
11898 Concatenate each @var{arg}, separated by @var{separator}.
11899 @code{joinall} uses every argument, while @code{join} omits empty
11900 arguments so that there are no back-to-back separators in the output.
11901 The result is a quoted string.
11902 @example
11903 m4_define([active], [ACTIVE])dnl
11904 m4_join([|], [one], [], [active], [two])
11905 @result{}one|active|two
11906 m4_joinall([|], [one], [], [active], [two])
11907 @result{}one||active|two
11908 @end example
11910 Note that if all you intend to do is join @var{args} with commas between
11911 them, to form a quoted list suitable for @code{m4_foreach}, it is more
11912 efficient to use @code{m4_dquote}.
11913 @end defmac
11915 @defmac m4_newline (@ovar{text})
11916 @msindex{newline}
11917 This macro was introduced in Autoconf 2.62, and expands to a newline,
11918 followed by any @var{text}.
11919 It is primarily useful for maintaining macro formatting, and ensuring
11920 that M4 does not discard leading whitespace during argument collection.
11921 @end defmac
11923 @defmac m4_normalize (@var{string})
11924 @msindex{normalize}
11925 Remove leading and trailing spaces and tabs, sequences of
11926 backslash-then-newline, and replace multiple spaces, tabs, and newlines
11927 with a single space.  This is a combination of @code{m4_flatten} and
11928 @code{m4_strip}.  To determine if @var{string} consists only of bytes
11929 that would be removed by @code{m4_normalize}, you can use
11930 @code{m4_ifblank}.
11931 @end defmac
11933 @defmac m4_re_escape (@var{string})
11934 @msindex{re_escape}
11935 Backslash-escape all characters in @var{string} that are active in
11936 regexps.
11937 @end defmac
11939 @defmac m4_split (@var{string}, @dvar{regexp, [\t ]+})
11940 @msindex{split}
11941 Split @var{string} into an M4 list of elements quoted by @samp{[} and
11942 @samp{]}, while keeping white space at the beginning and at the end.
11943 If @var{regexp} is given, use it instead of @samp{[\t ]+} for splitting.
11944 If @var{string} is empty, the result is an empty list.
11945 @end defmac
11947 @defmac m4_strip (@var{string})
11948 @msindex{strip}
11949 Strip whitespace from @var{string}.  Sequences of spaces and tabs are
11950 reduced to a single space, then leading and trailing spaces are removed.
11951 The result is still a quoted string.  Note that this does not interfere
11952 with newlines; if you want newlines stripped as well, consider
11953 @code{m4_flatten}, or do it all at once with @code{m4_normalize}.  To
11954 quickly test if @var{string} has only whitespace, use @code{m4_ifblank}.
11955 @end defmac
11957 @defmac m4_text_box (@var{message}, @dvar{frame, -})
11958 @msindex{text_box}
11959 Add a text box around @var{message}, using @var{frame} as the border
11960 character above and below the message.  The frame correctly accounts for
11961 the subsequent expansion of @var{message}.  For example:
11962 @example
11963 m4_define([macro], [abc])dnl
11964 m4_text_box([macro])
11965 @result{}## --- ##
11966 @result{}## abc ##
11967 @result{}## --- ##
11968 @end example
11970 The @var{message} must contain balanced quotes and parentheses, although
11971 quadrigraphs can be used to work around this.
11972 @end defmac
11974 @defmac m4_text_wrap (@var{string}, @ovar{prefix}, @
11975   @dvar{prefix1, @var{prefix}}, @dvar{width, 79})
11976 @msindex{text_wrap}
11977 Break @var{string} into a series of whitespace-separated words, then
11978 output those words separated by spaces, and wrapping lines any time the
11979 output would exceed @var{width} columns.  If given, @var{prefix1} begins
11980 the first line, and @var{prefix} begins all wrapped lines.  If
11981 @var{prefix1} is longer than @var{prefix}, then the first line consists
11982 of just @var{prefix1}.  If @var{prefix} is longer than @var{prefix1},
11983 padding is inserted so that the first word of @var{string} begins at the
11984 same indentation as all wrapped lines.  Note that using literal tab
11985 characters in any of the arguments will interfere with the calculation
11986 of width.  No expansions occur on @var{prefix}, @var{prefix1}, or the
11987 words of @var{string}, although quadrigraphs are recognized.
11989 For some examples:
11990 @example
11991 m4_text_wrap([Short string */], [   ], [/* ], [20])
11992 @result{}/* Short string */
11993 m4_text_wrap([Much longer string */], [   ], [/* ], [20])
11994 @result{}/* Much longer
11995 @result{}   string */
11996 m4_text_wrap([Short doc.], [          ], [  --short ], [30])
11997 @result{}  --short Short doc.
11998 m4_text_wrap([Short doc.], [          ], [  --too-wide ], [30])
11999 @result{}  --too-wide
12000 @result{}          Short doc.
12001 m4_text_wrap([Super long documentation.], [     ],
12002              [  --too-wide ], 30)
12003 @result{}  --too-wide
12004 @result{}     Super long
12005 @result{}     documentation.
12006 @end example
12007 @end defmac
12009 @defmac m4_tolower (@var{string})
12010 @defmacx m4_toupper (@var{string})
12011 @msindex{tolower}
12012 @msindex{toupper}
12013 Return @var{string} with letters converted to upper or lower case,
12014 respectively.
12015 @end defmac
12017 @node Number processing Macros
12018 @subsection Arithmetic computation in M4
12020 The following macros facilitate integer arithmetic operations.
12021 Where a parameter is documented as taking an arithmetic expression, you
12022 can use anything that can be parsed by @code{m4_eval}.
12024 @defmac m4_cmp (@var{expr-1}, @var{expr-2})
12025 @msindex{cmp}
12026 Compare the arithmetic expressions @var{expr-1} and @var{expr-2}, and
12027 expand to @samp{-1} if @var{expr-1} is smaller, @samp{0} if they are
12028 equal, and @samp{1} if @var{expr-1} is larger.
12029 @end defmac
12031 @defmac m4_list_cmp (@var{list-1}, @var{list-2})
12032 @msindex{list_cmp}
12033 Compare the two M4 lists consisting of comma-separated arithmetic
12034 expressions, left to right.  Expand to @samp{-1} for the first element
12035 pairing where the value from @var{list-1} is smaller, @samp{1} where the
12036 value from @var{list-2} is smaller, or @samp{0} if both lists have the
12037 same values.  If one list is shorter than the other, the remaining
12038 elements of the longer list are compared against zero.
12039 @example
12040 m4_list_cmp([1, 0],       [1])
12041 @result{}0
12042 m4_list_cmp([1, [1 * 0]], [1, 0])
12043 @result{}0
12044 m4_list_cmp([1, 2],       [1, 0])
12045 @result{}1
12046 m4_list_cmp([1, [1+1], 3],[1, 2])
12047 @result{}1
12048 m4_list_cmp([1, 2, -3],   [1, 2])
12049 @result{}-1
12050 m4_list_cmp([1, 0],       [1, 2])
12051 @result{}-1
12052 m4_list_cmp([1],          [1, 2])
12053 @result{}-1
12054 @end example
12055 @end defmac
12057 @defmac m4_max (@var{arg}, @dots{})
12058 @msindex{max}
12059 This macro was introduced in Autoconf 2.62.  Expand to the decimal value
12060 of the maximum arithmetic expression among all the arguments.
12061 @end defmac
12063 @defmac m4_min (@var{arg}, @dots{})
12064 @msindex{min}
12065 This macro was introduced in Autoconf 2.62.  Expand to the decimal value
12066 of the minimum arithmetic expression among all the arguments.
12067 @end defmac
12069 @defmac m4_sign (@var{expr})
12070 @msindex{sign}
12071 Expand to @samp{-1} if the arithmetic expression @var{expr} is negative,
12072 @samp{1} if it is positive, and @samp{0} if it is zero.
12073 @end defmac
12075 @anchor{m4_version_compare}
12076 @defmac m4_version_compare (@var{version-1}, @var{version-2})
12077 @msindex{version_compare}
12078 This macro was introduced in Autoconf 2.53, but had a number of
12079 usability limitations that were not lifted until Autoconf 2.62.  Compare
12080 the version strings @var{version-1} and @var{version-2}, and expand to
12081 @samp{-1} if @var{version-1} is smaller, @samp{0} if they are the same,
12082 or @samp{1} @var{version-2} is smaller.  Version strings must be a list
12083 of elements separated by @samp{.}, @samp{,} or @samp{-}, where each
12084 element is a number along with optional case-insensitive letters
12085 designating beta releases.  The comparison stops at the leftmost element
12086 that contains a difference, although a 0 element compares equal to a
12087 missing element.
12089 It is permissible to include commit identifiers in @var{version}, such
12090 as an abbreviated SHA1 of the commit, provided there is still a
12091 monotonically increasing prefix to allow for accurate version-based
12092 comparisons.  For example, this paragraph was written when the
12093 development snapshot of autoconf claimed to be at version
12094 @samp{2.61a-248-dc51}, or 248 commits after the 2.61a release, with an
12095 abbreviated commit identification of @samp{dc51}.
12097 @example
12098 m4_version_compare([1.1], [2.0])
12099 @result{}-1
12100 m4_version_compare([2.0b], [2.0a])
12101 @result{}1
12102 m4_version_compare([1.1.1], [1.1.1a])
12103 @result{}-1
12104 m4_version_compare([1.2], [1.1.1a])
12105 @result{}1
12106 m4_version_compare([1.0], [1])
12107 @result{}0
12108 m4_version_compare([1.1pre], [1.1PRE])
12109 @result{}0
12110 m4_version_compare([1.1a], [1,10])
12111 @result{}-1
12112 m4_version_compare([2.61a], [2.61a-248-dc51])
12113 @result{}-1
12114 m4_version_compare([2.61b], [2.61a-248-dc51])
12115 @result{}1
12116 @end example
12117 @end defmac
12119 @defmac m4_version_prereq (@var{version}, @ovar{if-new-enough}, @
12120   @dvar{if-old, m4_fatal})
12121 @msindex{version_prereq}
12122 Compares @var{version} against the version of Autoconf currently
12123 running.  If the running version is at @var{version} or newer, expand
12124 @var{if-new-enough}, but if @var{version} is larger than the version
12125 currently executing, expand @var{if-old}, which defaults to printing an
12126 error message and exiting m4sugar with status 63.  When given only one
12127 argument, this behaves like @code{AC_PREREQ} (@pxref{Versioning}).
12128 Remember that the autoconf philosophy favors feature checks over version
12129 checks.
12130 @end defmac
12132 @node Set manipulation Macros
12133 @subsection Set manipulation in M4
12134 @cindex Set manipulation
12135 @cindex Data structure, set
12136 @cindex Unordered set manipulation
12138 Sometimes, it is necessary to track a set of data, where the order does
12139 not matter and where there are no duplicates in the set.  The following
12140 macros facilitate set manipulations.  Each set is an opaque object,
12141 which can only be accessed via these basic operations.  The underlying
12142 implementation guarantees linear scaling for set creation, which is more
12143 efficient than using the quadratic @code{m4_append_uniq}.  Both set
12144 names and values can be arbitrary strings, except for unbalanced quotes.
12145 This implementation ties up memory for removed elements until the next
12146 operation that must traverse all the elements of a set; and although
12147 that may slow down some operations until the memory for removed elements
12148 is pruned, it still guarantees linear performance.
12150 @defmac m4_set_add (@var{set}, @var{value}, @ovar{if-uniq}, @ovar{if-dup})
12151 @msindex{set_add}
12152 Adds the string @var{value} as a member of set @var{set}.  Expand
12153 @var{if-uniq} if the element was added, or @var{if-dup} if it was
12154 previously in the set.  Operates in amortized constant time, so that set
12155 creation scales linearly.
12156 @end defmac
12158 @defmac m4_set_add_all (@var{set}, @var{value}@dots{})
12159 @msindex{set_add_all}
12160 Adds each @var{value} to the set @var{set}.  This is slightly more
12161 efficient than repeatedly invoking @code{m4_set_add}.
12162 @end defmac
12164 @defmac m4_set_contains (@var{set}, @var{value}, @ovar{if-present}, @
12165  @ovar{if-absent})
12166 @msindex{set_contains}
12167 Expands @var{if-present} if the string @var{value} is a member of
12168 @var{set}, otherwise @var{if-absent}.
12170 @example
12171 m4_set_contains([a], [1], [yes], [no])
12172 @result{}no
12173 m4_set_add([a], [1], [added], [dup])
12174 @result{}added
12175 m4_set_add([a], [1], [added], [dup])
12176 @result{}dup
12177 m4_set_contains([a], [1], [yes], [no])
12178 @result{}yes
12179 m4_set_remove([a], [1], [removed], [missing])
12180 @result{}removed
12181 m4_set_contains([a], [1], [yes], [no])
12182 @result{}no
12183 m4_set_remove([a], [1], [removed], [missing])
12184 @result{}missing
12185 @end example
12186 @end defmac
12188 @defmac m4_set_contents (@var{set}, @ovar{sep})
12189 @defmacx m4_set_dump (@var{set}, @ovar{sep})
12190 @msindex{set_contents}
12191 @msindex{set_dump}
12192 Expands to a single string consisting of all the members of the set
12193 @var{set}, each separated by @var{sep}, which is not expanded.
12194 @code{m4_set_contents} leaves the elements in @var{set} but reclaims any
12195 memory occupied by removed elements, while @code{m4_set_dump} is a
12196 faster one-shot action that also deletes the set.  No provision is made
12197 for disambiguating members that contain a non-empty @var{sep} as a
12198 substring; use @code{m4_set_empty} to distinguish between an empty set
12199 and the set containing only the empty string.  The order of the output
12200 is unspecified; in the current implementation, part of the speed of
12201 @code{m4_set_dump} results from using a different output order than
12202 @code{m4_set_contents}.  These macros scale linearly in the size of the
12203 set before memory pruning, and @code{m4_set_contents([@var{set}],
12204 [@var{sep}])} is faster than
12205 @code{m4_joinall([@var{sep}]m4_set_listc([@var{set}]))}.
12207 @example
12208 m4_set_add_all([a], [1], [2], [3])
12209 @result{}
12210 m4_set_contents([a], [-])
12211 @result{}1-2-3
12212 m4_joinall([-]m4_set_listc([a]))
12213 @result{}1-2-3
12214 m4_set_dump([a], [-])
12215 @result{}3-2-1
12216 m4_set_contents([a])
12217 @result{}
12218 m4_set_add([a], [])
12219 @result{}
12220 m4_set_contents([a], [-])
12221 @result{}
12222 @end example
12223 @end defmac
12225 @defmac m4_set_delete (@var{set})
12226 @msindex{set_delete}
12227 Delete all elements and memory associated with @var{set}.  This is
12228 linear in the set size, and faster than removing one element at a time.
12229 @end defmac
12231 @defmac m4_set_difference (@var{seta}, @var{setb})
12232 @defmacx m4_set_intersection (@var{seta}, @var{setb})
12233 @defmacx m4_set_union (@var{seta}, @var{setb})
12234 @msindex{set_difference}
12235 @msindex{set_intersection}
12236 @msindex{set_union}
12237 Compute the relation between @var{seta} and @var{setb}, and output the
12238 result as a list of quoted arguments without duplicates and with a
12239 leading comma.  Set difference selects the elements in @var{seta} but
12240 not @var{setb}, intersection selects only elements in both sets, and
12241 union selects elements in either set.  These actions are linear in the
12242 sum of the set sizes.  The leading comma is necessary to distinguish
12243 between no elements and the empty string as the only element.
12245 @example
12246 m4_set_add_all([a], [1], [2], [3])
12247 @result{}
12248 m4_set_add_all([b], [3], [], [4])
12249 @result{}
12250 m4_set_difference([a], [b])
12251 @result{},1,2
12252 m4_set_difference([b], [a])
12253 @result{},,4
12254 m4_set_intersection([a], [b])
12255 @result{},3
12256 m4_set_union([a], [b])
12257 @result{},1,2,3,,4
12258 @end example
12259 @end defmac
12261 @defmac m4_set_empty (@var{set}, @ovar{if-empty}, @ovar{if-elements})
12262 @msindex{set_empty}
12263 Expand @var{if-empty} if the set @var{set} has no elements, otherwise
12264 expand @var{if-elements}.  This macro operates in constant time.  Using
12265 this macro can help disambiguate output from @code{m4_set_contents} or
12266 @code{m4_set_list}.
12267 @end defmac
12269 @defmac m4_set_foreach (@var{set}, @var{variable}, @var{action})
12270 @msindex{set_foreach}
12271 For each element in the set @var{set}, expand @var{action} with the
12272 macro @var{variable} defined as the set element.  Behavior is
12273 unspecified if @var{action} recursively lists the contents of @var{set}
12274 (although listing other sets is acceptable), or if it modifies the set
12275 in any way other than removing the element currently contained in
12276 @var{variable}.  This macro is faster than the corresponding
12277 @code{m4_foreach([@var{variable}],
12278 m4_indir([m4_dquote]m4_set_listc([@var{set}])), [@var{action}])},
12279 although @code{m4_set_map} might be faster still.
12281 @example
12282 m4_set_add_all([a]m4_for([i], [1], [5], [], [,i]))
12283 @result{}
12284 m4_set_contents([a])
12285 @result{}12345
12286 m4_set_foreach([a], [i],
12287   [m4_if(m4_eval(i&1), [0], [m4_set_remove([a], i, [i])])])
12288 @result{}24
12289 m4_set_contents([a])
12290 @result{}135
12291 @end example
12292 @end defmac
12294 @defmac m4_set_list (@var{set})
12295 @defmacx m4_set_listc (@var{set})
12296 @msindex{set_list}
12297 @msindex{set_listc}
12298 Produce a list of arguments, where each argument is a quoted element
12299 from the set @var{set}.  The variant @code{m4_set_listc} is unambiguous,
12300 by adding a leading comma if there are any set elements, whereas the
12301 variant @code{m4_set_list} cannot distinguish between an empty set and a
12302 set containing only the empty string.  These can be directly used in
12303 macros that take multiple arguments, such as @code{m4_join} or
12304 @code{m4_set_add_all}, or wrapped by @code{m4_dquote} for macros that
12305 take a quoted list, such as @code{m4_map} or @code{m4_foreach}.  Any
12306 memory occupied by removed elements is reclaimed during these macros.
12308 @example
12309 m4_set_add_all([a], [1], [2], [3])
12310 @result{}
12311 m4_set_list([a])
12312 @result{}1,2,3
12313 m4_set_list([b])
12314 @result{}
12315 m4_set_listc([b])
12316 @result{}
12317 m4_count(m4_set_list([b]))
12318 @result{}1
12319 m4_set_empty([b], [0], [m4_count(m4_set_list([b]))])
12320 @result{}0
12321 m4_set_add([b], [])
12322 @result{}
12323 m4_set_list([b])
12324 @result{}
12325 m4_set_listc([b])
12326 @result{},
12327 m4_count(m4_set_list([b]))
12328 @result{}1
12329 m4_set_empty([b], [0], [m4_count(m4_set_list([b]))])
12330 @result{}1
12331 @end example
12332 @end defmac
12334 @defmac m4_set_map (@var{set}, @var{action})
12335 @msindex{set_map}
12336 For each element in the set @var{set}, expand @var{action} with a single
12337 argument of the set element.  Behavior is unspecified if @var{action}
12338 recursively lists the contents of @var{set} (although listing other sets
12339 is acceptable), or if it modifies the set in any way other than removing
12340 the element passed as an argument.  This macro is faster than either
12341 corresponding counterpart of
12342 @code{m4_map_args([@var{action}]m4_set_listc([@var{set}]))} or
12343 @code{m4_set_foreach([@var{set}], [var],
12344 [@var{action}(m4_defn([var]))])}.  It is possible to use @code{m4_curry}
12345 if more than one argument is needed for @var{action}, although it is
12346 more efficient to use @code{m4_set_map_sep} in that case.
12347 @end defmac
12349 @defmac m4_set_map_sep (@var{set}, @ovar{pre}, @ovar{post}, @ovar{sep})
12350 @msindex{set_map_sep}
12351 For each element in the set @var{set}, expand
12352 @code{@var{pre}[element]@var{post}}, additionally expanding @var{sep}
12353 between elements.  Behavior is unspecified if the expansion recursively
12354 lists the contents of @var{set} (although listing other sets
12355 is acceptable), or if it modifies the set in any way other than removing
12356 the element visited by the expansion.  This macro provides the most
12357 efficient means for non-destructively visiting the elements of a set; in
12358 particular, @code{m4_set_map([@var{set}], [@var{action}])} is equivalent
12359 to @code{m4_set_map_sep([@var{set}], [@var{action}(], [)])}.
12360 @end defmac
12362 @defmac m4_set_remove (@var{set}, @var{value}, @ovar{if-present}, @
12363  @ovar{if-absent})
12364 @msindex{set_remove}
12365 If @var{value} is an element in the set @var{set}, then remove it and
12366 expand @var{if-present}.  Otherwise expand @var{if-absent}.  This macro
12367 operates in constant time so that multiple removals will scale linearly
12368 rather than quadratically; but when used outside of
12369 @code{m4_set_foreach} or @code{m4_set_map}, it leaves memory occupied
12370 until the set is later
12371 compacted by @code{m4_set_contents} or @code{m4_set_list}.  Several
12372 other set operations are then less efficient between the time of element
12373 removal and subsequent memory compaction, but still maintain their
12374 guaranteed scaling performance.
12375 @end defmac
12377 @defmac m4_set_size (@var{set})
12378 @msindex{set_size}
12379 Expand to the size of the set @var{set}.  This implementation operates
12380 in constant time, and is thus more efficient than
12381 @code{m4_eval(m4_count(m4_set_listc([set])) - 1)}.
12382 @end defmac
12385 @node Forbidden Patterns
12386 @subsection Forbidden Patterns
12387 @cindex Forbidden patterns
12388 @cindex Patterns, forbidden
12390 M4sugar provides a means to define suspicious patterns, patterns
12391 describing tokens which should not be found in the output.  For
12392 instance, if an Autoconf @file{configure} script includes tokens such as
12393 @samp{AC_DEFINE}, or @samp{dnl}, then most probably something went
12394 wrong (typically a macro was not evaluated because of overquotation).
12396 M4sugar forbids all the tokens matching @samp{^_?m4_} and @samp{^dnl$}.
12397 Additional layers, such as M4sh and Autoconf, add additional forbidden
12398 patterns to the list.
12400 @defmac m4_pattern_forbid (@var{pattern})
12401 @msindex{pattern_forbid}
12402 Declare that no token matching @var{pattern} must be found in the output.
12403 Comments are not checked; this can be a problem if, for instance, you
12404 have some macro left unexpanded after an @samp{#include}.  No consensus
12405 is currently found in the Autoconf community, as some people consider it
12406 should be valid to name macros in comments (which doesn't make sense to
12407 the authors of this documentation: input, such as macros, should be
12408 documented by @samp{dnl} comments; reserving @samp{#}-comments to
12409 document the output).
12410 @end defmac
12412 Of course, you might encounter exceptions to these generic rules, for
12413 instance you might have to refer to @samp{$m4_flags}.
12415 @defmac m4_pattern_allow (@var{pattern})
12416 @msindex{pattern_allow}
12417 Any token matching @var{pattern} is allowed, including if it matches an
12418 @code{m4_pattern_forbid} pattern.
12419 @end defmac
12421 @node Programming in M4sh
12422 @chapter Programming in M4sh
12424 M4sh, pronounced ``mash'', is aiming at producing portable Bourne shell
12425 scripts.  This name was coined by Lars J. Aas, who notes that,
12426 according to the Webster's Revised Unabridged Dictionary (1913):
12428 @quotation
12429 Mash \Mash\, n.  [Akin to G. meisch, maisch, meische, maische, mash,
12430 wash, and prob.@: to AS. miscian to mix.  See ``Mix''.]
12432 @enumerate 1
12433 @item
12434 A mass of mixed ingredients reduced to a soft pulpy state by beating or
12435 pressure@enddots{}
12437 @item
12438 A mixture of meal or bran and water fed to animals.
12440 @item
12441 A mess; trouble.  [Obs.] --Beau.@: & Fl.
12442 @end enumerate
12443 @end quotation
12445 M4sh reserves the M4 macro namespace @samp{^_AS_} for internal use, and
12446 the namespace @samp{^AS_} for M4sh macros.  It also reserves the shell
12447 and environment variable namespace @samp{^as_}, and the here-document
12448 delimiter namespace @samp{^_AS[A-Z]} in the output file.  You should not
12449 define your own macros or output shell code that conflicts with these
12450 namespaces.
12452 @menu
12453 * Common Shell Constructs::     Portability layer for common shell constructs
12454 * Polymorphic Variables::       Support for indirect variable names
12455 * Initialization Macros::       Macros to establish a sane shell environment
12456 * File Descriptor Macros::      File descriptor macros for input and output
12457 @end menu
12459 @node Common Shell Constructs
12460 @section Common Shell Constructs
12462 M4sh provides portable alternatives for some common shell constructs
12463 that unfortunately are not portable in practice.
12465 @c Deprecated, to be replaced by a better API
12466 @ignore
12467 @defmac AS_BASENAME (@var{file-name})
12468 @asindex{BASENAME}
12469 Output the non-directory portion of @var{file-name}.  For example,
12470 if @code{$file} is @samp{/one/two/three}, the command
12471 @code{base=`AS_BASENAME(["$file"])`} sets @code{base} to @samp{three}.
12472 @end defmac
12473 @end ignore
12475 @defmac AS_CASE (@var{word}, @ovar{pattern1}, @ovar{if-matched1}, @
12476   @dots{}, @ovar{default})
12477 @asindex{CASE}
12478 Expand into a shell @samp{case} statement, where @var{word} is matched
12479 against one or more patterns.  @var{if-matched} is run if the
12480 corresponding pattern matched @var{word}, else @var{default} is run.
12481 Avoids several portability issues (@pxref{case, , Limitations of Shell
12482 Builtins}).
12483 @end defmac
12485 @c Deprecated, to be replaced by a better API
12486 @ignore
12487 @defmac AS_DIRNAME (@var{file-name})
12488 @asindex{DIRNAME}
12489 Output the directory portion of @var{file-name}.  For example,
12490 if @code{$file} is @samp{/one/two/three}, the command
12491 @code{dir=`AS_DIRNAME(["$file"])`} sets @code{dir} to @samp{/one/two}.
12492 @end defmac
12493 @end ignore
12495 @defmac AS_ECHO (@var{word})
12496 @asindex{ECHO}
12497 Emits @var{word} to the standard output, followed by a newline.  @var{word}
12498 must be a single shell word (typically a quoted string).  The bytes of
12499 @var{word} are output as-is, even if it starts with "-" or contains "\".
12500 Redirections can be placed outside the macro invocation.  This is much
12501 more portable than using @command{echo} (@pxref{echo, , Limitations of
12502 Shell Builtins}).
12503 @end defmac
12505 @defmac AS_ECHO_N (@var{word})
12506 @asindex{ECHO_N}
12507 Emits @var{word} to the standard output, without a following newline.
12508 @var{word} must be a single shell word (typically a quoted string) and,
12509 for portability, should not include more than one newline.  The bytes of
12510 @var{word} are output as-is, even if it starts with "-" or contains "\".
12511 Redirections can be placed outside the macro invocation.
12512 @end defmac
12514 @defmac AS_ESCAPE (@var{string}, @dvar{chars, `\"$})
12515 @asindex{ESCAPE}
12516 Expands to @var{string}, with any characters in @var{chars} escaped with
12517 a backslash (@samp{\}).  @var{chars} should be at most four bytes long,
12518 and only contain characters from the set @samp{`\"$}; however,
12519 characters may be safely listed more than once in @var{chars} for the
12520 sake of syntax highlighting editors.  The current implementation expands
12521 @var{string} after adding escapes; if @var{string} contains macro calls
12522 that in turn expand to text needing shell quoting, you can use
12523 @code{AS_ESCAPE(m4_dquote(m4_expand([string])))}.
12525 The default for @var{chars} (@samp{\"$`}) is the set of characters
12526 needing escapes when @var{string} will be used literally within double
12527 quotes.  One common variant is the set of characters to protect when
12528 @var{string} will be used literally within back-ticks or an unquoted
12529 here-document (@samp{\$`}).  Another common variant is @samp{""}, which can
12530 be used to form a double-quoted string containing the same expansions
12531 that would have occurred if @var{string} were expanded in an unquoted
12532 here-document; however, when using this variant, care must be taken that
12533 @var{string} does not use double quotes within complex variable
12534 expansions (such as @samp{$@{foo-`echo "hi"`@}}) that would be broken
12535 with improper escapes.
12537 This macro is often used with @code{AS_ECHO}.  For an example, observe
12538 the output generated by the shell code generated from this snippet:
12540 @example
12541 foo=bar
12542 AS_ECHO(["AS_ESCAPE(["$foo" = ])AS_ESCAPE(["$foo"], [""])"])
12543 @result{}"$foo" = "bar"
12544 m4_define([macro], [a, [\b]])
12545 AS_ECHO(["AS_ESCAPE([[macro]])"])
12546 @result{}macro
12547 AS_ECHO(["AS_ESCAPE([macro])"])
12548 @result{}a, b
12549 AS_ECHO(["AS_ESCAPE(m4_dquote(m4_expand([macro])))"])
12550 @result{}a, \b
12551 @end example
12553 @comment Should we add AS_ESCAPE_SINGLE? If we do, we can optimize in
12554 @comment the case of @var{string} that does not contain '.
12555 To escape a string that will be placed within single quotes, use:
12557 @example
12558 m4_bpatsubst([[@var{string}]], ['], ['\\''])
12559 @end example
12560 @end defmac
12562 @defmac AS_EXIT (@dvar{status, $?})
12563 @asindex{EXIT}
12564 Emit code to exit the shell with @var{status}, defaulting to @samp{$?}.
12565 This macro
12566 works around shells that see the exit status of the command prior to
12567 @code{exit} inside a @samp{trap 0} handler (@pxref{trap, , Limitations
12568 of Shell Builtins}).
12569 @end defmac
12571 @defmac AS_IF (@var{test1}, @ovar{run-if-true1}, @dots{}, @ovar{run-if-false})
12572 @asindex{IF}
12573 Run shell code @var{test1}.  If @var{test1} exits with a zero status then
12574 run shell code @var{run-if-true1}, else examine further tests.  If no test
12575 exits with a zero status, run shell code @var{run-if-false}, with
12576 simplifications if either @var{run-if-true1} or @var{run-if-false}
12577 is empty.  For example,
12579 @example
12580 AS_IF([test "x$foo" = xyes], [HANDLE_FOO([yes])],
12581       [test "x$foo" != xno], [HANDLE_FOO([maybe])],
12582       [echo foo not specified])
12583 @end example
12585 @noindent
12586 ensures any required macros of @code{HANDLE_FOO}
12587 are expanded before the first test.
12588 @end defmac
12590 @defmac AS_MKDIR_P (@var{file-name})
12591 @asindex{MKDIR_P}
12592 Make the directory @var{file-name}, including intervening directories
12593 as necessary.  This is equivalent to @samp{mkdir -p -- @var{file-name}},
12594 except that it is portable to older versions of @command{mkdir} that
12595 lack support for the @option{-p} option or for the @option{--}
12596 delimiter (@pxref{mkdir, , Limitations of Usual Tools}).  Also,
12597 @code{AS_MKDIR_P}
12598 succeeds if @var{file-name} is a symbolic link to an existing directory,
12599 even though Posix is unclear whether @samp{mkdir -p} should
12600 succeed in that case.  If creation of @var{file-name} fails, exit the
12601 script.
12603 Also see the @code{AC_PROG_MKDIR_P} macro (@pxref{Particular Programs}).
12604 @end defmac
12606 @defmac AS_SET_STATUS (@var{status})
12607 @asindex{SET_STATUS}
12608 Emit shell code to set the value of @samp{$?} to @var{status}, as
12609 efficiently as possible.  However, this is not guaranteed to abort a
12610 shell running with @code{set -e} (@pxref{set, , Limitations of Shell
12611 Builtins}).
12612 @end defmac
12614 @defmac AS_TR_CPP (@var{expression})
12615 @asindex{TR_CPP}
12616 Transform @var{expression} into a valid right-hand side for a C @code{#define}.
12617 For example:
12619 @example
12620 # This outputs "#define HAVE_CHAR_P 1".
12621 # Notice the m4 quoting around #, to prevent an m4 comment
12622 type="char *"
12623 echo "[#]define AS_TR_CPP([HAVE_$type]) 1"
12624 @end example
12625 @end defmac
12627 @defmac AS_TR_SH (@var{expression})
12628 @asindex{TR_SH}
12629 Transform @var{expression} into a valid shell variable name.  For example:
12631 @example
12632 # This outputs "Have it!".
12633 header="sys/some file.h"
12634 AS_TR_SH([HAVE_$header])=yes
12635 if test "x$HAVE_sys_some_file_h" = xyes; then echo "Have it!"; fi
12636 @end example
12637 @end defmac
12639 @defmac AS_SET_CATFILE (@var{var}, @var{dir}, @var{file})
12640 @asindex{SET_CATFILE}
12641 Set the shell variable @var{var} to @var{dir}/@var{file}, but
12642 optimizing the common cases (@var{dir} or @var{file} is @samp{.},
12643 @var{file} is absolute, etc.).
12644 @end defmac
12646 @defmac AS_UNSET (@var{var})
12647 @asindex{UNSET}
12648 Unsets the shell variable @var{var}, working around bugs in older
12649 shells (@pxref{unset, , Limitations of Shell
12650 Builtins}).  @var{var} can be a literal or indirect variable name.
12651 @end defmac
12653 @defmac AS_VERSION_COMPARE (@var{version-1}, @var{version-2}, @
12654   @ovar{action-if-less}, @ovar{action-if-equal}, @ovar{action-if-greater})
12655 @asindex{VERSION_COMPARE}
12656 Compare two strings @var{version-1} and @var{version-2}, possibly
12657 containing shell variables, as version strings, and expand
12658 @var{action-if-less}, @var{action-if-equal}, or @var{action-if-greater}
12659 depending upon the result.
12660 The algorithm to compare is similar to the one used by strverscmp in
12661 glibc (@pxref{String/Array Comparison, , String/Array Comparison, libc,
12662 The @acronym{GNU} C Library}).
12663 @end defmac
12665 @node Polymorphic Variables
12666 @section Support for indirect variable names
12667 @cindex variable name indirection
12668 @cindex polymorphic variable name
12669 @cindex indirection, variable name
12671 Often, it is convenient to write a macro that will emit shell code
12672 operating on a shell variable.  The simplest case is when the variable
12673 name is known.  But a more powerful idiom is writing shell code that can
12674 work through an indirection, where another variable or command
12675 substitution produces the name of the variable to actually manipulate.
12676 M4sh supports the notion of polymorphic shell variables, making it easy
12677 to write a macro that can deal with either literal or indirect variable
12678 names and output shell code appropriate for both use cases.  Behavior is
12679 undefined if expansion of an indirect variable does not result in a
12680 literal variable name.
12682 @defmac AS_LITERAL_IF (@var{expression}, @ovar{if-literal}, @ovar{if-not})
12683 @asindex{LITERAL_IF}
12684 If the expansion of @var{expression} is definitely a shell literal,
12685 expand @var{if-literal}.  If the expansion of @var{expression} looks
12686 like it might contain shell indirections (such as @code{$var} or
12687 @code{`expr`}), then @var{if-not} is expanded.  In order to reduce the
12688 time spent deciding whether an expression is literal, the implementation
12689 is somewhat conservative (for example, @samp{'[$]'} is a single-quoted
12690 shell literal, but causes @var{if-not} to be expanded).  While this
12691 macro is often used for recognizing shell variable names, it can also be
12692 used in other contexts.
12694 @example
12695 AC_DEFUN([MY_ACTION],
12696 [AS_LITERAL_IF([$1],
12697 [echo "$1"],
12698 [AS_VAR_COPY([tmp], [$1])
12699 echo "$tmp"])])
12700 @end example
12701 @end defmac
12703 @defmac AS_VAR_APPEND (@var{var}, @var{text})
12704 @asindex{APPEND}
12705 Emit shell code to append the shell expansion of @var{text} to the end
12706 of the current contents of the polymorphic shell variable @var{var},
12707 taking advantage of shells that provide the @samp{+=} extension for more
12708 efficient scaling.
12710 For situations where the final contents of @var{var} are relatively
12711 short (less than 256 bytes), it is more efficient to use the simpler
12712 code sequence of @code{@var{var}=$@{@var{var}@}@var{text}} (or its
12713 polymorphic equivalent of @code{AS_VAR_COPY([tmp], [@var{var}])} and
12714 @code{AS_VAR_SET([@var{var}], ["$tmp"@var{text}])}).  But in the case
12715 when the script will be repeatedly appending text into @code{var},
12716 issues of scaling start to become apparent.  A naive implementation
12717 requires execution time linear to the length of the current contents of
12718 @var{var} as well as the length of @var{text} for a single append, for
12719 an overall quadratic scaling with multiple appends.  This macro takes
12720 advantage of shells which provide the extension
12721 @code{@var{var}+=@var{text}}, which can provide amortized constant time
12722 for a single append, for an overall linear scaling with multiple
12723 appends.  Note that unlike @code{AS_VAR_SET}, this macro requires that
12724 @var{text} be quoted properly to avoid field splitting and file name
12725 expansion.
12726 @end defmac
12728 @defmac AS_VAR_ARITH (@var{var}, @var{expression})
12729 @asindex{ARITH}
12730 Emit shell code to compute the arithmetic expansion of @var{expression},
12731 assigning the result as the contents of the polymorphic shell variable
12732 @var{var}.  The code takes advantage of shells that provide @samp{$(())}
12733 for fewer forks, but uses @command{expr} as a fallback.  Therefore, the
12734 syntax for a valid @var{expression} is rather limited: all operators
12735 must occur as separate shell arguments and with proper quoting, there is
12736 no portable equality operator, all variables containing numeric values
12737 must be expanded prior to the computation, all numeric values must be
12738 provided in decimal without leading zeroes, and the first shell argument
12739 should not be a negative number.  In the following example, this snippet
12740 will print @samp{(2+3)*4 == 20}.
12742 @example
12743 bar=3
12744 AS_VAR_ARITH([foo], [\( 2 + $bar \) \* 4])
12745 echo "(2+$bar)*4 == $foo"
12746 @end example
12747 @end defmac
12749 @defmac AS_VAR_COPY (@var{dest}, @var{source})
12750 @asindex{VAR_COPY}
12751 Emit shell code to assign the contents of the polymorphic shell variable
12752 @var{source} to the polymorphic shell variable @var{dest}.  For example,
12753 executing this M4sh snippet will output @samp{bar hi}:
12755 @example
12756 foo=bar bar=hi
12757 AS_VAR_COPY([a], [foo])
12758 AS_VAR_COPY([b], [$foo])
12759 echo "$a $b"
12760 @end example
12762 When it is necessary to access the contents of an indirect variable
12763 inside a shell double-quoted context, the recommended idiom is to first
12764 copy the contents into a temporary literal shell variable.
12766 @smallexample
12767 for header in stdint_h inttypes_h ; do
12768   AS_VAR_COPY([var], [ac_cv_header_$header])
12769   echo "$header detected: $var"
12770 done
12771 @end smallexample
12772 @end defmac
12774 @comment AS_VAR_GET is intentionally undocumented; it can't handle
12775 @comment trailing newlines uniformly, and forks too much.
12777 @defmac AS_VAR_IF (@var{var}, @ovar{value}, @ovar{if-equal}, @
12778   @ovar{if-not-equal})
12779 @asindex{VAR_IF}
12780 Output a shell conditional statement.  If the contents of the
12781 polymorphic shell variable @var{var} match the string @var{value},
12782 execute @var{if-equal}; otherwise execute @var{if-not-equal}.  Avoids
12783 shell bugs if an interrupt signal arrives while a command substitution
12784 in @var{var} is being expanded.
12785 @end defmac
12787 @defmac AS_VAR_PUSHDEF (@var{m4-name}, @var{value})
12788 @defmacx AS_VAR_POPDEF (@var{m4-name})
12789 @asindex{VAR_PUSHDEF}
12790 @asindex{VAR_POPDEF}
12791 @cindex composing variable names
12792 @cindex variable names, composing
12793 A common M4sh idiom involves composing shell variable names from an m4
12794 argument (for example, writing a macro that uses a cache variable).
12795 @var{value} can be an arbitrary string, which will be transliterated
12796 into a valid shell name by @code{AS_TR_SH}.  In order to access the
12797 composed variable name based on @var{value}, it is easier to declare a
12798 temporary m4 macro @var{m4-name} with @code{AS_VAR_PUSHDEF}, then use
12799 that macro as the argument to subsequent @code{AS_VAR} macros as a
12800 polymorphic variable name, and finally free the temporary macro with
12801 @code{AS_VAR_POPDEF}.  These macros are often followed with @code{dnl},
12802 to avoid excess newlines in the output.
12804 Here is an involved example, that shows the power of writing macros that
12805 can handle composed shell variable names:
12807 @example
12808 m4_define([MY_CHECK_HEADER],
12809 [AS_VAR_PUSHDEF([my_Header], [ac_cv_header_$1])dnl
12810 AS_VAR_IF([my_Header], [yes], [echo "header $1 available"])dnl
12811 AS_VAR_POPDEF([my_Header])dnl
12813 MY_CHECK_HEADER([stdint.h])
12814 for header in inttypes.h stdlib.h ; do
12815   MY_CHECK_HEADER([$header])
12816 done
12817 @end example
12819 @noindent
12820 In the above example, @code{MY_CHECK_HEADER} can operate on polymorphic
12821 variable names.  In the first invocation, the m4 argument is
12822 @code{stdint.h}, which transliterates into a literal @code{stdint_h}.
12823 As a result, the temporary macro @code{my_Header} expands to the literal
12824 shell name @samp{ac_cv_header_stdint_h}.  In the second invocation, the
12825 m4 argument to @code{MY_CHECK_HEADER} is @code{$header}, and the
12826 temporary macro @code{my_Header} expands to the indirect shell name
12827 @samp{$as_my_Header}.  During the shell execution of the for loop, when
12828 @samp{$header} contains @samp{inttypes.h}, then @samp{$as_my_Header}
12829 contains @samp{ac_cv_header_inttypes_h}.  If this script is then run on a
12830 platform where all three headers have been previously detected, the
12831 output of the script will include:
12833 @smallexample
12834 header stdint.h detected
12835 header inttypes.h detected
12836 header stdlib.h detected
12837 @end smallexample
12838 @end defmac
12840 @defmac AS_VAR_SET (@var{var}, @ovar{value})
12841 @asindex{VAR_SET}
12842 Emit shell code to assign the contents of the polymorphic shell variable
12843 @var{var} to the shell expansion of @var{value}.  @var{value} is not
12844 subject to field splitting or file name expansion, so if command
12845 substitution is used, it may be done with @samp{`""`} rather than using
12846 an intermediate variable (@pxref{Shell Substitutions}).  However,
12847 @var{value} does undergo rescanning for additional macro names; behavior
12848 is unspecified if late expansion results in any shell meta-characters.
12849 @end defmac
12851 @defmac AS_VAR_SET_IF (@var{var}, @ovar{if-set}, @ovar{if-undef})
12852 @asindex{VAR_SET_IF}
12853 Emit a shell conditional statement, which executes @var{if-set} if the
12854 polymorphic shell variable @code{var} is set to any value, and
12855 @var{if-undef} otherwise.
12856 @end defmac
12858 @defmac AS_VAR_TEST_SET (@var{var})
12859 @asindex{VAR_TEST_SET}
12860 Emit a shell statement that results in a successful exit status only if
12861 the polymorphic shell variable @code{var} is set.
12862 @end defmac
12864 @node Initialization Macros
12865 @section Initialization Macros
12867 @defmac AS_BOURNE_COMPATIBLE
12868 @asindex{BOURNE_COMPATIBLE}
12869 Set up the shell to be more compatible with the Bourne shell as
12870 standardized by Posix, if possible.  This may involve setting
12871 environment variables, or setting options, or similar
12872 implementation-specific actions.  This macro is deprecated, since
12873 @code{AS_INIT} already invokes it.
12874 @end defmac
12876 @defmac AS_INIT
12877 @asindex{INIT}
12878 @evindex LC_ALL
12879 @evindex SHELL
12880 Initialize the M4sh environment.  This macro calls @code{m4_init}, then
12881 outputs the @code{#! /bin/sh} line, a notice about where the output was
12882 generated from, and code to sanitize the environment for the rest of the
12883 script.  Among other initializations, this sets @env{SHELL} to the shell
12884 chosen to run the script (@pxref{CONFIG_SHELL}), and @env{LC_ALL} to
12885 ensure the C locale.  Finally, it changes the current diversion to
12886 @code{BODY}.
12887 @end defmac
12889 @defmac AS_INIT_GENERATED (@var{file}, @ovar{comment})
12890 @asindex{INIT_GENERATED}
12891 Emit shell code to start the creation of a subsidiary shell script in
12892 @var{file}, including changing @var{file} to be executable.  This macro
12893 populates the child script with information learned from the parent
12894 (thus, the emitted code is equivalent in effect, but more efficient,
12895 than the code output by @code{AS_INIT}, @code{AS_BOURNE_COMPATIBLE}, and
12896 @code{AS_SHELL_SANITIZE}).  If present, @var{comment} is output near the
12897 beginning of the child, prior to the shell initialization code, and is
12898 subject to parameter expansion, command substitution, and backslash
12899 quote removal.  The
12900 parent script should check the exit status after this macro, in case
12901 @var{file} could not be properly created (for example, if the disk was
12902 full).  If successfully created, the parent script can then proceed to
12903 append additional M4sh constructs into the child script.
12905 Note that the child script starts life without a log file open, so if
12906 the parent script uses logging (@pxref{AS_MESSAGE_LOG_FD}), you
12907 must temporarily disable any attempts to use the log file until after
12908 emitting code to open a log within the child.  On the other hand, if the
12909 parent script has @code{AS_MESSAGE_FD} redirected somewhere besides
12910 @samp{1}, then the child script already has code that copies stdout to
12911 that descriptor.  Currently, the suggested
12912 idiom for writing a M4sh shell script from within another script is:
12914 @example
12915 AS_INIT_GENERATED([@var{file}], [[# My child script.
12916 ]]) || @{ AS_ECHO(["Failed to create child script"]); AS_EXIT; @}
12917 m4_pushdef([AS_MESSAGE_LOG_FD])dnl
12918 cat >> "@var{file}" <<\__EOF__
12919 # Code to initialize AS_MESSAGE_LOG_FD
12920 m4_popdef([AS_MESSAGE_LOG_FD])dnl
12921 # Additional code
12922 __EOF__
12923 @end example
12925 This, however, may change in the future as the M4sh interface is
12926 stabilized further.
12928 Also, be aware that use of @env{LINENO} within the child script may
12929 report line numbers relative to their location in the parent script,
12930 even when using @code{AS_LINENO_PREPARE}, if the parent script was
12931 unable to locate a shell with working @env{LINENO} support.
12932 @end defmac
12934 @defmac AS_LINENO_PREPARE
12935 @asindex{LINENO_PREPARE}
12936 @evindex LINENO
12937 Find a shell that supports the special variable @env{LINENO}, which
12938 contains the number of the currently executing line.  This macro is
12939 automatically invoked by @code{AC_INIT} in configure scripts.
12940 @end defmac
12942 @defmac AS_ME_PREPARE
12943 @asindex{ME_PREPARE}
12944 Set up variable @env{as_me} to be the basename of the currently executing
12945 script.  This macro is automatically invoked by @code{AC_INIT} in
12946 configure scripts.
12947 @end defmac
12949 @defmac AS_SHELL_SANITIZE
12950 @asindex{SHELL_SANITIZE}
12951 Initialize the shell suitably for @command{configure} scripts.  This has
12952 the effect of @code{AS_BOURNE_COMPATIBLE}, and sets some other
12953 environment variables for predictable results from configuration tests.
12954 For example, it sets @env{LC_ALL} to change to the default C locale.
12955 @xref{Special Shell Variables}.  This macro is deprecated, since
12956 @code{AS_INIT} already invokes it.
12957 @end defmac
12960 @node File Descriptor Macros
12961 @section File Descriptor Macros
12962 @cindex input
12963 @cindex standard input
12964 @cindex file descriptors
12965 @cindex descriptors
12966 @cindex low-level output
12967 @cindex output, low-level
12969 The following macros define file descriptors used to output messages
12970 (or input values) from @file{configure} scripts.
12971 For example:
12973 @example
12974 echo "$wombats found" >&AS_MESSAGE_LOG_FD
12975 echo 'Enter desired kangaroo count:' >&AS_MESSAGE_FD
12976 read kangaroos <&AS_ORIGINAL_STDIN_FD`
12977 @end example
12979 @noindent
12980 However doing so is seldom needed, because Autoconf provides higher
12981 level macros as described below.
12983 @defmac AS_MESSAGE_FD
12984 @asindex{MESSAGE_FD}
12985 The file descriptor for @samp{checking for...}  messages and results.
12986 By default, @code{AS_INIT} sets this to @samp{1} for standalone M4sh
12987 clients.  However, @code{AC_INIT} shuffles things around to another file
12988 descriptor, in order to allow the @option{-q} option of
12989 @command{configure} to choose whether messages should go to the script's
12990 standard output or be discarded.
12992 If you want to display some messages, consider using one of the printing
12993 macros (@pxref{Printing Messages}) instead.  Copies of messages output
12994 via these macros are also recorded in @file{config.log}.
12995 @end defmac
12997 @anchor{AS_MESSAGE_LOG_FD}
12998 @defmac AS_MESSAGE_LOG_FD
12999 @asindex{MESSAGE_LOG_FD}
13000 This must either be empty, or expand to a file descriptor for log
13001 messages.  By default, @code{AS_INIT} sets this macro to the empty
13002 string for standalone M4sh clients, thus disabling logging.  However,
13003 @code{AC_INIT} shuffles things around so that both @command{configure}
13004 and @command{config.status} use @file{config.log} for log messages.
13005 Macros that run tools, like @code{AC_COMPILE_IFELSE} (@pxref{Running the
13006 Compiler}), redirect all output to this descriptor.  You may want to do
13007 so if you develop such a low-level macro.
13008 @end defmac
13010 @defmac AS_ORIGINAL_STDIN_FD
13011 @asindex{ORIGINAL_STDIN_FD}
13012 This must expand to a file descriptor for the original standard input.
13013 By default, @code{AS_INIT} sets this macro to @samp{0} for standalone
13014 M4sh clients.  However, @code{AC_INIT} shuffles things around for
13015 safety.
13017 When @command{configure} runs, it may accidentally execute an
13018 interactive command that has the same name as the non-interactive meant
13019 to be used or checked.  If the standard input was the terminal, such
13020 interactive programs would cause @command{configure} to stop, pending
13021 some user input.  Therefore @command{configure} redirects its standard
13022 input from @file{/dev/null} during its initialization.  This is not
13023 normally a problem, since @command{configure} normally does not need
13024 user input.
13026 In the extreme case where your @file{configure} script really needs to
13027 obtain some values from the original standard input, you can read them
13028 explicitly from @code{AS_ORIGINAL_STDIN_FD}.
13029 @end defmac
13032 @c =================================================== Writing Autoconf Macros.
13034 @node Writing Autoconf Macros
13035 @chapter Writing Autoconf Macros
13037 When you write a feature test that could be applicable to more than one
13038 software package, the best thing to do is encapsulate it in a new macro.
13039 Here are some instructions and guidelines for writing Autoconf macros.
13041 @menu
13042 * Macro Definitions::           Basic format of an Autoconf macro
13043 * Macro Names::                 What to call your new macros
13044 * Reporting Messages::          Notifying @command{autoconf} users
13045 * Dependencies Between Macros::  What to do when macros depend on other macros
13046 * Obsoleting Macros::           Warning about old ways of doing things
13047 * Coding Style::                Writing Autoconf macros @`a la Autoconf
13048 @end menu
13050 @node Macro Definitions
13051 @section Macro Definitions
13053 @defmac AC_DEFUN (@var{name}, @ovar{body})
13054 @acindex{DEFUN}
13055 Autoconf macros are defined using the @code{AC_DEFUN} macro, which is
13056 similar to the M4 builtin @code{m4_define} macro; this creates a macro
13057 named @var{name} and with @var{body} as its expansion.  In addition to
13058 defining a macro, @code{AC_DEFUN} adds to it some code that is used to
13059 constrain the order in which macros are called, while avoiding redundant
13060 output (@pxref{Prerequisite Macros}).
13061 @end defmac
13063 An Autoconf macro definition looks like this:
13065 @example
13066 AC_DEFUN(@var{macro-name}, @var{macro-body})
13067 @end example
13069 You can refer to any arguments passed to the macro as @samp{$1},
13070 @samp{$2}, etc.  @xref{Definitions, , How to define new macros, m4.info,
13071 @acronym{GNU} M4}, for more complete information on writing M4 macros.
13073 Most macros fall in one of two general categories.  The first category
13074 includes macros which take arguments, in order to generate output
13075 parameterized by those arguments.  Macros in this category are designed
13076 to be directly expanded, often multiple times, and should not be used as
13077 the argument to @code{AC_REQUIRE}.  The other category includes macros
13078 which are shorthand for a fixed block of text, and therefore do not take
13079 arguments.  For this category of macros, directly expanding the macro
13080 multiple times results in redundant output, so it is more common to use
13081 the macro as the argument to @code{AC_REQUIRE}, or to declare the macro
13082 with @code{AC_DEFUN_ONCE} (@pxref{One-Shot Macros}).
13084 Be sure to properly quote both the @var{macro-body} @emph{and} the
13085 @var{macro-name} to avoid any problems if the macro happens to have
13086 been previously defined.
13088 Each macro should have a header comment that gives its prototype, and a
13089 brief description.  When arguments have default values, display them in
13090 the prototype.  For example:
13092 @example
13093 # AC_MSG_ERROR(ERROR, [EXIT-STATUS = 1])
13094 # --------------------------------------
13095 m4_define([AC_MSG_ERROR],
13096   [@{ AS_MESSAGE([error: $1], [2])
13097      exit m4_default([$2], [1]); @}])
13098 @end example
13100 Comments about the macro should be left in the header comment.  Most
13101 other comments make their way into @file{configure}, so just keep
13102 using @samp{#} to introduce comments.
13104 @cindex @code{dnl}
13105 If you have some special comments about pure M4 code, comments
13106 that make no sense in @file{configure} and in the header comment, then
13107 use the builtin @code{dnl}: it causes M4 to discard the text
13108 through the next newline.
13110 Keep in mind that @code{dnl} is rarely needed to introduce comments;
13111 @code{dnl} is more useful to get rid of the newlines following macros
13112 that produce no output, such as @code{AC_REQUIRE}.
13114 Public third-party macros need to use @code{AC_DEFUN}, and not
13115 @code{m4_define}, in order to be found by @command{aclocal}
13116 (@pxref{Extending aclocal,,, automake, @acronym{GNU} Automake}).
13117 Additionally, if it is ever determined that a macro should be made
13118 obsolete, it is easy to convert from @code{AC_DEFUN} to @code{AU_DEFUN}
13119 in order to have @command{autoupdate} assist the user in choosing a
13120 better alternative, but there is no corresponding way to make
13121 @code{m4_define} issue an upgrade notice (@pxref{AU_DEFUN}).
13123 There is another subtle, but important, difference between using
13124 @code{m4_define} and @code{AC_DEFUN}: only the former is unaffected by
13125 @code{AC_REQUIRE}.  When writing a file, it is always safe to replace a
13126 block of text with a @code{m4_define} macro that will expand to the same
13127 text.  But replacing a block of text with an @code{AC_DEFUN} macro with
13128 the same content does not necessarily give the same results, because it
13129 changes the location where any embedded but unsatisfied
13130 @code{AC_REQUIRE} invocations within the block will be expanded.  For an
13131 example of this, see @ref{Expanded Before Required}.
13133 @node Macro Names
13134 @section Macro Names
13136 All of the public Autoconf macros have all-uppercase names in the
13137 namespace @samp{^AC_} to prevent them from accidentally conflicting with
13138 other text; Autoconf also reserves the namespace @samp{^_AC_} for
13139 internal macros.  All shell variables that they use for internal
13140 purposes have mostly-lowercase names starting with @samp{ac_}.  Autoconf
13141 also uses here-document delimiters in the namespace @samp{^_AC[A-Z]}.  During
13142 @command{configure}, files produced by Autoconf make heavy use of the
13143 file system namespace @samp{^conf}.
13145 Since Autoconf is built on top of M4sugar (@pxref{Programming in
13146 M4sugar}) and M4sh (@pxref{Programming in M4sh}), you must also be aware
13147 of those namespaces (@samp{^_?\(m4\|AS\)_}).  And since
13148 @file{configure.ac} is also designed to be scanned by Autoheader,
13149 Autoscan, Autoupdate, and Automake, you should be aware of the
13150 @samp{^_?A[HNUM]_} namespaces.  In general, you @emph{should not use}
13151 the namespace of a package that does not own the macro or shell code you
13152 are writing.
13154 To ensure that your macros don't conflict with present or future
13155 Autoconf macros, you should prefix your own macro names and any shell
13156 variables they use with some other sequence.  Possibilities include your
13157 initials, or an abbreviation for the name of your organization or
13158 software package.  Historically, people have not always followed the
13159 rule of using a namespace appropriate for their package, and this has
13160 made it difficult for determining the origin of a macro (and where to
13161 report bugs about that macro), as well as difficult for the true
13162 namespace owner to add new macros without interference from pre-existing
13163 uses of third-party macros.  Perhaps the best example of this confusion
13164 is the @code{AM_GNU_GETTEXT} macro, which belongs, not to Automake, but
13165 to Gettext.
13167 Most of the Autoconf macros' names follow a structured naming convention
13168 that indicates the kind of feature check by the name.  The macro names
13169 consist of several words, separated by underscores, going from most
13170 general to most specific.  The names of their cache variables use the
13171 same convention (@pxref{Cache Variable Names}, for more information on
13172 them).
13174 The first word of the name after the namespace initials (such as
13175 @samp{AC_}) usually tells the category
13176 of the feature being tested.  Here are the categories used in Autoconf for
13177 specific test macros, the kind of macro that you are more likely to
13178 write.  They are also used for cache variables, in all-lowercase.  Use
13179 them where applicable; where they're not, invent your own categories.
13181 @table @code
13182 @item C
13183 C language builtin features.
13184 @item DECL
13185 Declarations of C variables in header files.
13186 @item FUNC
13187 Functions in libraries.
13188 @item GROUP
13189 Posix group owners of files.
13190 @item HEADER
13191 Header files.
13192 @item LIB
13193 C libraries.
13194 @item PROG
13195 The base names of programs.
13196 @item MEMBER
13197 Members of aggregates.
13198 @item SYS
13199 Operating system features.
13200 @item TYPE
13201 C builtin or declared types.
13202 @item VAR
13203 C variables in libraries.
13204 @end table
13206 After the category comes the name of the particular feature being
13207 tested.  Any further words in the macro name indicate particular aspects
13208 of the feature.  For example, @code{AC_PROG_CC_STDC} checks whether the
13209 C compiler supports @acronym{ISO} Standard C.
13211 An internal macro should have a name that starts with an underscore;
13212 Autoconf internals should therefore start with @samp{_AC_}.
13213 Additionally, a macro that is an internal subroutine of another macro
13214 should have a name that starts with an underscore and the name of that
13215 other macro, followed by one or more words saying what the internal
13216 macro does.  For example, @code{AC_PATH_X} has internal macros
13217 @code{_AC_PATH_X_XMKMF} and @code{_AC_PATH_X_DIRECT}.
13219 @node Reporting Messages
13220 @section Reporting Messages
13221 @cindex Messages, from @command{autoconf}
13223 When macros statically diagnose abnormal situations, benign or fatal, it
13224 is possible to make @command{autoconf} detect the problem, and refuse to
13225 create @file{configure} in the case of an error.  The macros in this
13226 section are considered obsolescent, and new code should use M4sugar
13227 macros for this purpose, see @ref{Diagnostic Macros}.
13229 On the other hand, it is possible to want to detect errors when
13230 @command{configure} is run, which are dependent on the environment of
13231 the user rather than the maintainer.  For dynamic diagnostics, see
13232 @ref{Printing Messages}.
13234 @defmac AC_DIAGNOSE (@var{category}, @var{message})
13235 @acindex{DIAGNOSE}
13236 Report @var{message} as a warning (or as an error if requested by the
13237 user) if warnings of the @var{category} are turned on.  This macro is
13238 obsolescent; you are encouraged to use:
13239 @example
13240 m4_warn([@var{category}], [@var{message}])
13241 @end example
13242 @noindent
13243 instead.  @xref{m4_warn}, for more details, including valid
13244 @var{category} names.
13245 @end defmac
13247 @defmac AC_WARNING (@var{message})
13248 @acindex{WARNING}
13249 Report @var{message} as a syntax warning.  This macro is obsolescent;
13250 you are encouraged to use:
13251 @example
13252 m4_warn([syntax], [@var{message}])
13253 @end example
13254 @noindent
13255 instead.  @xref{m4_warn}, for more details, as well as better
13256 finer-grained categories of warnings (not all problems have to do with
13257 syntax).
13258 @end defmac
13260 @defmac AC_FATAL (@var{message})
13261 @acindex{FATAL}
13262 Report a severe error @var{message}, and have @command{autoconf} die.
13263 This macro is obsolescent; you are encouraged to use:
13264 @example
13265 m4_fatal([@var{message}])
13266 @end example
13267 @noindent
13268 instead.  @xref{m4_fatal}, for more details.
13269 @end defmac
13271 When the user runs @samp{autoconf -W error}, warnings from
13272 @code{m4_warn} (including those issued through @code{AC_DIAGNOSE} and
13273 @code{AC_WARNING}) are reported as errors, see @ref{autoconf Invocation}.
13275 @node Dependencies Between Macros
13276 @section Dependencies Between Macros
13277 @cindex Dependencies between macros
13279 Some Autoconf macros depend on other macros having been called first in
13280 order to work correctly.  Autoconf provides a way to ensure that certain
13281 macros are called if needed and a way to warn the user if macros are
13282 called in an order that might cause incorrect operation.
13284 @menu
13285 * Prerequisite Macros::         Ensuring required information
13286 * Suggested Ordering::          Warning about possible ordering problems
13287 * One-Shot Macros::             Ensuring a macro is called only once
13288 @end menu
13290 @node Prerequisite Macros
13291 @subsection Prerequisite Macros
13292 @cindex Prerequisite macros
13293 @cindex Macros, prerequisites
13295 A macro that you write might need to use values that have previously
13296 been computed by other macros.  For example, @code{AC_DECL_YYTEXT}
13297 examines the output of @code{flex} or @code{lex}, so it depends on
13298 @code{AC_PROG_LEX} having been called first to set the shell variable
13299 @code{LEX}.
13301 Rather than forcing the user of the macros to keep track of the
13302 dependencies between them, you can use the @code{AC_REQUIRE} macro to do
13303 it automatically.  @code{AC_REQUIRE} can ensure that a macro is only
13304 called if it is needed, and only called once.
13306 @defmac AC_REQUIRE (@var{macro-name})
13307 @acindex{REQUIRE}
13308 If the M4 macro @var{macro-name} has not already been called, call it
13309 (without any arguments).  Make sure to quote @var{macro-name} with
13310 square brackets.  @var{macro-name} must have been defined using
13311 @code{AC_DEFUN} or else contain a call to @code{AC_PROVIDE} to indicate
13312 that it has been called.
13314 @code{AC_REQUIRE} must be used inside a macro defined by @code{AC_DEFUN}; it
13315 must not be called from the top level.  Also, it does not make sense to
13316 require a macro that takes parameters.
13317 @end defmac
13319 @code{AC_REQUIRE} is often misunderstood.  It really implements
13320 dependencies between macros in the sense that if one macro depends upon
13321 another, the latter is expanded @emph{before} the body of the
13322 former.  To be more precise, the required macro is expanded before
13323 the outermost defined macro in the current expansion stack.
13324 In particular, @samp{AC_REQUIRE([FOO])} is not replaced with the body of
13325 @code{FOO}.  For instance, this definition of macros:
13327 @example
13328 @group
13329 AC_DEFUN([TRAVOLTA],
13330 [test "$body_temperature_in_celsius" -gt "38" &&
13331   dance_floor=occupied])
13332 AC_DEFUN([NEWTON_JOHN],
13333 [test "x$hair_style" = xcurly &&
13334   dance_floor=occupied])
13335 @end group
13337 @group
13338 AC_DEFUN([RESERVE_DANCE_FLOOR],
13339 [if date | grep '^Sat.*pm' >/dev/null 2>&1; then
13340   AC_REQUIRE([TRAVOLTA])
13341   AC_REQUIRE([NEWTON_JOHN])
13342 fi])
13343 @end group
13344 @end example
13346 @noindent
13347 with this @file{configure.ac}
13349 @example
13350 AC_INIT([Dance Manager], [1.0], [bug-dance@@example.org])
13351 RESERVE_DANCE_FLOOR
13352 if test "x$dance_floor" = xoccupied; then
13353   AC_MSG_ERROR([cannot pick up here, let's move])
13355 @end example
13357 @noindent
13358 does not leave you with a better chance to meet a kindred soul at
13359 other times than Saturday night since it expands into:
13361 @example
13362 @group
13363 test "$body_temperature_in_Celsius" -gt "38" &&
13364   dance_floor=occupied
13365 test "x$hair_style" = xcurly &&
13366   dance_floor=occupied
13368 if date | grep '^Sat.*pm' >/dev/null 2>&1; then
13372 @end group
13373 @end example
13375 This behavior was chosen on purpose: (i) it prevents messages in
13376 required macros from interrupting the messages in the requiring macros;
13377 (ii) it avoids bad surprises when shell conditionals are used, as in:
13379 @example
13380 @group
13381 if @dots{}; then
13382   AC_REQUIRE([SOME_CHECK])
13384 @dots{}
13385 SOME_CHECK
13386 @end group
13387 @end example
13389 However, this implementation can lead to another class of problems.
13390 Consider the case where an outer macro first expands, then indirectly
13391 requires, an inner macro:
13393 @example
13394 AC_DEFUN([TESTA], [[echo in A
13395 if test -n "$SEEN_A" ; then echo duplicate ; fi
13396 SEEN_A=:]])
13397 AC_DEFUN([TESTB], [AC_REQUIRE([TESTA])[echo in B
13398 if test -z "$SEEN_A" ; then echo bug ; fi]])
13399 AC_DEFUN([TESTC], [AC_REQUIRE([TESTB])[echo in C]])
13400 AC_DEFUN([OUTER], [[echo in OUTER]
13403 OUTER
13404 @end example
13406 @noindent
13407 Prior to Autoconf 2.64, the implementation of @code{AC_REQUIRE}
13408 recognized that @code{TESTB} needed to be hoisted prior to the expansion
13409 of @code{OUTER}, but because @code{TESTA} had already been directly
13410 expanded, it failed to hoist @code{TESTA}.  Therefore, the expansion of
13411 @code{TESTB} occurs prior to its prerequisites, leading to the following
13412 output:
13414 @example
13415 in B
13417 in OUTER
13418 in A
13419 in C
13420 @end example
13422 @noindent
13423 Newer Autoconf is smart enough to recognize this situation, and hoists
13424 @code{TESTA} even though it has already been expanded, but issues a
13425 syntax warning in the process.  This is because the hoisted expansion of
13426 @code{TESTA} defeats the purpose of using @code{AC_REQUIRE} to avoid
13427 redundant code, and causes its own set of problems if the hoisted macro
13428 is not idempotent:
13430 @example
13431 in A
13432 in B
13433 in OUTER
13434 in A
13435 duplicate
13436 in C
13437 @end example
13439 The bug is not in Autoconf, but in the macro definitions.  If you ever
13440 pass a particular macro name to @code{AC_REQUIRE}, then you are implying
13441 that the macro only needs to be expanded once.  But to enforce this,
13442 either the macro must be declared with @code{AC_DEFUN_ONCE} (although
13443 this only helps in Autoconf 2.64 or newer), or all
13444 uses of that macro should be through @code{AC_REQUIRE}; directly
13445 expanding the macro defeats the point of using @code{AC_REQUIRE} to
13446 eliminate redundant expansion.  In the example, this rule of thumb was
13447 violated because @code{TESTB} requires @code{TESTA} while @code{OUTER}
13448 directly expands it.  One way of fixing the bug is to factor
13449 @code{TESTA} into two macros, the portion designed for direct and
13450 repeated use (here, named @code{TESTA}), and the portion designed for
13451 one-shot output and used only inside @code{AC_REQUIRE} (here, named
13452 @code{TESTA_PREREQ}).  Then, by fixing all clients to use the correct
13453 calling convention according to their needs:
13455 @example
13456 AC_DEFUN([TESTA], [AC_REQUIRE([TESTA_PREREQ])[echo in A]])
13457 AC_DEFUN([TESTA_PREREQ], [[echo in A_PREREQ
13458 if test -n "$SEEN_A" ; then echo duplicate ; fi
13459 SEEN_A=:]])
13460 AC_DEFUN([TESTB], [AC_REQUIRE([TESTA_PREREQ])[echo in B
13461 if test -z "$SEEN_A" ; then echo bug ; fi]])
13462 AC_DEFUN([TESTC], [AC_REQUIRE([TESTB])[echo in C]])
13463 AC_DEFUN([OUTER], [[echo in OUTER]
13464 TESTA
13465 TESTC])
13466 OUTER
13467 @end example
13469 @noindent
13470 the resulting output will then obey all dependency rules and avoid any
13471 syntax warnings, whether the script is built with old or new Autoconf
13472 versions:
13474 @example
13475 in A_PREREQ
13476 in B
13477 in OUTER
13478 in A
13479 in C
13480 @end example
13482 The helper macros @code{AS_IF} and @code{AS_CASE} may be used to
13483 enforce expansion of required macros outside of shell conditional
13484 constructs.  You are furthermore encouraged, although not required, to
13485 put all @code{AC_REQUIRE} calls
13486 at the beginning of a macro.  You can use @code{dnl} to avoid the empty
13487 lines they leave.
13489 @node Suggested Ordering
13490 @subsection Suggested Ordering
13491 @cindex Macros, ordering
13492 @cindex Ordering macros
13494 Some macros should be run before another macro if both are called, but
13495 neither @emph{requires} that the other be called.  For example, a macro
13496 that changes the behavior of the C compiler should be called before any
13497 macros that run the C compiler.  Many of these dependencies are noted in
13498 the documentation.
13500 Autoconf provides the @code{AC_BEFORE} macro to warn users when macros
13501 with this kind of dependency appear out of order in a
13502 @file{configure.ac} file.  The warning occurs when creating
13503 @command{configure} from @file{configure.ac}, not when running
13504 @command{configure}.
13506 For example, @code{AC_PROG_CPP} checks whether the C compiler
13507 can run the C preprocessor when given the @option{-E} option.  It should
13508 therefore be called after any macros that change which C compiler is
13509 being used, such as @code{AC_PROG_CC}.  So @code{AC_PROG_CC} contains:
13511 @example
13512 AC_BEFORE([$0], [AC_PROG_CPP])dnl
13513 @end example
13515 @noindent
13516 This warns the user if a call to @code{AC_PROG_CPP} has already occurred
13517 when @code{AC_PROG_CC} is called.
13519 @defmac AC_BEFORE (@var{this-macro-name}, @var{called-macro-name})
13520 @acindex{BEFORE}
13521 Make M4 print a warning message to the standard error output if
13522 @var{called-macro-name} has already been called.  @var{this-macro-name}
13523 should be the name of the macro that is calling @code{AC_BEFORE}.  The
13524 macro @var{called-macro-name} must have been defined using
13525 @code{AC_DEFUN} or else contain a call to @code{AC_PROVIDE} to indicate
13526 that it has been called.
13527 @end defmac
13529 @node One-Shot Macros
13530 @subsection One-Shot Macros
13531 @cindex One-shot macros
13532 @cindex Macros, called once
13534 Some macros should be called only once, either because calling them
13535 multiple time is unsafe, or because it is bad style.  For instance
13536 Autoconf ensures that @code{AC_CANONICAL_BUILD} and cousins
13537 (@pxref{Canonicalizing}) are evaluated only once, because it makes no
13538 sense to run these expensive checks more than once.  Such one-shot
13539 macros can be defined using @code{AC_DEFUN_ONCE}.
13541 @defmac AC_DEFUN_ONCE (@var{macro-name}, @var{macro-body})
13542 @acindex{DEFUN_ONCE}
13543 Declare macro @var{macro-name} like @code{AC_DEFUN} would (@pxref{Macro
13544 Definitions}), but add additional logic that guarantees that only the
13545 first use of the macro (whether by direct expansion or
13546 @code{AC_REQUIRE}) causes an expansion of @var{macro-body}; the
13547 expansion will occur before the start of any enclosing macro defined by
13548 @code{AC_DEFUN}.  Subsequent expansions are silently ignored.
13549 Generally, it does not make sense for @var{macro-body} to use parameters
13550 such as @code{$1}.
13551 @end defmac
13553 Prior to Autoconf 2.64, a macro defined by @code{AC_DEFUN_ONCE} would
13554 emit a warning if it was directly expanded a second time, so for
13555 portability, it is better to use @code{AC_REQUIRE} than direct
13556 invocation of @var{macro-name} inside a macro defined by @code{AC_DEFUN}
13557 (@pxref{Prerequisite Macros}).
13559 @node Obsoleting Macros
13560 @section Obsoleting Macros
13561 @cindex Obsoleting macros
13562 @cindex Macros, obsoleting
13564 Configuration and portability technology has evolved over the years.
13565 Often better ways of solving a particular problem are developed, or
13566 ad-hoc approaches are systematized.  This process has occurred in many
13567 parts of Autoconf.  One result is that some of the macros are now
13568 considered @dfn{obsolete}; they still work, but are no longer considered
13569 the best thing to do, hence they should be replaced with more modern
13570 macros.  Ideally, @command{autoupdate} should replace the old macro calls
13571 with their modern implementation.
13573 Autoconf provides a simple means to obsolete a macro.
13575 @anchor{AU_DEFUN}
13576 @defmac AU_DEFUN (@var{old-macro}, @var{implementation}, @ovar{message})
13577 @auindex{DEFUN}
13578 Define @var{old-macro} as @var{implementation}.  The only difference
13579 with @code{AC_DEFUN} is that the user is warned that
13580 @var{old-macro} is now obsolete.
13582 If she then uses @command{autoupdate}, the call to @var{old-macro} is
13583 replaced by the modern @var{implementation}.  @var{message} should
13584 include information on what to do after running @command{autoupdate};
13585 @command{autoupdate} prints it as a warning, and includes it
13586 in the updated @file{configure.ac} file.
13588 The details of this macro are hairy: if @command{autoconf} encounters an
13589 @code{AU_DEFUN}ed macro, all macros inside its second argument are expanded
13590 as usual.  However, when @command{autoupdate} is run, only M4 and M4sugar
13591 macros are expanded here, while all other macros are disabled and
13592 appear literally in the updated @file{configure.ac}.
13593 @end defmac
13595 @defmac AU_ALIAS (@var{old-name}, @var{new-name})
13596 @auindex{ALIAS}
13597 Used if the @var{old-name} is to be replaced by a call to @var{new-macro}
13598 with the same parameters.  This happens for example if the macro was renamed.
13599 @end defmac
13601 @node Coding Style
13602 @section Coding Style
13603 @cindex Coding style
13605 The Autoconf macros follow a strict coding style.  You are encouraged to
13606 follow this style, especially if you intend to distribute your macro,
13607 either by contributing it to Autoconf itself, or via other means.
13609 The first requirement is to pay great attention to the quotation.  For
13610 more details, see @ref{Autoconf Language}, and @ref{M4 Quotation}.
13612 Do not try to invent new interfaces.  It is likely that there is a macro
13613 in Autoconf that resembles the macro you are defining: try to stick to
13614 this existing interface (order of arguments, default values, etc.).  We
13615 @emph{are} conscious that some of these interfaces are not perfect;
13616 nevertheless, when harmless, homogeneity should be preferred over
13617 creativity.
13619 Be careful about clashes both between M4 symbols and between shell
13620 variables.
13622 If you stick to the suggested M4 naming scheme (@pxref{Macro Names}),
13623 you are unlikely to generate conflicts.  Nevertheless, when you need to
13624 set a special value, @emph{avoid using a regular macro name}; rather,
13625 use an ``impossible'' name.  For instance, up to version 2.13, the macro
13626 @code{AC_SUBST} used to remember what @var{symbol} macros were already defined
13627 by setting @code{AC_SUBST_@var{symbol}}, which is a regular macro name.
13628 But since there is a macro named @code{AC_SUBST_FILE}, it was just
13629 impossible to @samp{AC_SUBST(FILE)}!  In this case,
13630 @code{AC_SUBST(@var{symbol})} or @code{_AC_SUBST(@var{symbol})} should
13631 have been used (yes, with the parentheses).
13632 @c or better yet, high-level macros such as @code{m4_expand_once}
13634 No Autoconf macro should ever enter the user-variable name space; i.e.,
13635 except for the variables that are the actual result of running the
13636 macro, all shell variables should start with @code{ac_}.  In
13637 addition, small macros or any macro that is likely to be embedded in
13638 other macros should be careful not to use obvious names.
13640 @cindex @code{dnl}
13641 Do not use @code{dnl} to introduce comments: most of the comments you
13642 are likely to write are either header comments which are not output
13643 anyway, or comments that should make their way into @file{configure}.
13644 There are exceptional cases where you do want to comment special M4
13645 constructs, in which case @code{dnl} is right, but keep in mind that it
13646 is unlikely.
13648 M4 ignores the leading blanks and newlines before each argument.
13649 Use this feature to
13650 indent in such a way that arguments are (more or less) aligned with the
13651 opening parenthesis of the macro being called.  For instance, instead of
13653 @example
13654 AC_CACHE_CHECK(for EMX OS/2 environment,
13655 ac_cv_emxos2,
13656 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM(, [return __EMX__;])],
13657 [ac_cv_emxos2=yes], [ac_cv_emxos2=no])])
13658 @end example
13660 @noindent
13661 write
13663 @example
13664 AC_CACHE_CHECK([for EMX OS/2 environment], [ac_cv_emxos2],
13665 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([], [return __EMX__;])],
13666                    [ac_cv_emxos2=yes],
13667                    [ac_cv_emxos2=no])])
13668 @end example
13670 @noindent
13671 or even
13673 @example
13674 AC_CACHE_CHECK([for EMX OS/2 environment],
13675                [ac_cv_emxos2],
13676                [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([],
13677                                                    [return __EMX__;])],
13678                                   [ac_cv_emxos2=yes],
13679                                   [ac_cv_emxos2=no])])
13680 @end example
13682 When using @code{AC_RUN_IFELSE} or any macro that cannot work when
13683 cross-compiling, provide a pessimistic value (typically @samp{no}).
13685 Feel free to use various tricks to prevent auxiliary tools, such as
13686 syntax-highlighting editors, from behaving improperly.  For instance,
13687 instead of:
13689 @example
13690 m4_bpatsubst([$1], [$"])
13691 @end example
13693 @noindent
13696 @example
13697 m4_bpatsubst([$1], [$""])
13698 @end example
13700 @noindent
13701 so that Emacsen do not open an endless ``string'' at the first quote.
13702 For the same reasons, avoid:
13704 @example
13705 test $[#] != 0
13706 @end example
13708 @noindent
13709 and use:
13711 @example
13712 test $[@@%:@@] != 0
13713 @end example
13715 @noindent
13716 Otherwise, the closing bracket would be hidden inside a @samp{#}-comment,
13717 breaking the bracket-matching highlighting from Emacsen.  Note the
13718 preferred style to escape from M4: @samp{$[1]}, @samp{$[@@]}, etc.  Do
13719 not escape when it is unnecessary.  Common examples of useless quotation
13720 are @samp{[$]$1} (write @samp{$$1}), @samp{[$]var} (use @samp{$var}),
13721 etc.  If you add portability issues to the picture, you'll prefer
13722 @samp{$@{1+"$[@@]"@}} to @samp{"[$]@@"}, and you'll prefer do something
13723 better than hacking Autoconf @code{:-)}.
13725 When using @command{sed}, don't use @option{-e} except for indenting
13726 purposes.  With the @code{s} and @code{y} commands, the preferred
13727 separator is @samp{/} unless @samp{/} itself might appear in the pattern
13728 or replacement, in which case you should use @samp{|}, or optionally
13729 @samp{,} if you know the pattern and replacement cannot contain a file
13730 name.  If none of these characters will do, choose a printable character
13731 that cannot appear in the pattern or replacement.  Characters from the
13732 set @samp{"#$&'()*;<=>?`|~} are good choices if the pattern or
13733 replacement might contain a file name, since they have special meaning
13734 to the shell and are less likely to occur in file names.
13736 @xref{Macro Definitions}, for details on how to define a macro.  If a
13737 macro doesn't use @code{AC_REQUIRE}, is expected to never be the object
13738 of an @code{AC_REQUIRE} directive, and macros required by other macros
13739 inside arguments do not need to be expanded before this macro, then
13740 use @code{m4_define}.  In case of doubt, use @code{AC_DEFUN}.
13741 Also take into account that public third-party macros need to use
13742 @code{AC_DEFUN} in order to be found by @command{aclocal}
13743 (@pxref{Extending aclocal,,, automake, @acronym{GNU} Automake}).
13744 All the @code{AC_REQUIRE} statements should be at the beginning of the
13745 macro, and each statement should be followed by @code{dnl}.
13747 You should not rely on the number of arguments: instead of checking
13748 whether an argument is missing, test that it is not empty.  It provides
13749 both a simpler and a more predictable interface to the user, and saves
13750 room for further arguments.
13752 Unless the macro is short, try to leave the closing @samp{])} at the
13753 beginning of a line, followed by a comment that repeats the name of the
13754 macro being defined.  This introduces an additional newline in
13755 @command{configure}; normally, that is not a problem, but if you want to
13756 remove it you can use @samp{[]dnl} on the last line.  You can similarly
13757 use @samp{[]dnl} after a macro call to remove its newline.  @samp{[]dnl}
13758 is recommended instead of @samp{dnl} to ensure that M4 does not
13759 interpret the @samp{dnl} as being attached to the preceding text or
13760 macro output.  For example, instead of:
13762 @example
13763 AC_DEFUN([AC_PATH_X],
13764 [AC_MSG_CHECKING([for X])
13765 AC_REQUIRE_CPP()
13766 @r{# @dots{}omitted@dots{}}
13767   AC_MSG_RESULT([libraries $x_libraries, headers $x_includes])
13768 fi])
13769 @end example
13771 @noindent
13772 you would write:
13774 @example
13775 AC_DEFUN([AC_PATH_X],
13776 [AC_REQUIRE_CPP()[]dnl
13777 AC_MSG_CHECKING([for X])
13778 @r{# @dots{}omitted@dots{}}
13779   AC_MSG_RESULT([libraries $x_libraries, headers $x_includes])
13780 fi[]dnl
13781 ])# AC_PATH_X
13782 @end example
13784 If the macro is long, try to split it into logical chunks.  Typically,
13785 macros that check for a bug in a function and prepare its
13786 @code{AC_LIBOBJ} replacement should have an auxiliary macro to perform
13787 this setup.  Do not hesitate to introduce auxiliary macros to factor
13788 your code.
13790 In order to highlight the recommended coding style, here is a macro
13791 written the old way:
13793 @example
13794 dnl Check for EMX on OS/2.
13795 dnl _AC_EMXOS2
13796 AC_DEFUN(_AC_EMXOS2,
13797 [AC_CACHE_CHECK(for EMX OS/2 environment, ac_cv_emxos2,
13798 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM(, return __EMX__;)],
13799 ac_cv_emxos2=yes, ac_cv_emxos2=no)])
13800 test "x$ac_cv_emxos2" = xyes && EMXOS2=yes])
13801 @end example
13803 @noindent
13804 and the new way:
13806 @example
13807 # _AC_EMXOS2
13808 # ----------
13809 # Check for EMX on OS/2.
13810 m4_define([_AC_EMXOS2],
13811 [AC_CACHE_CHECK([for EMX OS/2 environment], [ac_cv_emxos2],
13812 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([], [return __EMX__;])],
13813                    [ac_cv_emxos2=yes],
13814                    [ac_cv_emxos2=no])])
13815 test "x$ac_cv_emxos2" = xyes && EMXOS2=yes[]dnl
13816 ])# _AC_EMXOS2
13817 @end example
13822 @c ============================================= Portable Shell Programming
13824 @node Portable Shell
13825 @chapter Portable Shell Programming
13826 @cindex Portable shell programming
13828 When writing your own checks, there are some shell-script programming
13829 techniques you should avoid in order to make your code portable.  The
13830 Bourne shell and upward-compatible shells like the Korn shell and Bash
13831 have evolved over the years, and many features added to the original
13832 System7 shell are now supported on all interesting porting targets.
13833 However, the following discussion between Russ Allbery and Robert Lipe
13834 is worth reading:
13836 @noindent
13837 Russ Allbery:
13839 @quotation
13840 The @acronym{GNU} assumption that @command{/bin/sh} is the one and only shell
13841 leads to a permanent deadlock.  Vendors don't want to break users'
13842 existing shell scripts, and there are some corner cases in the Bourne
13843 shell that are not completely compatible with a Posix shell.  Thus,
13844 vendors who have taken this route will @emph{never} (OK@dots{}``never say
13845 never'') replace the Bourne shell (as @command{/bin/sh}) with a
13846 Posix shell.
13847 @end quotation
13849 @noindent
13850 Robert Lipe:
13852 @quotation
13853 This is exactly the problem.  While most (at least most System V's) do
13854 have a Bourne shell that accepts shell functions most vendor
13855 @command{/bin/sh} programs are not the Posix shell.
13857 So while most modern systems do have a shell @emph{somewhere} that meets the
13858 Posix standard, the challenge is to find it.
13859 @end quotation
13861 For this reason, part of the job of M4sh (@pxref{Programming in M4sh})
13862 is to find such a shell.  But to prevent trouble, if you're not using
13863 M4sh you should not take advantage of features that were added after Unix
13864 version 7, circa 1977 (@pxref{Systemology}); you should not use aliases,
13865 negated character classes, or even @command{unset}.  @code{#} comments,
13866 while not in Unix version 7, were retrofitted in the original Bourne
13867 shell and can be assumed to be part of the least common denominator.
13869 On the other hand, if you're using M4sh you can assume that the shell
13870 has the features that were added in SVR2 (circa 1984), including shell
13871 functions,
13872 @command{return}, @command{unset}, and I/O redirection for builtins.  For
13873 more information, refer to @uref{http://@/www.in-ulm.de/@/~mascheck/@/bourne/}.
13874 However, some pitfalls have to be avoided for portable use of these
13875 constructs; these will be documented in the rest of this chapter.
13876 See in particular @ref{Shell Functions} and @ref{Limitations of
13877 Builtins, , Limitations of Shell Builtins}.
13879 Some ancient systems have quite
13880 small limits on the length of the @samp{#!} line; for instance, 32
13881 bytes (not including the newline) on SunOS 4.
13882 However, these ancient systems are no longer of practical concern.
13884 The set of external programs you should run in a @command{configure} script
13885 is fairly small.  @xref{Utilities in Makefiles, , Utilities in
13886 Makefiles, standards, @acronym{GNU} Coding Standards}, for the list.  This
13887 restriction allows users to start out with a fairly small set of
13888 programs and build the rest, avoiding too many interdependencies between
13889 packages.
13891 Some of these external utilities have a portable subset of features; see
13892 @ref{Limitations of Usual Tools}.
13894 There are other sources of documentation about shells.  The
13895 specification for the Posix
13896 @uref{http://@/www.opengroup.org/@/susv3/@/utilities/@/xcu_chap02@/.html, Shell
13897 Command Language}, though more generous than the restrictive shell
13898 subset described above, is fairly portable nowadays.  Also please see
13899 @uref{http://@/www.faqs.org/@/faqs/@/unix-faq/@/shell/, the Shell FAQs}.
13901 @menu
13902 * Shellology::                  A zoology of shells
13903 * Here-Documents::              Quirks and tricks
13904 * File Descriptors::            FDs and redirections
13905 * File System Conventions::     File names
13906 * Shell Pattern Matching::      Pattern matching
13907 * Shell Substitutions::         Variable and command expansions
13908 * Assignments::                 Varying side effects of assignments
13909 * Parentheses::                 Parentheses in shell scripts
13910 * Slashes::                     Slashes in shell scripts
13911 * Special Shell Variables::     Variables you should not change
13912 * Shell Functions::             What to look out for if you use them
13913 * Limitations of Builtins::     Portable use of not so portable /bin/sh
13914 * Limitations of Usual Tools::  Portable use of portable tools
13915 @end menu
13917 @node Shellology
13918 @section Shellology
13919 @cindex Shellology
13921 There are several families of shells, most prominently the Bourne family
13922 and the C shell family which are deeply incompatible.  If you want to
13923 write portable shell scripts, avoid members of the C shell family.  The
13924 @uref{http://@/www.faqs.org/@/faqs/@/unix-faq/@/shell/@/shell-differences/, the
13925 Shell difference FAQ} includes a small history of Posix shells, and a
13926 comparison between several of them.
13928 Below we describe some of the members of the Bourne shell family.
13930 @table @asis
13931 @item Ash
13932 @cindex Ash
13933 Ash is often used on @acronym{GNU}/Linux and @acronym{BSD}
13934 systems as a light-weight Bourne-compatible shell.  Ash 0.2 has some
13935 bugs that are fixed in the 0.3.x series, but portable shell scripts
13936 should work around them, since version 0.2 is still shipped with many
13937 @acronym{GNU}/Linux distributions.
13939 To be compatible with Ash 0.2:
13941 @itemize @minus
13942 @item
13943 don't use @samp{$?} after expanding empty or unset variables,
13944 or at the start of an @command{eval}:
13946 @example
13947 foo=
13948 false
13949 $foo
13950 echo "Do not use it: $?"
13951 false
13952 eval 'echo "Do not use it: $?"'
13953 @end example
13955 @item
13956 don't use command substitution within variable expansion:
13958 @example
13959 cat $@{FOO=`bar`@}
13960 @end example
13962 @item
13963 beware that single builtin substitutions are not performed by a
13964 subshell, hence their effect applies to the current shell!  @xref{Shell
13965 Substitutions}, item ``Command Substitution''.
13966 @end itemize
13968 @item Bash
13969 @cindex Bash
13970 To detect whether you are running Bash, test whether
13971 @code{BASH_VERSION} is set.  To require
13972 Posix compatibility, run @samp{set -o posix}.  @xref{Bash POSIX
13973 Mode, , Bash Posix Mode, bash, The @acronym{GNU} Bash Reference
13974 Manual}, for details.
13976 @item Bash 2.05 and later
13977 @cindex Bash 2.05 and later
13978 Versions 2.05 and later of Bash use a different format for the
13979 output of the @command{set} builtin, designed to make evaluating its
13980 output easier.  However, this output is not compatible with earlier
13981 versions of Bash (or with many other shells, probably).  So if
13982 you use Bash 2.05 or higher to execute @command{configure},
13983 you'll need to use Bash 2.05 for all other build tasks as well.
13985 @item Ksh
13986 @cindex Ksh
13987 @cindex Korn shell
13988 @prindex @samp{ksh}
13989 @prindex @samp{ksh88}
13990 @prindex @samp{ksh93}
13991 The Korn shell is compatible with the Bourne family and it mostly
13992 conforms to Posix.  It has two major variants commonly
13993 called @samp{ksh88} and @samp{ksh93}, named after the years of initial
13994 release.  It is usually called @command{ksh}, but is called @command{sh}
13995 on some hosts if you set your path appropriately.
13997 Solaris systems have three variants:
13998 @prindex @command{/usr/bin/ksh} on Solaris
13999 @command{/usr/bin/ksh} is @samp{ksh88}; it is
14000 standard on Solaris 2.0 and later.
14001 @prindex @command{/usr/xpg4/bin/sh} on Solaris
14002 @command{/usr/xpg4/bin/sh} is a Posix-compliant variant of
14003 @samp{ksh88}; it is standard on Solaris 9 and later.
14004 @prindex @command{/usr/dt/bin/dtksh} on Solaris
14005 @command{/usr/dt/bin/dtksh} is @samp{ksh93}.
14006 Variants that are not standard may be parts of optional
14007 packages.  There is no extra charge for these packages, but they are
14008 not part of a minimal OS install and therefore some installations may
14009 not have it.
14011 Starting with Tru64 Version 4.0, the Korn shell @command{/usr/bin/ksh}
14012 is also available as @command{/usr/bin/posix/sh}.  If the environment
14013 variable @env{BIN_SH} is set to @code{xpg4}, subsidiary invocations of
14014 the standard shell conform to Posix.
14016 @item Pdksh
14017 @prindex @samp{pdksh}
14018 A public-domain clone of the Korn shell called @command{pdksh} is widely
14019 available: it has most of the @samp{ksh88} features along with a few of
14020 its own.  It usually sets @code{KSH_VERSION}, except if invoked as
14021 @command{/bin/sh} on Open@acronym{BSD}, and similarly to Bash you can require
14022 Posix compatibility by running @samp{set -o posix}.  Unfortunately, with
14023 @command{pdksh} 5.2.14 (the latest stable version as of January 2007)
14024 Posix mode is buggy and causes @command{pdksh} to depart from Posix in
14025 at least one respect:
14027 @example
14028 $ @kbd{echo "`echo \"hello\"`"}
14029 hello
14030 $ @kbd{set -o posix}
14031 $ @kbd{echo "`echo \"hello\"`"}
14032 "hello"
14033 @end example
14035 The last line of output contains spurious quotes.  This is yet another
14036 reason why portable shell code should not contain
14037 @code{"`@dots{}\"@dots{}\"@dots{}`"} constructs (@pxref{Shell
14038 Substitutions}).
14040 @item Zsh
14041 @cindex Zsh
14042 To detect whether you are running @command{zsh}, test whether
14043 @code{ZSH_VERSION} is set.  By default @command{zsh} is @emph{not}
14044 compatible with the Bourne shell: you must execute @samp{emulate sh},
14045 and for @command{zsh} versions before 3.1.6-dev-18 you must also
14046 set @code{NULLCMD} to @samp{:}.  @xref{Compatibility, , Compatibility,
14047 zsh, The Z Shell Manual}, for details.
14049 The default Mac OS X @command{sh} was originally Zsh; it was changed to
14050 Bash in Mac OS X 10.2.
14051 @end table
14053 @node Here-Documents
14054 @section Here-Documents
14055 @cindex Here-documents
14056 @cindex Shell here-documents
14058 Don't rely on @samp{\} being preserved just because it has no special
14059 meaning together with the next symbol.  In the native @command{sh}
14060 on Open@acronym{BSD} 2.7 @samp{\"} expands to @samp{"} in here-documents with
14061 unquoted delimiter.  As a general rule, if @samp{\\} expands to @samp{\}
14062 use @samp{\\} to get @samp{\}.
14064 With Open@acronym{BSD} 2.7's @command{sh}
14066 @example
14067 @group
14068 $ @kbd{cat <<EOF
14069 > \" \\
14070 > EOF}
14071 " \
14072 @end group
14073 @end example
14075 @noindent
14076 and with Bash:
14078 @example
14079 @group
14080 bash-2.04$ @kbd{cat <<EOF
14081 > \" \\
14082 > EOF}
14083 \" \
14084 @end group
14085 @end example
14087 Some shells mishandle large here-documents: for example,
14088 Solaris 10 @command{dtksh} and the UnixWare 7.1.1 Posix shell, which are
14089 derived from Korn shell version M-12/28/93d, mishandle braced variable
14090 expansion that crosses a 1024- or 4096-byte buffer boundary
14091 within a here-document.  Only the part of the variable name after the boundary
14092 is used.  For example, @code{$@{variable@}} could be replaced by the expansion
14093 of @code{$@{ble@}}.  If the end of the variable name is aligned with the block
14094 boundary, the shell reports an error, as if you used @code{$@{@}}.
14095 Instead of @code{$@{variable-default@}}, the shell may expand
14096 @code{$@{riable-default@}}, or even @code{$@{fault@}}.  This bug can often
14097 be worked around by omitting the braces: @code{$variable}.  The bug was
14098 fixed in
14099 @samp{ksh93g} (1998-04-30) but as of 2006 many operating systems were
14100 still shipping older versions with the bug.
14102 Many shells (including the Bourne shell) implement here-documents
14103 inefficiently.  In particular, some shells can be extremely inefficient when
14104 a single statement contains many here-documents.  For instance if your
14105 @file{configure.ac} includes something like:
14107 @example
14108 @group
14109 if <cross_compiling>; then
14110   assume this and that
14111 else
14112   check this
14113   check that
14114   check something else
14115   @dots{}
14116   on and on forever
14117   @dots{}
14119 @end group
14120 @end example
14122 A shell parses the whole @code{if}/@code{fi} construct, creating
14123 temporary files for each here-document in it.  Some shells create links
14124 for such here-documents on every @code{fork}, so that the clean-up code
14125 they had installed correctly removes them.  It is creating the links
14126 that can take the shell forever.
14128 Moving the tests out of the @code{if}/@code{fi}, or creating multiple
14129 @code{if}/@code{fi} constructs, would improve the performance
14130 significantly.  Anyway, this kind of construct is not exactly the
14131 typical use of Autoconf.  In fact, it's even not recommended, because M4
14132 macros can't look into shell conditionals, so we may fail to expand a
14133 macro when it was expanded before in a conditional path, and the
14134 condition turned out to be false at runtime, and we end up not
14135 executing the macro at all.
14137 @node File Descriptors
14138 @section File Descriptors
14139 @cindex Descriptors
14140 @cindex File descriptors
14141 @cindex Shell file descriptors
14143 Most shells, if not all (including Bash, Zsh, Ash), output traces on
14144 stderr, even for subshells.  This might result in undesirable content
14145 if you meant to capture the standard-error output of the inner command:
14147 @example
14148 $ @kbd{ash -x -c '(eval "echo foo >&2") 2>stderr'}
14149 $ @kbd{cat stderr}
14150 + eval echo foo >&2
14151 + echo foo
14153 $ @kbd{bash -x -c '(eval "echo foo >&2") 2>stderr'}
14154 $ @kbd{cat stderr}
14155 + eval 'echo foo >&2'
14156 ++ echo foo
14158 $ @kbd{zsh -x -c '(eval "echo foo >&2") 2>stderr'}
14159 @i{# Traces on startup files deleted here.}
14160 $ @kbd{cat stderr}
14161 +zsh:1> eval echo foo >&2
14162 +zsh:1> echo foo
14164 @end example
14166 @noindent
14167 One workaround is to grep out uninteresting lines, hoping not to remove
14168 good ones.
14170 If you intend to redirect both standard error and standard output,
14171 redirect standard output first.  This works better with @acronym{HP-UX},
14172 since its shell mishandles tracing if standard error is redirected
14173 first:
14175 @example
14176 $ @kbd{sh -x -c ': 2>err >out'}
14177 + :
14178 + 2> err $ @kbd{cat err}
14179 1> out
14180 @end example
14182 Don't try to redirect the standard error of a command substitution.  It
14183 must be done @emph{inside} the command substitution.  When running
14184 @samp{: `cd /zorglub` 2>/dev/null} expect the error message to
14185 escape, while @samp{: `cd /zorglub 2>/dev/null`} works properly.
14187 It is worth noting that Zsh (but not Ash nor Bash) makes it possible
14188 in assignments though: @samp{foo=`cd /zorglub` 2>/dev/null}.
14190 Some shells, like @command{ash}, don't recognize bi-directional
14191 redirection (@samp{<>}).  And even on shells that recognize it, it is
14192 not portable to use on fifos: Posix does not require read-write support
14193 for named pipes, and Cygwin does not support it:
14195 @example
14196 $ @kbd{mkfifo fifo}
14197 $ @kbd{exec 5<>fifo}
14198 $ @kbd{echo hi >&5}
14199 bash: echo: write error: Communication error on send
14200 @end example
14202 When catering to old systems, don't redirect the same file descriptor
14203 several times, as you are doomed to failure under Ultrix.
14205 @example
14206 ULTRIX V4.4 (Rev. 69) System #31: Thu Aug 10 19:42:23 GMT 1995
14207 UWS V4.4 (Rev. 11)
14208 $ @kbd{eval 'echo matter >fullness' >void}
14209 illegal io
14210 $ @kbd{eval '(echo matter >fullness)' >void}
14211 illegal io
14212 $ @kbd{(eval '(echo matter >fullness)') >void}
14213 Ambiguous output redirect.
14214 @end example
14216 @noindent
14217 In each case the expected result is of course @file{fullness} containing
14218 @samp{matter} and @file{void} being empty.  However, this bug is
14219 probably not of practical concern to modern platforms.
14221 Solaris 10 @command{sh} will try to optimize away a @command{:} command
14222 in a loop after the first iteration, even if it is redirected:
14224 @example
14225 $ @kbd{for i in 1 2 3 ; do : >x$i; done}
14226 $ @kbd{ls}
14228 @end example
14230 @noindent
14231 As a workaround, @command{echo} or @command{eval} can be used.
14233 Don't rely on file descriptors 0, 1, and 2 remaining closed in a
14234 subsidiary program.  If any of these descriptors is closed, the
14235 operating system may open an unspecified file for the descriptor in the
14236 new process image.  Posix says this may be done only if the subsidiary
14237 program is set-user-ID or set-group-ID, but @acronym{HP-UX} 11.23 does
14238 it even for ordinary programs.
14240 Don't rely on open file descriptors being open in child processes.  In
14241 @command{ksh}, file descriptors above 2 which are opened using
14242 @samp{exec @var{n}>file} are closed by a subsequent @samp{exec} (such as
14243 that involved in the fork-and-exec which runs a program or script).
14244 Thus, using @command{sh}, we have:
14246 @example
14247 $ @kbd{cat ./descrips}
14248 #!/bin/sh -
14249 echo hello >&5
14250 $ @kbd{exec 5>t}
14251 $ @kbd{./descrips}
14252 $ @kbd{cat t}
14253 hello
14255 @end example
14257 @noindent
14258 But using ksh:
14260 @example
14261 $ @kbd{exec 5>t}
14262 $ @kbd{./descrips}
14263 hello
14264 $ @kbd{cat t}
14266 @end example
14268 @noindent
14269 Within the process which runs the @samp{descrips} script, file
14270 descriptor 5 is closed.
14272 Don't rely on redirection to a closed file descriptor to cause an
14273 error.  With Solaris @command{/bin/sh}, when the redirection fails, the
14274 output goes to the original file descriptor.
14276 @example
14277 $ @kbd{bash -c 'echo hi >&3' 3>&-; echo $?}
14278 bash: 3: Bad file descriptor
14280 $ @kbd{/bin/sh -c 'echo hi >&3' 3>&-; echo $?}
14283 @end example
14285 @acronym{DOS} variants cannot rename or remove open files, such as in
14286 @samp{mv foo bar >foo} or @samp{rm foo >foo}, even though this is
14287 perfectly portable among Posix hosts.
14289 A few ancient systems reserved some file descriptors.  By convention,
14290 file descriptor 3 was opened to @file{/dev/tty} when you logged into
14291 Eighth Edition (1985) through Tenth Edition Unix (1989).  File
14292 descriptor 4 had a special use on the Stardent/Kubota Titan (circa
14293 1990), though we don't now remember what it was.  Both these systems are
14294 obsolete, so it's now safe to treat file descriptors 3 and 4 like any
14295 other file descriptors.
14297 @node File System Conventions
14298 @section File System Conventions
14299 @cindex File system conventions
14301 Autoconf uses shell-script processing extensively, so the file names
14302 that it processes should not contain characters that are special to the
14303 shell.  Special characters include space, tab, newline, @sc{nul}, and
14304 the following:
14306 @example
14307 " # $ & ' ( ) * ; < = > ? [ \ ` |
14308 @end example
14310 Also, file names should not begin with @samp{~} or @samp{-}, and should
14311 contain neither @samp{-} immediately after @samp{/} nor @samp{~}
14312 immediately after @samp{:}.  On Posix-like platforms, directory names
14313 should not contain @samp{:}, as this runs afoul of @samp{:} used as the
14314 path separator.
14316 These restrictions apply not only to the files that you distribute, but
14317 also to the absolute file names of your source, build, and destination
14318 directories.
14320 On some Posix-like platforms, @samp{!} and @samp{^} are special too, so
14321 they should be avoided.
14323 Posix lets implementations treat leading @file{//} specially, but
14324 requires leading @file{///} and beyond to be equivalent to @file{/}.
14325 Most Unix variants treat @file{//} like @file{/}.  However, some treat
14326 @file{//} as a ``super-root'' that can provide access to files that are
14327 not otherwise reachable from @file{/}.  The super-root tradition began
14328 with Apollo Domain/OS, which died out long ago, but unfortunately Cygwin
14329 has revived it.
14331 While @command{autoconf} and friends are usually run on some Posix
14332 variety, they can be used on other systems, most notably @acronym{DOS}
14333 variants.  This impacts several assumptions regarding file names.
14335 @noindent
14336 For example, the following code:
14338 @example
14339 case $foo_dir in
14340   /*) # Absolute
14341      ;;
14342   *)
14343      foo_dir=$dots$foo_dir ;;
14344 esac
14345 @end example
14347 @noindent
14348 fails to properly detect absolute file names on those systems, because
14349 they can use a drivespec, and usually use a backslash as directory
14350 separator.  If you want to be portable to @acronym{DOS} variants (at the
14351 price of rejecting valid but oddball Posix file names like @file{a:\b}),
14352 you can check for absolute file names like this:
14354 @cindex absolute file names, detect
14355 @example
14356 case $foo_dir in
14357   [\\/]* | ?:[\\/]* ) # Absolute
14358      ;;
14359   *)
14360      foo_dir=$dots$foo_dir ;;
14361 esac
14362 @end example
14364 @noindent
14365 Make sure you quote the brackets if appropriate and keep the backslash as
14366 first character (@pxref{case, , Limitations of Shell Builtins}).
14368 Also, because the colon is used as part of a drivespec, these systems don't
14369 use it as path separator.  When creating or accessing paths, you can use the
14370 @code{PATH_SEPARATOR} output variable instead.  @command{configure} sets this
14371 to the appropriate value for the build system (@samp{:} or @samp{;}) when it
14372 starts up.
14374 File names need extra care as well.  While @acronym{DOS} variants
14375 that are Posixy enough to run @command{autoconf} (such as @acronym{DJGPP})
14376 are usually able to handle long file names properly, there are still
14377 limitations that can seriously break packages.  Several of these issues
14378 can be easily detected by the
14379 @uref{ftp://@/ftp.gnu.org/@/gnu/@/non-gnu/@/doschk/@/doschk-1.1.tar.gz, doschk}
14380 package.
14382 A short overview follows; problems are marked with @sc{sfn}/@sc{lfn} to
14383 indicate where they apply: @sc{sfn} means the issues are only relevant to
14384 plain @acronym{DOS}, not to @acronym{DOS} under Microsoft Windows
14385 variants, while @sc{lfn} identifies problems that exist even under
14386 Microsoft Windows variants.
14388 @table @asis
14389 @item No multiple dots (@sc{sfn})
14390 @acronym{DOS} cannot handle multiple dots in file names.  This is an especially
14391 important thing to remember when building a portable configure script,
14392 as @command{autoconf} uses a .in suffix for template files.
14394 This is perfectly OK on Posix variants:
14396 @example
14397 AC_CONFIG_HEADERS([config.h])
14398 AC_CONFIG_FILES([source.c foo.bar])
14399 AC_OUTPUT
14400 @end example
14402 @noindent
14403 but it causes problems on @acronym{DOS}, as it requires @samp{config.h.in},
14404 @samp{source.c.in} and @samp{foo.bar.in}.  To make your package more portable
14405 to @acronym{DOS}-based environments, you should use this instead:
14407 @example
14408 AC_CONFIG_HEADERS([config.h:config.hin])
14409 AC_CONFIG_FILES([source.c:source.cin foo.bar:foobar.in])
14410 AC_OUTPUT
14411 @end example
14413 @item No leading dot (@sc{sfn})
14414 @acronym{DOS} cannot handle file names that start with a dot.  This is usually
14415 not important for @command{autoconf}.
14417 @item Case insensitivity (@sc{lfn})
14418 @acronym{DOS} is case insensitive, so you cannot, for example, have both a
14419 file called @samp{INSTALL} and a directory called @samp{install}.  This
14420 also affects @command{make}; if there's a file called @samp{INSTALL} in
14421 the directory, @samp{make install} does nothing (unless the
14422 @samp{install} target is marked as PHONY).
14424 @item The 8+3 limit (@sc{sfn})
14425 Because the @acronym{DOS} file system only stores the first 8 characters of
14426 the file name and the first 3 of the extension, those must be unique.
14427 That means that @file{foobar-part1.c}, @file{foobar-part2.c} and
14428 @file{foobar-prettybird.c} all resolve to the same file name
14429 (@file{FOOBAR-P.C}).  The same goes for @file{foo.bar} and
14430 @file{foo.bartender}.
14432 The 8+3 limit is not usually a problem under Microsoft Windows, as it
14433 uses numeric
14434 tails in the short version of file names to make them unique.  However, a
14435 registry setting can turn this behavior off.  While this makes it
14436 possible to share file trees containing long file names between @sc{sfn}
14437 and @sc{lfn} environments, it also means the above problem applies there
14438 as well.
14440 @item Invalid characters (@sc{lfn})
14441 Some characters are invalid in @acronym{DOS} file names, and should therefore
14442 be avoided.  In a @sc{lfn} environment, these are @samp{/}, @samp{\},
14443 @samp{?}, @samp{*}, @samp{:}, @samp{<}, @samp{>}, @samp{|} and @samp{"}.
14444 In a @sc{sfn} environment, other characters are also invalid.  These
14445 include @samp{+}, @samp{,}, @samp{[} and @samp{]}.
14447 @item Invalid names (@sc{lfn})
14448 Some @acronym{DOS} file names are reserved, and cause problems if you
14449 try to use files with those names.  These names include @file{CON},
14450 @file{AUX}, @file{COM1}, @file{COM2}, @file{COM3}, @file{COM4},
14451 @file{LPT1}, @file{LPT2}, @file{LPT3}, @file{NUL}, and @file{PRN}.
14452 File names are case insensitive, so even names like
14453 @file{aux/config.guess} are disallowed.
14455 @end table
14457 @node Shell Pattern Matching
14458 @section Shell Pattern Matching
14459 @cindex Shell pattern matching
14461 Nowadays portable patterns can use negated character classes like
14462 @samp{[!-aeiou]}.  The older syntax @samp{[^-aeiou]} is supported by
14463 some shells but not others; hence portable scripts should never use
14464 @samp{^} as the first character of a bracket pattern.
14466 Outside the C locale, patterns like @samp{[a-z]} are problematic since
14467 they may match characters that are not lower-case letters.
14469 @node Shell Substitutions
14470 @section Shell Substitutions
14471 @cindex Shell substitutions
14473 Contrary to a persistent urban legend, the Bourne shell does not
14474 systematically split variables and back-quoted expressions, in particular
14475 on the right-hand side of assignments and in the argument of @code{case}.
14476 For instance, the following code:
14478 @example
14479 case "$given_srcdir" in
14480 .)  top_srcdir="`echo "$dots" | sed 's|/$||'`" ;;
14481 *)  top_srcdir="$dots$given_srcdir" ;;
14482 esac
14483 @end example
14485 @noindent
14486 is more readable when written as:
14488 @example
14489 case $given_srcdir in
14490 .)  top_srcdir=`echo "$dots" | sed 's|/$||'` ;;
14491 *)  top_srcdir=$dots$given_srcdir ;;
14492 esac
14493 @end example
14495 @noindent
14496 and in fact it is even @emph{more} portable: in the first case of the
14497 first attempt, the computation of @code{top_srcdir} is not portable,
14498 since not all shells properly understand @code{"`@dots{}"@dots{}"@dots{}`"}.
14499 Worse yet, not all shells understand @code{"`@dots{}\"@dots{}\"@dots{}`"}
14500 the same way.  There is just no portable way to use double-quoted
14501 strings inside double-quoted back-quoted expressions (pfew!).
14503 @table @code
14504 @item $@@
14505 @cindex @samp{"$@@"}
14506 One of the most famous shell-portability issues is related to
14507 @samp{"$@@"}.  When there are no positional arguments, Posix says
14508 that @samp{"$@@"} is supposed to be equivalent to nothing, but the
14509 original Unix version 7 Bourne shell treated it as equivalent to
14510 @samp{""} instead, and this behavior survives in later implementations
14511 like Digital Unix 5.0.
14513 The traditional way to work around this portability problem is to use
14514 @samp{$@{1+"$@@"@}}.  Unfortunately this method does not work with
14515 Zsh (3.x and 4.x), which is used on Mac OS X@.  When emulating
14516 the Bourne shell, Zsh performs word splitting on @samp{$@{1+"$@@"@}}:
14518 @example
14519 zsh $ @kbd{emulate sh}
14520 zsh $ @kbd{for i in "$@@"; do echo $i; done}
14521 Hello World
14523 zsh $ @kbd{for i in $@{1+"$@@"@}; do echo $i; done}
14524 Hello
14525 World
14527 @end example
14529 @noindent
14530 Zsh handles plain @samp{"$@@"} properly, but we can't use plain
14531 @samp{"$@@"} because of the portability problems mentioned above.
14532 One workaround relies on Zsh's ``global aliases'' to convert
14533 @samp{$@{1+"$@@"@}} into @samp{"$@@"} by itself:
14535 @example
14536 test "$@{ZSH_VERSION+set@}" = set && alias -g '$@{1+"$@@"@}'='"$@@"'
14537 @end example
14539 Zsh only recognizes this alias when a shell word matches it exactly;
14540 @samp{"foo"$@{1+"$@@"@}} remains subject to word splitting.  Since this
14541 case always yields at least one shell word, use plain @samp{"$@@"}.
14543 A more conservative workaround is to avoid @samp{"$@@"} if it is
14544 possible that there may be no positional arguments.  For example,
14545 instead of:
14547 @example
14548 cat conftest.c "$@@"
14549 @end example
14551 you can use this instead:
14553 @example
14554 case $# in
14555 0) cat conftest.c;;
14556 *) cat conftest.c "$@@";;
14557 esac
14558 @end example
14560 Autoconf macros often use the @command{set} command to update
14561 @samp{$@@}, so if you are writing shell code intended for
14562 @command{configure} you should not assume that the value of @samp{$@@}
14563 persists for any length of time.
14566 @item $@{10@}
14567 @cindex positional parameters
14568 The 10th, 11th, @dots{} positional parameters can be accessed only after
14569 a @code{shift}.  The 7th Edition shell reported an error if given
14570 @code{$@{10@}}, and
14571 Solaris 10 @command{/bin/sh} still acts that way:
14573 @example
14574 $ @kbd{set 1 2 3 4 5 6 7 8 9 10}
14575 $ @kbd{echo $@{10@}}
14576 bad substitution
14577 @end example
14579 @item $@{@var{var}:-@var{value}@}
14580 @c Info cannot handle `:' in index entries.
14581 @c @cindex $@{@var{var}:-@var{value}@}
14582 Old @acronym{BSD} shells, including the Ultrix @code{sh}, don't accept the
14583 colon for any shell substitution, and complain and die.
14584 Similarly for $@{@var{var}:=@var{value}@}, $@{@var{var}:?@var{value}@}, etc.
14586 @item $@{@var{var}=@var{literal}@}
14587 @cindex $@{@var{var}=@var{literal}@}
14588 Be sure to quote:
14590 @example
14591 : $@{var='Some words'@}
14592 @end example
14594 @noindent
14595 otherwise some shells, such as on Digital Unix V 5.0, die because
14596 of a ``bad substitution''.
14598 @sp 1
14600 Solaris @command{/bin/sh} has a frightening bug in its interpretation
14601 of this.  Imagine you need set a variable to a string containing
14602 @samp{@}}.  This @samp{@}} character confuses Solaris @command{/bin/sh}
14603 when the affected variable was already set.  This bug can be exercised
14604 by running:
14606 @example
14607 $ @kbd{unset foo}
14608 $ @kbd{foo=$@{foo='@}'@}}
14609 $ @kbd{echo $foo}
14611 $ @kbd{foo=$@{foo='@}'   # no error; this hints to what the bug is}
14612 $ @kbd{echo $foo}
14614 $ @kbd{foo=$@{foo='@}'@}}
14615 $ @kbd{echo $foo}
14616 @}@}
14617  ^ ugh!
14618 @end example
14620 It seems that @samp{@}} is interpreted as matching @samp{$@{}, even
14621 though it is enclosed in single quotes.  The problem doesn't happen
14622 using double quotes.
14624 @item $@{@var{var}=@var{expanded-value}@}
14625 @cindex $@{@var{var}=@var{expanded-value}@}
14626 On Ultrix,
14627 running
14629 @example
14630 default="yu,yaa"
14631 : $@{var="$default"@}
14632 @end example
14634 @noindent
14635 sets @var{var} to @samp{M-yM-uM-,M-yM-aM-a}, i.e., the 8th bit of
14636 each char is set.  You don't observe the phenomenon using a simple
14637 @samp{echo $var} since apparently the shell resets the 8th bit when it
14638 expands $var.  Here are two means to make this shell confess its sins:
14640 @example
14641 $ @kbd{cat -v <<EOF
14642 $var
14643 EOF}
14644 @end example
14646 @noindent
14649 @example
14650 $ @kbd{set | grep '^var=' | cat -v}
14651 @end example
14653 One classic incarnation of this bug is:
14655 @example
14656 default="a b c"
14657 : $@{list="$default"@}
14658 for c in $list; do
14659   echo $c
14660 done
14661 @end example
14663 @noindent
14664 You'll get @samp{a b c} on a single line.  Why?  Because there are no
14665 spaces in @samp{$list}: there are @samp{M- }, i.e., spaces with the 8th
14666 bit set, hence no IFS splitting is performed!!!
14668 One piece of good news is that Ultrix works fine with @samp{:
14669 $@{list=$default@}}; i.e., if you @emph{don't} quote.  The bad news is
14670 then that @acronym{QNX} 4.25 then sets @var{list} to the @emph{last} item of
14671 @var{default}!
14673 The portable way out consists in using a double assignment, to switch
14674 the 8th bit twice on Ultrix:
14676 @example
14677 list=$@{list="$default"@}
14678 @end example
14680 @noindent
14681 @dots{}but beware of the @samp{@}} bug from Solaris (see above).  For safety,
14682 use:
14684 @example
14685 test "$@{var+set@}" = set || var=@var{@{value@}}
14686 @end example
14688 @item $@{#@var{var}@}
14689 @itemx $@{@var{var}%@var{word}@}
14690 @itemx $@{@var{var}%%@var{word}@}
14691 @itemx $@{@var{var}#@var{word}@}
14692 @itemx $@{@var{var}##@var{word}@}
14693 @cindex $@{#@var{var}@}
14694 @cindex $@{@var{var}%@var{word}@}
14695 @cindex $@{@var{var}%%@var{word}@}
14696 @cindex $@{@var{var}#@var{word}@}
14697 @cindex $@{@var{var}##@var{word}@}
14698 Posix requires support for these usages, but they do not work with many
14699 traditional shells, e.g., Solaris 10 @command{/bin/sh}.
14701 Also, @command{pdksh} 5.2.14 mishandles some @var{word} forms.  For
14702 example if @samp{$1} is @samp{a/b} and @samp{$2} is @samp{a}, then
14703 @samp{$@{1#$2@}} should yield @samp{/b}, but with @command{pdksh} it
14704 yields the empty string.
14707 @item `@var{commands}`
14708 @cindex `@var{commands}`
14709 @cindex Command Substitution
14710 Posix requires shells to trim all trailing newlines from command
14711 output before substituting it, so assignments like
14712 @samp{dir=`echo "$file" | tr a A`} do not work as expected if
14713 @samp{$file} ends in a newline.
14715 While in general it makes no sense, do not substitute a single builtin
14716 with side effects, because Ash 0.2, trying to optimize, does not fork a
14717 subshell to perform the command.
14719 For instance, if you wanted to check that @command{cd} is silent, do not
14720 use @samp{test -z "`cd /`"} because the following can happen:
14722 @example
14723 $ @kbd{pwd}
14724 /tmp
14725 $ @kbd{test -z "`cd /`" && pwd}
14727 @end example
14729 @noindent
14730 The result of @samp{foo=`exit 1`} is left as an exercise to the reader.
14732 The MSYS shell leaves a stray byte in the expansion of a double-quoted
14733 command substitution of a native program, if the end of the substitution
14734 is not aligned with the end of the double quote.  This may be worked
14735 around by inserting another pair of quotes:
14737 @example
14738 $ @kbd{echo "`printf 'foo\r\n'` bar" > broken}
14739 $ @kbd{echo "`printf 'foo\r\n'`"" bar" | cmp - broken}
14740 - broken differ: char 4, line 1
14741 @end example
14743 Upon interrupt or SIGTERM, some shells may abort a command substitution,
14744 replace it with a null string, and wrongly evaluate the enclosing
14745 command before entering the trap or ending the script.  This can lead to
14746 spurious errors:
14748 @example
14749 $ @kbd{sh -c 'if test `sleep 5; echo hi` = hi; then echo yes; fi'}
14750 $ @kbd{^C}
14751 sh: test: hi: unexpected operator/operand
14752 @end example
14754 @noindent
14755 You can avoid this by assigning the command substitution to a temporary
14756 variable:
14758 @example
14759 $ @kbd{sh -c 'res=`sleep 5; echo hi`
14760          if test "x$res" = xhi; then echo yes; fi'}
14761 $ @kbd{^C}
14762 @end example
14764 @item $(@var{commands})
14765 @cindex $(@var{commands})
14766 This construct is meant to replace @samp{`@var{commands}`},
14767 and it has most of the problems listed under @code{`@var{commands}`}.
14769 This construct can be
14770 nested while this is impossible to do portably with back quotes.
14771 Unfortunately it is not yet universally supported.  Most notably, even recent
14772 releases of Solaris don't support it:
14774 @example
14775 $ @kbd{showrev -c /bin/sh | grep version}
14776 Command version: SunOS 5.10 Generic 121005-03 Oct 2006
14777 $ @kbd{echo $(echo blah)}
14778 syntax error: `(' unexpected
14779 @end example
14781 @noindent
14782 nor does @sc{irix} 6.5's Bourne shell:
14783 @example
14784 $ @kbd{uname -a}
14785 IRIX firebird-image 6.5 07151432 IP22
14786 $ @kbd{echo $(echo blah)}
14787 $(echo blah)
14788 @end example
14790 If you do use @samp{$(@var{commands})}, make sure that the commands
14791 do not start with a parenthesis, as that would cause confusion with
14792 a different notation @samp{$((@var{expression}))} that in modern
14793 shells is an arithmetic expression not a command.  To avoid the
14794 confusion, insert a space between the two opening parentheses.
14796 Avoid @var{commands} that contain unbalanced parentheses in
14797 here-documents, comments, or case statement patterns, as many shells
14798 mishandle them.  For example, Bash 3.1, @samp{ksh88}, @command{pdksh}
14799 5.2.14, and Zsh 4.2.6 all mishandle the following valid command:
14801 @example
14802 echo $(case x in x) echo hello;; esac)
14803 @end example
14806 @item $((@var{expression}))
14807 @cindex $((@var{expression}))
14808 Arithmetic expansion is not portable as some shells (most
14809 notably Solaris 10 @command{/bin/sh}) don't support it.
14811 Among shells that do support @samp{$(( ))}, not all of them obey the
14812 Posix rule that octal and hexadecimal constants must be recognized:
14814 @example
14815 $ @kbd{bash -c 'echo $(( 010 + 0x10 ))'}
14817 $ @kbd{zsh -c 'echo $(( 010 + 0x10 ))'}
14819 $ @kbd{zsh -c 'emulate sh; echo $(( 010 + 0x10 ))'}
14821 $ @kbd{pdksh -c 'echo $(( 010 + 0x10 ))'}
14822 pdksh:  010 + 0x10 : bad number `0x10'
14823 $ @kbd{pdksh -c 'echo $(( 010 ))'}
14825 @end example
14827 When it is available, using arithmetic expansion provides a noticeable
14828 speedup in script execution; but testing for support requires
14829 @command{eval} to avoid syntax errors.  The following construct is used
14830 by @code{AS_VAR_ARITH} to provide arithmetic computation when all
14831 arguments are provided in decimal and without a leading zero, and all
14832 operators are properly quoted and appear as distinct arguments:
14834 @example
14835 if ( eval 'test $(( 1 + 1 )) = 2' ) 2>/dev/null; then
14836   eval 'func_arith ()
14837   @{
14838     func_arith_result=$(( $* ))
14839   @}'
14840 else
14841   func_arith ()
14842   @{
14843     func_arith_result=`expr "$@@"`
14844   @}
14846 func_arith 1 + 1
14847 foo=$func_arith_result
14848 @end example
14851 @item ^
14852 @cindex ^ quoting
14853 Always quote @samp{^}, otherwise traditional shells such as
14854 @command{/bin/sh} on Solaris 10 treat this like @samp{|}.
14856 @end table
14859 @node Assignments
14860 @section Assignments
14861 @cindex Shell assignments
14863 When setting several variables in a row, be aware that the order of the
14864 evaluation is undefined.  For instance @samp{foo=1 foo=2; echo $foo}
14865 gives @samp{1} with Solaris @command{/bin/sh}, but @samp{2} with Bash.
14866 You must use
14867 @samp{;} to enforce the order: @samp{foo=1; foo=2; echo $foo}.
14869 Don't rely on the following to find @file{subdir/program}:
14871 @example
14872 PATH=subdir$PATH_SEPARATOR$PATH program
14873 @end example
14875 @noindent
14876 as this does not work with Zsh 3.0.6.  Use something like this
14877 instead:
14879 @example
14880 (PATH=subdir$PATH_SEPARATOR$PATH; export PATH; exec program)
14881 @end example
14883 Don't rely on the exit status of an assignment: Ash 0.2 does not change
14884 the status and propagates that of the last statement:
14886 @example
14887 $ @kbd{false || foo=bar; echo $?}
14889 $ @kbd{false || foo=`:`; echo $?}
14891 @end example
14893 @noindent
14894 and to make things even worse, @acronym{QNX} 4.25 just sets the exit status
14895 to 0 in any case:
14897 @example
14898 $ @kbd{foo=`exit 1`; echo $?}
14900 @end example
14902 To assign default values, follow this algorithm:
14904 @enumerate
14905 @item
14906 If the default value is a literal and does not contain any closing
14907 brace, use:
14909 @example
14910 : $@{var='my literal'@}
14911 @end example
14913 @item
14914 If the default value contains no closing brace, has to be expanded, and
14915 the variable being initialized is not intended to be IFS-split
14916 (i.e., it's not a list), then use:
14918 @example
14919 : $@{var="$default"@}
14920 @end example
14922 @item
14923 If the default value contains no closing brace, has to be expanded, and
14924 the variable being initialized is intended to be IFS-split (i.e., it's a list),
14925 then use:
14927 @example
14928 var=$@{var="$default"@}
14929 @end example
14931 @item
14932 If the default value contains a closing brace, then use:
14934 @example
14935 test "$@{var+set@}" = set || var="has a '@}'"
14936 @end example
14937 @end enumerate
14939 In most cases @samp{var=$@{var="$default"@}} is fine, but in case of
14940 doubt, just use the last form.  @xref{Shell Substitutions}, items
14941 @samp{$@{@var{var}:-@var{value}@}} and @samp{$@{@var{var}=@var{value}@}}
14942 for the rationale.
14944 @node Parentheses
14945 @section Parentheses in Shell Scripts
14946 @cindex Shell parentheses
14948 Beware of two opening parentheses in a row, as many shell
14949 implementations treat them specially.  Posix requires that the command
14950 @samp{((cat))} must behave like @samp{(cat)}, but many shells, including
14951 Bash and the Korn shell, treat @samp{((cat))} as an arithmetic
14952 expression equivalent to @samp{let "cat"}, and may or may not report an
14953 error when they detect that @samp{cat} is not a number.  As another
14954 example, @samp{pdksh} 5.2.14 misparses the following code:
14956 @example
14957 if ((true) || false); then
14958   echo ok
14960 @end example
14962 @noindent
14963 To work around this problem, insert a space between the two opening
14964 parentheses.  There is a similar problem and workaround with
14965 @samp{$((}; see @ref{Shell Substitutions}.
14967 @node Slashes
14968 @section Slashes in Shell Scripts
14969 @cindex Shell slashes
14971 Unpatched Tru64 5.1 @command{sh} omits the last slash of command-line
14972 arguments that contain two trailing slashes:
14974 @example
14975 $ @kbd{echo / // /// //// .// //.}
14976 / / // /// ./ //.
14977 $ @kbd{x=//}
14978 $ @kbd{eval "echo \$x"}
14980 $ @kbd{set -x}
14981 $ @kbd{echo abc | tr -t ab //}
14982 + echo abc
14983 + tr -t ab /
14985 @end example
14987 Unpatched Tru64 4.0 @command{sh} adds a slash after @samp{"$var"} if the
14988 variable is empty and the second double-quote is followed by a word that
14989 begins and ends with slash:
14991 @example
14992 $ @kbd{sh -xc 'p=; echo "$p"/ouch/'}
14994 + echo //ouch/
14995 //ouch/
14996 @end example
14998 However, our understanding is that patches are available, so perhaps
14999 it's not worth worrying about working around these horrendous bugs.
15001 @node Special Shell Variables
15002 @section Special Shell Variables
15003 @cindex Shell variables
15004 @cindex Special shell variables
15006 Some shell variables should not be used, since they can have a deep
15007 influence on the behavior of the shell.  In order to recover a sane
15008 behavior from the shell, some variables should be unset; M4sh takes
15009 care of this and provides fallback values, whenever needed, to cater
15010 for a very old @file{/bin/sh} that does not support @command{unset}.
15011 (@pxref{Portable Shell, , Portable Shell Programming}).
15013 As a general rule, shell variable names containing a lower-case letter
15014 are safe; you can define and use these variables without worrying about
15015 their effect on the underlying system, and without worrying about
15016 whether the shell changes them unexpectedly.  (The exception is the
15017 shell variable @code{status}, as described below.)
15019 Here is a list of names that are known to cause trouble.  This list is
15020 not exhaustive, but you should be safe if you avoid the name
15021 @code{status} and names containing only upper-case letters and
15022 underscores.
15024 @c Alphabetical order, case insensitive, `A' before `a'.
15025 @table @code
15026 @item ?
15027 Not all shells correctly reset @samp{$?} after conditionals (@pxref{if,
15028 , Limitations of Shell Builtins}).  Not all shells manage @samp{$?}
15029 correctly in shell functions (@pxref{Shell Functions}) or in traps
15030 (@pxref{trap, , Limitations of Shell Builtins}).  Not all shells reset
15031 @samp{$?} to zero after an empty command.
15033 @example
15034 $ @kbd{bash -c 'false; $empty; echo $?'}
15036 $ @kbd{zsh -c 'false; $empty; echo $?'}
15038 @end example
15040 @item _
15041 @evindex _
15042 Many shells reserve @samp{$_} for various purposes, e.g., the name of
15043 the last command executed.
15045 @item BIN_SH
15046 @evindex BIN_SH
15047 In Tru64, if @env{BIN_SH} is set to @code{xpg4}, subsidiary invocations of
15048 the standard shell conform to Posix.
15050 @item CDPATH
15051 @evindex CDPATH
15052 When this variable is set it specifies a list of directories to search
15053 when invoking @code{cd} with a relative file name that did not start
15054 with @samp{./} or @samp{../}.  Posix
15055 1003.1-2001 says that if a nonempty directory name from @env{CDPATH}
15056 is used successfully, @code{cd} prints the resulting absolute
15057 file name.  Unfortunately this output can break idioms like
15058 @samp{abs=`cd src && pwd`} because @code{abs} receives the name twice.
15059 Also, many shells do not conform to this part of Posix; for
15060 example, @command{zsh} prints the result only if a directory name
15061 other than @file{.} was chosen from @env{CDPATH}.
15063 In practice the shells that have this problem also support
15064 @command{unset}, so you can work around the problem as follows:
15066 @example
15067 (unset CDPATH) >/dev/null 2>&1 && unset CDPATH
15068 @end example
15070 You can also avoid output by ensuring that your directory name is
15071 absolute or anchored at @samp{./}, as in @samp{abs=`cd ./src && pwd`}.
15073 Configure scripts use M4sh, which automatically unsets @env{CDPATH} if
15074 possible, so you need not worry about this problem in those scripts.
15076 @item CLICOLOR_FORCE
15077 @evindex CLICOLOR_FORCE
15078 When this variable is set, some implementations of tools like
15079 @command{ls} attempt to add color to their output via terminal escape
15080 sequences, even when the output is not directed to a terminal, and can
15081 thus cause spurious failures in scripts.  Configure scripts use M4sh,
15082 which automatically unsets this variable.
15084 @item DUALCASE
15085 @evindex DUALCASE
15086 In the MKS shell, case statements and file name generation are
15087 case-insensitive unless @env{DUALCASE} is nonzero.
15088 Autoconf-generated scripts export this variable when they start up.
15090 @item ENV
15091 @itemx MAIL
15092 @itemx MAILPATH
15093 @itemx PS1
15094 @itemx PS2
15095 @itemx PS4
15096 @evindex ENV
15097 @evindex MAIL
15098 @evindex MAILPATH
15099 @evindex PS1
15100 @evindex PS2
15101 @evindex PS4
15102 These variables should not matter for shell scripts, since they are
15103 supposed to affect only interactive shells.  However, at least one
15104 shell (the pre-3.0 @sc{uwin} Korn shell) gets confused about
15105 whether it is interactive, which means that (for example) a @env{PS1}
15106 with a side effect can unexpectedly modify @samp{$?}.  To work around
15107 this bug, M4sh scripts (including @file{configure} scripts) do something
15108 like this:
15110 @example
15111 (unset ENV) >/dev/null 2>&1 && unset ENV MAIL MAILPATH
15112 PS1='$ '
15113 PS2='> '
15114 PS4='+ '
15115 @end example
15117 @noindent
15118 (actually, there is some complication due to bugs in @command{unset};
15119 see @pxref{unset, , Limitations of Shell Builtins}).
15121 @item FPATH
15122 @evindex FPATH
15123 The Korn shell uses @env{FPATH} to find shell functions, so avoid
15124 @env{FPATH} in portable scripts.  @env{FPATH} is consulted after
15125 @env{PATH}, but you still need to be wary of tests that use @env{PATH}
15126 to find whether a command exists, since they might report the wrong
15127 result if @env{FPATH} is also set.
15129 @item GREP_OPTIONS
15130 @evindex GREP_OPTIONS
15131 When this variable is set, some implementations of @command{grep} honor
15132 these options, even if the options include direction to enable colored
15133 output via terminal escape sequences, and the result can cause spurious
15134 failures when the output is not directed to a terminal.  Configure
15135 scripts use M4sh, which automatically unsets this variable.
15137 @item IFS
15138 @evindex IFS
15139 Long ago, shell scripts inherited @env{IFS} from the environment,
15140 but this caused many problems so modern shells ignore any environment
15141 settings for @env{IFS}.
15143 Don't set the first character of @code{IFS} to backslash.  Indeed,
15144 Bourne shells use the first character (backslash) when joining the
15145 components in @samp{"$@@"} and some shells then reinterpret (!)@: the
15146 backslash escapes, so you can end up with backspace and other strange
15147 characters.
15149 The proper value for @code{IFS} (in regular code, not when performing
15150 splits) is @samp{@key{SPC}@key{TAB}@key{RET}}.  The first character is
15151 especially important, as it is used to join the arguments in @samp{$*};
15152 however, note that traditional shells, but also bash-2.04, fail to adhere
15153 to this and join with a space anyway.
15155 @item LANG
15156 @itemx LC_ALL
15157 @itemx LC_COLLATE
15158 @itemx LC_CTYPE
15159 @itemx LC_MESSAGES
15160 @itemx LC_MONETARY
15161 @itemx LC_NUMERIC
15162 @itemx LC_TIME
15163 @evindex LANG
15164 @evindex LC_ALL
15165 @evindex LC_COLLATE
15166 @evindex LC_CTYPE
15167 @evindex LC_MESSAGES
15168 @evindex LC_MONETARY
15169 @evindex LC_NUMERIC
15170 @evindex LC_TIME
15172 You should set all these variables to @samp{C} because so much
15173 configuration code assumes the C locale and Posix requires that locale
15174 environment variables be set to @samp{C} if the C locale is desired;
15175 @file{configure} scripts and M4sh do that for you.
15176 Export these variables after setting them.
15178 @c  However, some older, nonstandard
15179 @c  systems (notably @acronym{SCO}) break if locale environment variables
15180 @c  are set to @samp{C}, so when running on these systems
15181 @c  Autoconf-generated scripts unset the variables instead.
15183 @item LANGUAGE
15184 @evindex LANGUAGE
15186 @env{LANGUAGE} is not specified by Posix, but it is a @acronym{GNU}
15187 extension that overrides @env{LC_ALL} in some cases, so you (or M4sh)
15188 should set it too.
15190 @item LC_ADDRESS
15191 @itemx LC_IDENTIFICATION
15192 @itemx LC_MEASUREMENT
15193 @itemx LC_NAME
15194 @itemx LC_PAPER
15195 @itemx LC_TELEPHONE
15196 @evindex LC_ADDRESS
15197 @evindex LC_IDENTIFICATION
15198 @evindex LC_MEASUREMENT
15199 @evindex LC_NAME
15200 @evindex LC_PAPER
15201 @evindex LC_TELEPHONE
15203 These locale environment variables are @acronym{GNU} extensions.  They
15204 are treated like their Posix brethren (@env{LC_COLLATE},
15205 etc.)@: as described above.
15207 @item LINENO
15208 @evindex LINENO
15209 Most modern shells provide the current line number in @code{LINENO}.
15210 Its value is the line number of the beginning of the current command.
15211 M4sh, and hence Autoconf, attempts to execute @command{configure} with
15212 a shell that supports @code{LINENO}.  If no such shell is available, it
15213 attempts to implement @code{LINENO} with a Sed prepass that replaces each
15214 instance of the string @code{$LINENO} (not followed by an alphanumeric
15215 character) with the line's number.  In M4sh scripts you should execute
15216 @code{AS_LINENO_PREPARE} so that these workarounds are included in
15217 your script; configure scripts do this automatically in @code{AC_INIT}.
15219 You should not rely on @code{LINENO} within @command{eval} or shell
15220 functions, as the behavior differs in practice.  The presence of a
15221 quoted newline within simple commands can alter which line number is
15222 used as the starting point for @code{$LINENO} substitutions within that
15223 command.  Also, the possibility of the Sed prepass means that you should
15224 not rely on @code{$LINENO} when quoted, when in here-documents, or when
15225 line continuations are used.  Subshells should be OK, though.  In the
15226 following example, lines 1, 9, and 14 are portable, but the other
15227 instances of @code{$LINENO} do not have deterministic values:
15229 @example
15230 @group
15231 $ @kbd{cat lineno}
15232 echo 1. $LINENO
15233 echo "2. $LINENO
15234 3. $LINENO"
15235 cat <<EOF
15236 5. $LINENO
15237 6. $LINENO
15238 7. \$LINENO
15240 ( echo 9. $LINENO )
15241 eval 'echo 10. $LINENO'
15242 eval 'echo 11. $LINENO
15243 echo 12. $LINENO'
15244 echo 13. '$LINENO'
15245 echo 14. $LINENO '
15246 15.' $LINENO
15247 f () @{ echo $1 $LINENO;
15248 echo $1 $LINENO @}
15249 f 18.
15250 echo 19. \
15251 $LINENO
15252 @end group
15253 @group
15254 $ @kbd{bash-3.2 ./lineno}
15255 1. 1
15256 2. 3
15257 3. 3
15258 5. 4
15259 6. 4
15260 7. $LINENO
15261 9. 9
15262 10. 10
15263 11. 12
15264 12. 13
15265 13. $LINENO
15266 14. 14
15267 15. 14
15268 18. 16
15269 18. 17
15270 19. 19
15271 @end group
15272 @group
15273 $ @kbd{zsh-4.3.4 ./lineno}
15274 1. 1
15275 2. 2
15276 3. 2
15277 5. 4
15278 6. 4
15279 7. $LINENO
15280 9. 9
15281 10. 1
15282 11. 1
15283 12. 2
15284 13. $LINENO
15285 14. 14
15286 15. 14
15287 18. 0
15288 18. 1
15289 19. 19
15290 @end group
15291 @group
15292 $ @kbd{pdksh-5.2.14 ./lineno}
15293 1. 1
15294 2. 2
15295 3. 2
15296 5. 4
15297 6. 4
15298 7. $LINENO
15299 9. 9
15300 10. 0
15301 11. 0
15302 12. 0
15303 13. $LINENO
15304 14. 14
15305 15. 14
15306 18. 16
15307 18. 17
15308 19. 19
15309 @end group
15310 @group
15311 $ @kbd{sed '=' <lineno |}
15312 > @kbd{  sed '}
15313 > @kbd{    N}
15314 > @kbd{    s,$,-,}
15315 > @kbd{    t loop}
15316 > @kbd{    :loop}
15317 > @kbd{    s,^\([0-9]*\)\(.*\)[$]LINENO\([^a-zA-Z0-9_]\),\1\2\1\3,}
15318 > @kbd{    t loop}
15319 > @kbd{    s,-$,,}
15320 > @kbd{    s,^[0-9]*\n,,}
15321 > @kbd{  ' |}
15322 > @kbd{  sh}
15323 1. 1
15324 2. 2
15325 3. 3
15326 5. 5
15327 6. 6
15328 7. \7
15329 9. 9
15330 10. 10
15331 11. 11
15332 12. 12
15333 13. 13
15334 14. 14
15335 15. 15
15336 18. 16
15337 18. 17
15338 19. 20
15339 @end group
15340 @end example
15342 In particular, note that @file{config.status} (and any other subsidiary
15343 script created by @code{AS_INIT_GENERATED}) might report line numbers
15344 relative to the parent script as a result of the potential Sed pass.
15346 @item NULLCMD
15347 @evindex NULLCMD
15348 When executing the command @samp{>foo}, @command{zsh} executes
15349 @samp{$NULLCMD >foo} unless it is operating in Bourne shell
15350 compatibility mode and the @command{zsh} version is newer
15351 than 3.1.6-dev-18.  If you are using an older @command{zsh}
15352 and forget to set @env{NULLCMD},
15353 your script might be suspended waiting for data on its standard input.
15355 @item PATH_SEPARATOR
15356 @evindex PATH_SEPARATOR
15357 On @acronym{DJGPP} systems, the @env{PATH_SEPARATOR} environment
15358 variable can be set to either @samp{:} or @samp{;} to control the path
15359 separator Bash uses to set up certain environment variables (such as
15360 @env{PATH}).  You can set this variable to @samp{;} if you want
15361 @command{configure} to use @samp{;} as a separator; this might be useful
15362 if you plan to use non-Posix shells to execute files.  @xref{File System
15363 Conventions}, for more information about @code{PATH_SEPARATOR}.
15365 @item PWD
15366 @evindex PWD
15367 Posix 1003.1-2001 requires that @command{cd} and
15368 @command{pwd} must update the @env{PWD} environment variable to point
15369 to the logical name of the current directory, but traditional shells
15370 do not support this.  This can cause confusion if one shell instance
15371 maintains @env{PWD} but a subsidiary and different shell does not know
15372 about @env{PWD} and executes @command{cd}; in this case @env{PWD}
15373 points to the wrong directory.  Use @samp{`pwd`} rather than
15374 @samp{$PWD}.
15376 @item RANDOM
15377 @evindex RANDOM
15378 Many shells provide @code{RANDOM}, a variable that returns a different
15379 integer each time it is used.  Most of the time, its value does not
15380 change when it is not used, but on @sc{irix} 6.5 the value changes all
15381 the time.  This can be observed by using @command{set}.  It is common
15382 practice to use @code{$RANDOM} as part of a file name, but code
15383 shouldn't rely on @code{$RANDOM} expanding to a nonempty string.
15385 @item status
15386 @evindex status
15387 This variable is an alias to @samp{$?} for @code{zsh} (at least 3.1.6),
15388 hence read-only.  Do not use it.
15389 @end table
15391 @node Shell Functions
15392 @section Shell Functions
15393 @cindex Shell Functions
15395 Nowadays, it is difficult to find a shell that does not support
15396 shell functions at all.  However, some differences should be expected.
15398 Inside a shell function, you should not rely on the error status of a
15399 subshell if the last command of that subshell was @code{exit} or
15400 @code{trap}, as this triggers bugs in zsh 4.x; while Autoconf tries to
15401 find a shell that does not exhibit the bug, zsh might be the only shell
15402 present on the user's machine.
15404 Likewise, the state of @samp{$?} is not reliable when entering a shell
15405 function.  This has the effect that using a function as the first
15406 command in a @command{trap} handler can cause problems.
15408 @example
15409 $ @kbd{bash -c 'foo()@{ echo $?; @}; trap foo 0; (exit 2); exit 2'; echo $?}
15412 $ @kbd{ash -c 'foo()@{ echo $?; @}; trap foo 0; (exit 2); exit 2'; echo $?}
15415 @end example
15417 Not all shells treat shell functions as simple commands impacted by
15418 @samp{set -e}, for example with Solaris 10 @command{bin/sh}:
15420 @example
15421 $ @kbd{bash -c 'f()@{ return 1; @}; set -e; f; echo oops}
15422 $ @kbd{/bin/sh -c 'f()@{ return 1; @}; set -e; f; echo oops}
15423 oops
15424 @end example
15426 Shell variables and functions may share the same namespace, for example
15427 with Solaris 10 @command{/bin/sh}:
15429 @example
15430 $ @kbd{f () @{ :; @}; f=; f}
15431 f: not found
15432 @end example
15434 @noindent
15435 For this reason, Autoconf (actually M4sh, @pxref{Programming in M4sh})
15436 uses the prefix @samp{as_fn_} for its functions.
15438 Handling of positional parameters and shell options varies among shells.
15439 For example, Korn shells reset and restore trace output (@samp{set -x})
15440 and other options upon function entry and exit.  Inside a function,
15441 @acronym{IRIX} sh sets @samp{$0} to the function name.
15443 It is not portable to pass temporary environment variables to shell
15444 functions.  Solaris @command{/bin/sh} does not see the variable.
15445 Meanwhile, not all shells follow the Posix rule that the assignment must
15446 affect the current environment in the same manner as special built-ins.
15448 @example
15449 $ @kbd{/bin/sh -c 'func()@{ echo $a;@}; a=1 func; echo $a'}
15450 @result{}
15451 @result{}
15452 $ @kbd{ash -c 'func()@{ echo $a;@}; a=1 func; echo $a'}
15453 @result{}1
15454 @result{}
15455 $ @kbd{bash -c 'set -o posix; func()@{ echo $a;@}; a=1 func; echo $a'}
15456 @result{}1
15457 @result{}1
15458 @end example
15460 Some ancient Bourne shell variants with function support did not reset
15461 @samp{$@var{i}, @var{i} >= 0}, upon function exit, so effectively the
15462 arguments of the script were lost after the first function invocation.
15463 It is probably not worth worrying about these shells any more.
15465 With @acronym{AIX} sh, a @command{trap} on 0 installed in a shell function
15466 triggers at function exit rather than at script exit, see @xref{trap, ,
15467 Limitations of Shell Builtins}.
15469 @node Limitations of Builtins
15470 @section Limitations of Shell Builtins
15471 @cindex Shell builtins
15472 @cindex Limitations of shell builtins
15474 No, no, we are serious: some shells do have limitations!  :)
15476 You should always keep in mind that any builtin or command may support
15477 options, and therefore differ in behavior with arguments
15478 starting with a dash.  For instance, even the innocent @samp{echo "$word"}
15479 can give unexpected results when @code{word} starts with a dash.  It is
15480 often possible to avoid this problem using @samp{echo "x$word"}, taking
15481 the @samp{x} into account later in the pipe.  Many of these limitations
15482 can be worked around using M4sh (@pxref{Programming in M4sh}).
15484 @c This table includes things like `@command{test} (files)', so we can't
15485 @c use @table @command.
15486 @table @asis
15487 @item @command{.}
15488 @c --------------
15489 @prindex @command{.}
15490 Use @command{.} only with regular files (use @samp{test -f}).  Bash
15491 2.03, for instance, chokes on @samp{. /dev/null}.  Remember that
15492 @command{.} uses @env{PATH} if its argument contains no slashes.  Also,
15493 some shells, including bash 3.2, implicitly append the current directory
15494 to this @env{PATH} search, even though Posix forbids it.  So if you want
15495 to use @command{.} on a file @file{foo} in the current directory, you
15496 must use @samp{. ./foo}.
15498 Not all shells gracefully handle syntax errors within a sourced file.
15499 On one extreme, some non-interactive shells abort the entire script.  On
15500 the other, @command{zsh} 4.3.10 has a bug where it fails to react to the
15501 syntax error.
15503 @example
15504 $ @kbd{echo 'fi' > syntax}
15505 $ @kbd{bash -c '. ./syntax; echo $?'}
15506 ./syntax: line 1: syntax error near unexpected token `fi'
15507 ./syntax: line 1: `fi'
15509 $ @kbd{ash -c '. ./syntax; echo $?'}
15510 ./syntax: 1: Syntax error: "fi" unexpected
15511 $ @kbd{zsh -c '. ./syntax; echo $?'}
15512 ./syntax:1: parse error near `fi'
15514 @end example
15516 @item @command{!}
15517 @c --------------
15518 @prindex @command{!}
15519 The Unix version 7 shell did not support
15520 negating the exit status of commands with @command{!}, and this feature
15521 is still absent from some shells (e.g., Solaris @command{/bin/sh}).
15522 Other shells, such as FreeBSD @command{/bin/sh} or @command{ash}, have
15523 bugs when using @command{!}:
15525 @example
15526 $ @kbd{sh -c '! : | :'; echo $?}
15528 $ @kbd{ash -c '! : | :'; echo $?}
15530 $ @kbd{sh -c '! @{ :; @}'; echo $?}
15532 $ @kbd{ash -c '! @{ :; @}'; echo $?}
15533 @{: not found
15534 Syntax error: "@}" unexpected
15536 @end example
15538 Shell code like this:
15540 @example
15541 if ! cmp file1 file2 >/dev/null 2>&1; then
15542   echo files differ or trouble
15544 @end example
15546 is therefore not portable in practice.  Typically it is easy to rewrite
15547 such code, e.g.:
15549 @example
15550 cmp file1 file2 >/dev/null 2>&1 ||
15551   echo files differ or trouble
15552 @end example
15554 More generally, one can always rewrite @samp{! @var{command}} as:
15556 @example
15557 if @var{command}; then (exit 1); else :; fi
15558 @end example
15561 @item @command{@{...@}}
15562 @c --------------------
15563 @prindex @command{@{...@}}
15564 Bash 3.2 (and earlier versions) sometimes does not properly set
15565 @samp{$?} when failing to write redirected output of a compound command.
15566 This problem is most commonly observed with @samp{@{@dots{}@}}; it does
15567 not occur with @samp{(@dots{})}.  For example:
15569 @example
15570 $ @kbd{bash -c '@{ echo foo; @} >/bad; echo $?'}
15571 bash: line 1: /bad: Permission denied
15573 $ @kbd{bash -c 'while :; do echo; done >/bad; echo $?'}
15574 bash: line 1: /bad: Permission denied
15576 @end example
15578 To work around the bug, prepend @samp{:;}:
15580 @example
15581 $ @kbd{bash -c ':;@{ echo foo; @} >/bad; echo $?'}
15582 bash: line 1: /bad: Permission denied
15584 @end example
15586 Posix requires a syntax error if a brace list has no contents.  However,
15587 not all shells obey this rule; and on shells where empty lists are
15588 permitted, the effect on @samp{$?} is inconsistent.  To avoid problems,
15589 ensure that a brace list is never empty.
15591 @example
15592 $ @kbd{bash -c 'false; @{ @}; echo $?' || echo $?}
15593 bash: line 1: syntax error near unexpected token `@}'
15594 bash: line 1: `false; @{ @}; echo $?'
15596 $ @kbd{zsh -c 'false; @{ @}; echo $?' || echo $?}
15598 $ @kbd{pdksh -c 'false; @{ @}; echo $?' || echo $?}
15600 @end example
15603 @item @command{break}
15604 @c ------------------
15605 @prindex @command{break}
15606 The use of @samp{break 2} etc.@: is safe.
15609 @anchor{case}
15610 @item @command{case}
15611 @c -----------------
15612 @prindex @command{case}
15613 You don't need to quote the argument; no splitting is performed.
15615 You don't need the final @samp{;;}, but you should use it.
15617 Posix requires support for @code{case} patterns with opening
15618 parentheses like this:
15620 @example
15621 case $file_name in
15622   (*.c) echo "C source code";;
15623 esac
15624 @end example
15626 @noindent
15627 but the @code{(} in this example is not portable to many Bourne
15628 shell implementations, which is a pity for those of us using tools that
15629 rely on balanced parentheses.  For instance, with Solaris
15630 @command{/bin/sh}:
15632 @example
15633 $ @kbd{case foo in (foo) echo foo;; esac}
15634 @error{}syntax error: `(' unexpected
15635 @end example
15637 @noindent
15638 The leading @samp{(} can be omitted safely.  Unfortunately, there are
15639 contexts where unbalanced parentheses cause other problems, such as when
15640 using a syntax-highlighting editor that searches for the balancing
15641 counterpart, or more importantly, when using a case statement as an
15642 underquoted argument to an Autoconf macro.  @xref{Balancing
15643 Parentheses}, for tradeoffs involved in various styles of dealing with
15644 unbalanced @samp{)}.
15646 Zsh handles pattern fragments derived from parameter expansions or
15647 command substitutions as though quoted:
15649 @example
15650 $ pat=\?; case aa in ?$pat) echo match;; esac
15651 $ pat=\?; case a? in ?$pat) echo match;; esac
15652 match
15653 @end example
15655 @noindent
15656 Because of a bug in its @code{fnmatch}, Bash fails to properly
15657 handle backslashes in character classes:
15659 @example
15660 bash-2.02$ @kbd{case /tmp in [/\\]*) echo OK;; esac}
15661 bash-2.02$
15662 @end example
15664 @noindent
15665 This is extremely unfortunate, since you are likely to use this code to
15666 handle Posix or @sc{ms-dos} absolute file names.  To work around this
15667 bug, always put the backslash first:
15669 @example
15670 bash-2.02$ @kbd{case '\TMP' in [\\/]*) echo OK;; esac}
15672 bash-2.02$ @kbd{case /tmp in [\\/]*) echo OK;; esac}
15674 @end example
15676 Many Bourne shells cannot handle closing brackets in character classes
15677 correctly.
15679 Some shells also have problems with backslash escaping in case you do not want
15680 to match the backslash: both a backslash and the escaped character match this
15681 pattern.  To work around this, specify the character class in a variable, so
15682 that quote removal does not apply afterwards, and the special characters don't
15683 have to be backslash-escaped:
15685 @example
15686 $ @kbd{case '\' in [\<]) echo OK;; esac}
15688 $ @kbd{scanset='[<]'; case '\' in $scanset) echo OK;; esac}
15690 @end example
15692 Even with this, Solaris @command{ksh} matches a backslash if the set
15693 contains any
15694 of the characters @samp{|}, @samp{&}, @samp{(}, or @samp{)}.
15696 Conversely, Tru64 @command{ksh} (circa 2003) erroneously always matches
15697 a closing parenthesis if not specified in a character class:
15699 @example
15700 $ @kbd{case foo in *\)*) echo fail ;; esac}
15701 fail
15702 $ @kbd{case foo in *')'*) echo fail ;; esac}
15703 fail
15704 @end example
15706 Some shells, such as Ash 0.3.8, are confused by an empty
15707 @code{case}/@code{esac}:
15709 @example
15710 ash-0.3.8 $ @kbd{case foo in esac;}
15711 @error{}Syntax error: ";" unexpected (expecting ")")
15712 @end example
15714 Posix requires @command{case} to give an exit status of 0 if no cases
15715 match.  However, @command{/bin/sh} in Solaris 10 does not obey this
15716 rule.  Meanwhile, it is unclear whether a case that matches, but
15717 contains no statements, must also change the exit status to 0.  The M4sh
15718 macro @code{AS_CASE} works around these inconsistencies.
15720 @example
15721 $ @kbd{bash -c 'case `false` in ?) ;; esac; echo $?'}
15723 $ @kbd{/bin/sh -c 'case `false` in ?) ;; esac; echo $?'}
15725 @end example
15728 @item @command{cd}
15729 @c ---------------
15730 @prindex @command{cd}
15731 Posix 1003.1-2001 requires that @command{cd} must support
15732 the @option{-L} (``logical'') and @option{-P} (``physical'') options,
15733 with @option{-L} being the default.  However, traditional shells do
15734 not support these options, and their @command{cd} command has the
15735 @option{-P} behavior.
15737 Portable scripts should assume neither option is supported, and should
15738 assume neither behavior is the default.  This can be a bit tricky,
15739 since the Posix default behavior means that, for example,
15740 @samp{ls ..} and @samp{cd ..} may refer to different directories if
15741 the current logical directory is a symbolic link.  It is safe to use
15742 @code{cd @var{dir}} if @var{dir} contains no @file{..} components.
15743 Also, Autoconf-generated scripts check for this problem when computing
15744 variables like @code{ac_top_srcdir} (@pxref{Configuration Actions}),
15745 so it is safe to @command{cd} to these variables.
15747 See @xref{Special Shell Variables}, for portability problems involving
15748 @command{cd} and the @env{CDPATH} environment variable.
15749 Also please see the discussion of the @command{pwd} command.
15752 @anchor{echo}
15753 @item @command{echo}
15754 @c -----------------
15755 @prindex @command{echo}
15756 The simple @command{echo} is probably the most surprising source of
15757 portability troubles.  It is not possible to use @samp{echo} portably
15758 unless both options and escape sequences are omitted.  Don't expect any
15759 option.
15761 Do not use backslashes in the arguments, as there is no consensus on
15762 their handling.  For @samp{echo '\n' | wc -l}, the @command{sh} of
15763 Solaris outputs 2, but Bash and Zsh (in @command{sh} emulation mode) output 1.
15764 The problem is truly @command{echo}: all the shells
15765 understand @samp{'\n'} as the string composed of a backslash and an
15766 @samp{n}.  Within a command substitution, @samp{echo 'string\c'} will
15767 mess up the internal state of ksh88 on AIX 6.1 so that it will print
15768 the first character @samp{s} only, followed by a newline, and then
15769 entirely drop the output of the next echo in a command substitution.
15771 Because of these problems, do not pass a string containing arbitrary
15772 characters to @command{echo}.  For example, @samp{echo "$foo"} is safe
15773 if you know that @var{foo}'s value cannot contain backslashes and cannot
15774 start with @samp{-}, but otherwise you should use a here-document like
15775 this:
15777 @example
15778 cat <<EOF
15779 $foo
15781 @end example
15783 New applications which are not aiming at portability should use
15784 @command{printf} instead of @command{echo}.  M4sh provides the
15785 @code{AS_ECHO} and @code{AS_ECHO_N} macros, which choose between
15786 @samp{echo -n} on implementations where that works, @command{printf} if
15787 it is available, or other creative tricks in order to work around the
15788 above problems.
15791 @item @command{eval}
15792 @c -----------------
15793 @prindex @command{eval}
15794 The @command{eval} command is useful in limited circumstances, e.g.,
15795 using commands like @samp{eval table_$key=\$value} and @samp{eval
15796 value=table_$key} to simulate a hash table when the key is known to be
15797 alphanumeric.
15799 You should also be wary of common bugs in @command{eval} implementations.
15800 In some shell implementations (e.g., older @command{ash}, Open@acronym{BSD} 3.8
15801 @command{sh}, @command{pdksh} v5.2.14 99/07/13.2, and @command{zsh}
15802 4.2.5), the arguments of @samp{eval} are evaluated in a context where
15803 @samp{$?} is 0, so they exhibit behavior like this:
15805 @example
15806 $ @kbd{false; eval 'echo $?'}
15808 @end example
15810 The correct behavior here is to output a nonzero value,
15811 but portable scripts should not rely on this.
15813 You should not rely on @code{LINENO} within @command{eval}.
15814 @xref{Special Shell Variables}.
15816 Note that, even though these bugs are easily avoided,
15817 @command{eval} is tricky to use on arbitrary arguments.
15818 It is obviously unwise to use @samp{eval $cmd} if the string value of
15819 @samp{cmd} was derived from an untrustworthy source.  But even if the
15820 string value is valid, @samp{eval $cmd} might not work as intended,
15821 since it causes field splitting and file name expansion to occur twice,
15822 once for the @command{eval} and once for the command itself.  It is
15823 therefore safer to use @samp{eval "$cmd"}.  For example, if @var{cmd}
15824 has the value @samp{cat test?.c}, @samp{eval $cmd} might expand to the
15825 equivalent of @samp{cat test;.c} if there happens to be a file named
15826 @file{test;.c} in the current directory; and this in turn
15827 mistakenly attempts to invoke @command{cat} on the file @file{test} and
15828 then execute the command @command{.c}.  To avoid this problem, use
15829 @samp{eval "$cmd"} rather than @samp{eval $cmd}.
15831 However, suppose that you want to output the text of the evaluated
15832 command just before executing it.  Assuming the previous example,
15833 @samp{echo "Executing: $cmd"} outputs @samp{Executing: cat test?.c}, but
15834 this output doesn't show the user that @samp{test;.c} is the actual name
15835 of the copied file.  Conversely, @samp{eval "echo Executing: $cmd"}
15836 works on this example, but it fails with @samp{cmd='cat foo >bar'},
15837 since it mistakenly replaces the contents of @file{bar} by the
15838 string @samp{cat foo}.  No simple, general, and portable solution to
15839 this problem is known.
15841 @item @command{exec}
15842 @c -----------------
15843 @prindex @command{exec}
15844 Posix describes several categories of shell built-ins.  Special
15845 built-ins (such as @command{exit}) must impact the environment of the
15846 current shell, and need not be available through @command{exec}.  All
15847 other built-ins are regular, and must not propagate variable assignments
15848 to the environment of the current shell.  However, the group of regular
15849 built-ins is further distinguished by commands that do not require a
15850 @env{PATH} search (such as @command{cd}), in contrast to built-ins that
15851 are offered as a more efficient version of something that must still be
15852 found in a @env{PATH} search (such as @command{echo}).  Posix is not
15853 clear on whether @command{exec} must work with the list of 17 utilities
15854 that are invoked without a @env{PATH} search, and many platforms lack an
15855 executable for some of those built-ins:
15857 @example
15858 $ @kbd{sh -c 'exec cd /tmp'}
15859 sh: line 0: exec: cd: not found
15860 @end example
15862 All other built-ins that provide utilities specified by Posix must have
15863 a counterpart executable that exists on @env{PATH}, although Posix
15864 allows @command{exec} to use the built-in instead of the executable.
15865 For example, contrast @command{bash} 3.2 and @command{pdksh} 5.2.14:
15867 @example
15868 $ @kbd{bash -c 'pwd --version' | head -n1}
15869 bash: line 0: pwd: --: invalid option
15870 pwd: usage: pwd [-LP]
15871 $ @kbd{bash -c 'exec pwd --version' | head -n1}
15872 pwd (GNU coreutils) 6.10
15873 $ @kbd{pdksh -c 'exec pwd --version' | head -n1}
15874 pdksh: pwd: --: unknown option
15875 @end example
15877 When it is desired to avoid a regular shell built-in, the workaround is
15878 to use some other forwarding command, such as @command{env} or
15879 @command{nice}, that will ensure a path search:
15881 @example
15882 $ @kbd{pdksh -c 'exec true --version' | head -n1}
15883 $ @kbd{pdksh -c 'nice true --version' | head -n1}
15884 true (GNU coreutils) 6.10
15885 $ @kbd{pdksh -c 'env true --version' | head -n1}
15886 true (GNU coreutils) 6.10
15887 @end example
15889 @item @command{exit}
15890 @c -----------------
15891 @prindex @command{exit}
15892 The default value of @command{exit} is supposed to be @code{$?};
15893 unfortunately, some shells, such as the @acronym{DJGPP} port of Bash 2.04, just
15894 perform @samp{exit 0}.
15896 @example
15897 bash-2.04$ @kbd{foo=`exit 1` || echo fail}
15898 fail
15899 bash-2.04$ @kbd{foo=`(exit 1)` || echo fail}
15900 fail
15901 bash-2.04$ @kbd{foo=`(exit 1); exit` || echo fail}
15902 bash-2.04$
15903 @end example
15905 Using @samp{exit $?} restores the expected behavior.
15907 Some shell scripts, such as those generated by @command{autoconf}, use a
15908 trap to clean up before exiting.  If the last shell command exited with
15909 nonzero status, the trap also exits with nonzero status so that the
15910 invoker can tell that an error occurred.
15912 Unfortunately, in some shells, such as Solaris @command{/bin/sh}, an exit
15913 trap ignores the @code{exit} command's argument.  In these shells, a trap
15914 cannot determine whether it was invoked by plain @code{exit} or by
15915 @code{exit 1}.  Instead of calling @code{exit} directly, use the
15916 @code{AC_MSG_ERROR} macro that has a workaround for this problem.
15919 @anchor{export}
15920 @item @command{export}
15921 @c -------------------
15922 @prindex @command{export}
15923 The builtin @command{export} dubs a shell variable @dfn{environment
15924 variable}.  Each update of exported variables corresponds to an update
15925 of the environment variables.  Conversely, each environment variable
15926 received by the shell when it is launched should be imported as a shell
15927 variable marked as exported.
15929 Alas, many shells, such as Solaris @command{/bin/sh},
15930 @sc{irix} 6.3, @sc{irix} 5.2,
15931 @acronym{AIX} 4.1.5, and Digital Unix 4.0, forget to
15932 @command{export} the environment variables they receive.  As a result,
15933 two variables coexist: the environment variable and the shell
15934 variable.  The following code demonstrates this failure:
15936 @example
15937 #!/bin/sh
15938 echo $FOO
15939 FOO=bar
15940 echo $FOO
15941 exec /bin/sh $0
15942 @end example
15944 @noindent
15945 when run with @samp{FOO=foo} in the environment, these shells print
15946 alternately @samp{foo} and @samp{bar}, although they should print only
15947 @samp{foo} and then a sequence of @samp{bar}s.
15949 Therefore you should @command{export} again each environment variable
15950 that you update; the export can occur before or after the assignment.
15952 Posix is not clear on whether the @command{export} of an undefined
15953 variable causes the variable to be defined with the value of an empty
15954 string, or merely marks any future definition of a variable by that name
15955 for export.  Various shells behave differently in this regard:
15957 @example
15958 $ @kbd{sh -c 'export foo; env | grep foo'}
15959 $ @kbd{ash -c 'export foo; env | grep foo'}
15960 foo=
15961 @end example
15963 @item @command{false}
15964 @c ------------------
15965 @prindex @command{false}
15966 Don't expect @command{false} to exit with status 1: in native
15967 Solaris @file{/bin/false} exits with status 255.
15970 @item @command{for}
15971 @c ----------------
15972 @prindex @command{for}
15973 To loop over positional arguments, use:
15975 @example
15976 for arg
15978   echo "$arg"
15979 done
15980 @end example
15982 @noindent
15983 You may @emph{not} leave the @code{do} on the same line as @code{for},
15984 since some shells improperly grok:
15986 @example
15987 for arg; do
15988   echo "$arg"
15989 done
15990 @end example
15992 If you want to explicitly refer to the positional arguments, given the
15993 @samp{$@@} bug (@pxref{Shell Substitutions}), use:
15995 @example
15996 for arg in $@{1+"$@@"@}; do
15997   echo "$arg"
15998 done
15999 @end example
16001 @noindent
16002 But keep in mind that Zsh, even in Bourne shell emulation mode, performs
16003 word splitting on @samp{$@{1+"$@@"@}}; see @ref{Shell Substitutions},
16004 item @samp{$@@}, for more.
16007 @anchor{if}
16008 @item @command{if}
16009 @c ---------------
16010 @prindex @command{if}
16011 Using @samp{!} is not portable.  Instead of:
16013 @example
16014 if ! cmp -s file file.new; then
16015   mv file.new file
16017 @end example
16019 @noindent
16020 use:
16022 @example
16023 if cmp -s file file.new; then :; else
16024   mv file.new file
16026 @end example
16028 @noindent
16029 Or, especially if the @dfn{else} branch is short, you can use @code{||}.
16030 In M4sh, the @code{AS_IF} macro provides an easy way to write these kinds
16031 of conditionals:
16033 @example
16034 AS_IF([cmp -s file file.new], [], [mv file.new file])
16035 @end example
16037 This is especially useful in other M4 macros, where the @dfn{then} and
16038 @dfn{else} branches might be macro arguments.
16040 Some very old shells did not reset the exit status from an @command{if}
16041 with no @command{else}:
16043 @example
16044 $ @kbd{if (exit 42); then true; fi; echo $?}
16046 @end example
16048 @noindent
16049 whereas a proper shell should have printed @samp{0}.  But this is no
16050 longer a portability problem; any shell that supports functions gets it
16051 correct.  However, it explains why some makefiles have lengthy
16052 constructs:
16054 @example
16055 if test -f "$file"; then
16056   install "$file" "$dest"
16057 else
16058   :
16060 @end example
16063 @item @command{printf}
16064 @c ------------------
16065 @prindex @command{printf}
16066 A format string starting with a @samp{-} can cause problems.
16067 Bash interprets it as an option and
16068 gives an error.  And @samp{--} to mark the end of options is not good
16069 in the Net@acronym{BSD} Almquist shell (e.g., 0.4.6) which takes that
16070 literally as the format string.  Putting the @samp{-} in a @samp{%c}
16071 or @samp{%s} is probably easiest:
16073 @example
16074 printf %s -foo
16075 @end example
16077 Bash 2.03 mishandles an escape sequence that happens to evaluate to @samp{%}:
16079 @example
16080 $ @kbd{printf '\045'}
16081 bash: printf: `%': missing format character
16082 @end example
16084 Large outputs may cause trouble.  On Solaris 2.5.1 through 10, for
16085 example, @file{/usr/bin/printf} is buggy, so when using
16086 @command{/bin/sh} the command @samp{printf %010000x 123} normally dumps
16087 core.
16089 Since @command{printf} is not always a shell builtin, there is a
16090 potential speed penalty for using @code{printf %s\\n} as a replacement
16091 for an @command{echo} that does not interpret @samp{\} or leading
16092 @samp{-}. With Solaris @command{ksh}, it is possible to use @code{print
16093 -r --} for this role instead.
16096 @item @command{pwd}
16097 @c ----------------
16098 @prindex @command{pwd}
16099 With modern shells, plain @command{pwd} outputs a ``logical''
16100 directory name, some of whose components may be symbolic links.  These
16101 directory names are in contrast to ``physical'' directory names, whose
16102 components are all directories.
16104 Posix 1003.1-2001 requires that @command{pwd} must support
16105 the @option{-L} (``logical'') and @option{-P} (``physical'') options,
16106 with @option{-L} being the default.  However, traditional shells do
16107 not support these options, and their @command{pwd} command has the
16108 @option{-P} behavior.
16110 Portable scripts should assume neither option is supported, and should
16111 assume neither behavior is the default.  Also, on many hosts
16112 @samp{/bin/pwd} is equivalent to @samp{pwd -P}, but Posix
16113 does not require this behavior and portable scripts should not rely on
16116 Typically it's best to use plain @command{pwd}.  On modern hosts this
16117 outputs logical directory names, which have the following advantages:
16119 @itemize @bullet
16120 @item
16121 Logical names are what the user specified.
16122 @item
16123 Physical names may not be portable from one installation
16124 host to another due to network file system gymnastics.
16125 @item
16126 On modern hosts @samp{pwd -P} may fail due to lack of permissions to
16127 some parent directory, but plain @command{pwd} cannot fail for this
16128 reason.
16129 @end itemize
16131 Also please see the discussion of the @command{cd} command.
16134 @item @command{read}
16135 @c -----------------
16136 @prindex @command{read}
16137 No options are portable, not even support @option{-r} (Solaris
16138 @command{/bin/sh} for example).
16141 @anchor{set}
16142 @item @command{set}
16143 @c ----------------
16144 @prindex @command{set}
16145 With the Free@acronym{BSD} 6.0 shell, the @command{set} command (without
16146 any options) does not sort its output.
16148 The @command{set} builtin faces the usual problem with arguments
16149 starting with a
16150 dash.  Modern shells such as Bash or Zsh understand @option{--} to specify
16151 the end of the options (any argument after @option{--} is a parameter,
16152 even @samp{-x} for instance), but many traditional shells (e.g., Solaris
16153 10 @command{/bin/sh}) simply stop option
16154 processing as soon as a non-option argument is found.  Therefore, use
16155 @samp{dummy} or simply @samp{x} to end the option processing, and use
16156 @command{shift} to pop it out:
16158 @example
16159 set x $my_list; shift
16160 @end example
16162 Avoid @samp{set -}, e.g., @samp{set - $my_list}.  Posix no
16163 longer requires support for this command, and in traditional shells
16164 @samp{set - $my_list} resets the @option{-v} and @option{-x} options, which
16165 makes scripts harder to debug.
16167 Some nonstandard shells do not recognize more than one option
16168 (e.g., @samp{set -e -x} assigns @samp{-x} to the command line).  It is
16169 better to combine them:
16171 @example
16172 set -ex
16173 @end example
16175 @cindex @command{set -e}
16176 The option @option{-e} has historically been underspecified, with enough
16177 ambiguities to cause numerous differences across various shell
16178 implementations.  Perhaps the best reference is
16179 @uref{http://www.opengroup.org/@/austin/@/mailarchives/@/ag-review/@/msg03507.html,
16180 this link}, recommending a change to Posix 2008 to match @command{ksh88}
16181 behavior.  Note that mixing @code{set -e} and shell functions is asking
16182 for surprises:
16184 @example
16185 set -e
16186 doit()
16188   rm file
16189   echo one
16191 doit || echo two
16192 @end example
16194 @noindent
16195 According to the recommendation, @samp{one} should always be output
16196 regardless of whether the @command{rm} failed, because it occurs within
16197 the body of the shell function @samp{doit} invoked on the left side of
16198 @samp{||}, where the effects of @samp{set -e} are not enforced.
16199 Likewise, @samp{two} should never be printed, since the failure of
16200 @command{rm} does not abort the function, such that the status of
16201 @samp{doit} is 0.
16203 The @acronym{BSD} shell has had several problems with the @option{-e}
16204 option.  Older versions of the @acronym{BSD}
16205 shell (circa 1990) mishandled @samp{&&}, @samp{||}, @samp{if}, and
16206 @samp{case} when @option{-e} was in effect, causing the shell to exit
16207 unexpectedly in some cases.  This was particularly a problem with
16208 makefiles, and led to circumlocutions like @samp{sh -c 'test -f file ||
16209 touch file'}, where the seemingly-unnecessary @samp{sh -c '@dots{}'}
16210 wrapper works around the bug (@pxref{Failure in Make Rules}).
16212 Even relatively-recent versions of the @acronym{BSD} shell (e.g.,
16213 Open@acronym{BSD} 3.4) wrongly exit with @option{-e} if a command within
16214 @samp{&&} fails inside a compound statement.  For example:
16216 @example
16217 #! /bin/sh
16218 set -e
16219 foo=''
16220 test -n "$foo" && exit 1
16221 echo one
16222 if :; then
16223   test -n "$foo" && exit 1
16225 echo two
16226 @end example
16228 @noindent
16229 does not print @samp{two}.  One workaround is to use @samp{if test -n
16230 "$foo"; then exit 1; fi} rather than @samp{test -n "$foo" && exit 1}.
16231 Another possibility is to warn @acronym{BSD} users not to use @samp{sh -e}.
16233 When @samp{set -e} is in effect, a failed command substitution in
16234 Solaris @command{/bin/sh} cannot be ignored, even with @samp{||}.
16236 @example
16237 $ @kbd{/bin/sh -c 'set -d; foo=`false` || echo foo; echo bar'}
16238 $ @kbd{bash -c 'set -d; foo=`false` || echo foo; echo bar'}
16241 @end example
16243 Portable scripts should not use @samp{set -e} if @command{trap} is used
16244 to install an exit handler.  This is because Tru64/OSF 5.1 @command{sh}
16245 sometimes enters the trap handler with the exit status of the command
16246 prior to the one that triggered the errexit handler:
16248 @example
16249 $ @kbd{sh -ec 'trap '\''echo $?'\'' 0; false'}
16251 $ @kbd{sh -c 'set -e; trap '\''echo $?'\'' 0; false'}
16253 @end example
16255 @noindent
16256 Thus, when writing a script in M4sh, rather than trying to rely on
16257 @samp{set -e}, it is better to append @samp{|| AS_EXIT} to any
16258 statement where it is desirable to abort on failure.
16260 @item @command{shift}
16261 @c ------------------
16262 @prindex @command{shift}
16263 Not only is @command{shift}ing a bad idea when there is nothing left to
16264 shift, but in addition it is not portable: the shell of @acronym{MIPS
16265 RISC/OS} 4.52 refuses to do it.
16267 Don't use @samp{shift 2} etc.; while it in the SVR1 shell (1983),
16268 it is also absent in many pre-Posix shells.
16271 @item @command{source}
16272 @c -------------------
16273 @prindex @command{source}
16274 This command is not portable, as Posix does not require it; use
16275 @command{.} instead.
16278 @item @command{test}
16279 @c -----------------
16280 @prindex @command{test}
16281 The @code{test} program is the way to perform many file and string
16282 tests.  It is often invoked by the alternate name @samp{[}, but using
16283 that name in Autoconf code is asking for trouble since it is an M4 quote
16284 character.
16286 The @option{-a}, @option{-o}, @samp{(}, and @samp{)} operands are not
16287 portable and should be avoided.  Thus, portable uses of @command{test}
16288 should never have more than four arguments, and scripts should use shell
16289 constructs like @samp{&&} and @samp{||} instead.  If you combine
16290 @samp{&&} and @samp{||} in the same statement, keep in mind that they
16291 have equal precedence, so it is often better to parenthesize even when
16292 this is redundant.  For example:
16294 @smallexample
16295 # Not portable:
16296 test "X$a" = "X$b" -a \
16297   '(' "X$c" != "X$d" -o "X$e" = "X$f" ')'
16299 # Portable:
16300 test "X$a" = "X$b" &&
16301   @{ test "X$c" != "X$d" || test "X$e" = "X$f"; @}
16302 @end smallexample
16304 @command{test} does not process options like most other commands do; for
16305 example, it does not recognize the @option{--} argument as marking the
16306 end of options.
16308 It is safe to use @samp{!} as a @command{test} operator.  For example,
16309 @samp{if test ! -d foo; @dots{}} is portable even though @samp{if ! test
16310 -d foo; @dots{}} is not.
16313 @item @command{test} (files)
16314 @c -------------------------
16315 To enable @command{configure} scripts to support cross-compilation, they
16316 shouldn't do anything that tests features of the build system instead of
16317 the host system.  But occasionally you may find it necessary to check
16318 whether some arbitrary file exists.  To do so, use @samp{test -f} or
16319 @samp{test -r}.  Do not use @samp{test -x}, because 4.3@acronym{BSD} does not
16320 have it.  Do not use @samp{test -e} either, because Solaris @command{/bin/sh}
16321 lacks it.  To test for symbolic links on systems that have them, use
16322 @samp{test -h} rather than @samp{test -L}; either form conforms to
16323 Posix 1003.1-2001, but older shells like Solaris 8
16324 @code{/bin/sh} support only @option{-h}.
16326 @item @command{test} (strings)
16327 @c ---------------------------
16328 Posix says that @samp{test "@var{string}"} succeeds if @var{string} is
16329 not null, but this usage is not portable to traditional platforms like
16330 Solaris 10 @command{/bin/sh}, which mishandle strings like @samp{!} and
16331 @samp{-n}.
16333 Posix also says that @samp{test ! "@var{string}"},
16334 @samp{test -n "@var{string}"} and
16335 @samp{test -z "@var{string}"} work with any string, but many
16336 shells (such as Solaris, @acronym{AIX} 3.2, @sc{unicos} 10.0.0.6,
16337 Digital Unix 4, etc.)@: get confused if
16338 @var{string} looks like an operator:
16340 @example
16341 $ @kbd{test -n =}
16342 test: argument expected
16343 $ @kbd{test ! -n}
16344 test: argument expected
16345 @end example
16347 Similarly, Posix says that both @samp{test "@var{string1}" = "@var{string2"}}
16348 and @samp{test "@var{string1}" != "@var{string2"}} work for any pairs of
16349 strings, but in practice this is not true for troublesome strings that
16350 look like operators or parentheses, or that begin with @samp{-}.
16352 It is best to protect such strings with a leading @samp{X}, e.g.,
16353 @samp{test "X@var{string}" != X} rather than @samp{test -n
16354 "@var{string}"} or @samp{test ! "@var{string}"}.
16356 It is common to find variations of the following idiom:
16358 @example
16359 test -n "`echo $ac_feature | sed 's/[-a-zA-Z0-9_]//g'`" &&
16360   @var{action}
16361 @end example
16363 @noindent
16364 to take an action when a token matches a given pattern.  Such constructs
16365 should be avoided by using:
16367 @example
16368 case $ac_feature in
16369   *[!-a-zA-Z0-9_]*) @var{action};;
16370 esac
16371 @end example
16373 If the pattern is a complicated regular expression that cannot be
16374 expressed as a shell pattern, use something like this instead:
16376 @example
16377 expr "X$ac_feature" : 'X.*[^-a-zA-Z0-9_]' >/dev/null &&
16378   @var{action}
16379 @end example
16381 @samp{expr "X@var{foo}" : "X@var{bar}"} is more robust than @samp{echo
16382 "X@var{foo}" | grep "^X@var{bar}"}, because it avoids problems when
16383 @samp{@var{foo}} contains backslashes.
16386 @anchor{trap}
16387 @item @command{trap}
16388 @c -----------------
16389 @prindex @command{trap}
16390 It is safe to trap at least the signals 1, 2, 13, and 15.  You can also
16391 trap 0, i.e., have the @command{trap} run when the script ends (either via an
16392 explicit @command{exit}, or the end of the script).  The trap for 0 should be
16393 installed outside of a shell function, or @acronym{AIX} 5.3 @command{/bin/sh}
16394 will invoke the trap at the end of this function.
16396 Posix says that @samp{trap - 1 2 13 15} resets the traps for the
16397 specified signals to their default values, but many common shells (e.g.,
16398 Solaris @command{/bin/sh}) misinterpret this and attempt to execute a
16399 ``command'' named @command{-} when the specified conditions arise.
16400 Posix 2008 also added a requirement to support @samp{trap 1 2 13 15} to
16401 reset traps, as this is supported by a larger set of shells, but there
16402 are still shells like @command{dash} that mistakenly try to execute
16403 @command{1} instead of resetting the traps.  Therefore, there is no
16404 portable workaround, except for @samp{trap - 0}, for which
16405 @samp{trap '' 0} is a portable substitute.
16407 Although Posix is not absolutely clear on this point, it is widely
16408 admitted that when entering the trap @samp{$?} should be set to the exit
16409 status of the last command run before the trap.  The ambiguity can be
16410 summarized as: ``when the trap is launched by an @command{exit}, what is
16411 the @emph{last} command run: that before @command{exit}, or
16412 @command{exit} itself?''
16414 Bash considers @command{exit} to be the last command, while Zsh and
16415 Solaris @command{/bin/sh} consider that when the trap is run it is
16416 @emph{still} in the @command{exit}, hence it is the previous exit status
16417 that the trap receives:
16419 @example
16420 $ @kbd{cat trap.sh}
16421 trap 'echo $?' 0
16422 (exit 42); exit 0
16423 $ @kbd{zsh trap.sh}
16425 $ @kbd{bash trap.sh}
16427 @end example
16429 The portable solution is then simple: when you want to @samp{exit 42},
16430 run @samp{(exit 42); exit 42}, the first @command{exit} being used to
16431 set the exit status to 42 for Zsh, and the second to trigger the trap
16432 and pass 42 as exit status for Bash.  In M4sh, this is covered by using
16433 @code{AS_EXIT}.
16435 The shell in Free@acronym{BSD} 4.0 has the following bug: @samp{$?} is
16436 reset to 0 by empty lines if the code is inside @command{trap}.
16438 @example
16439 $ @kbd{trap 'false}
16441 echo $?' 0
16442 $ @kbd{exit}
16444 @end example
16446 @noindent
16447 Fortunately, this bug only affects @command{trap}.
16449 Several shells fail to execute an exit trap that is defined inside a
16450 subshell, when the last command of that subshell is not a builtin.  A
16451 workaround is to use @samp{exit $?} as the shell builtin.
16453 @example
16454 $ @kbd{bash -c '(trap "echo hi" 0; /bin/true)'}
16456 $ @kbd{/bin/sh -c '(trap "echo hi" 0; /bin/true)'}
16457 $ @kbd{/bin/sh -c '(trap "echo hi" 0; /bin/true; exit $?)'}
16459 @end example
16461 @noindent
16462 Likewise, older implementations of @command{bash} failed to preserve
16463 @samp{$?} across an exit trap consisting of a single cleanup command.
16465 @example
16466 $ @kbd{bash -c 'trap "/bin/true" 0; exit 2'; echo $?}
16468 $ @kbd{bash-2.05b -c 'trap "/bin/true" 0; exit 2'; echo $?}
16470 $ @kbd{bash-2.05b -c 'trap ":; /bin/true" 0; exit 2'; echo $?}
16472 @end example
16474 @item @command{true}
16475 @c -----------------
16476 @prindex @command{true}
16477 @c Info cannot handle `:' in index entries.
16478 @c @prindex @command{:}
16479 Don't worry: as far as we know @command{true} is portable.
16480 Nevertheless, it's not always a builtin (e.g., Bash 1.x), and the
16481 portable shell community tends to prefer using @command{:}.  This has a
16482 funny side effect: when asked whether @command{false} is more portable
16483 than @command{true} Alexandre Oliva answered:
16485 @quotation
16486 In a sense, yes, because if it doesn't exist, the shell will produce an
16487 exit status of failure, which is correct for @command{false}, but not
16488 for @command{true}.
16489 @end quotation
16492 @anchor{unset}
16493 @item @command{unset}
16494 @c ------------------
16495 @prindex @command{unset}
16496 In some nonconforming shells (e.g., Bash 2.05a), @code{unset FOO} fails
16497 when @code{FOO} is not set.  You can use
16499 @smallexample
16500 FOO=; unset FOO
16501 @end smallexample
16503 if you are not sure that @code{FOO} is set.
16505 A few ancient shells lack @command{unset} entirely.  For some variables
16506 such as @code{PS1}, you can use a neutralizing value instead:
16508 @smallexample
16509 PS1='$ '
16510 @end smallexample
16512 Usually, shells that do not support @command{unset} need less effort to
16513 make the environment sane, so for example is not a problem if you cannot
16514 unset @command{CDPATH} on those shells.  However, Bash 2.01 mishandles
16515 @code{unset MAIL} in some cases and dumps core.  So, you should do
16516 something like
16518 @smallexample
16519 ( (unset MAIL) || exit 1) >/dev/null 2>&1 && unset MAIL || :
16520 @end smallexample
16522 @noindent
16523 @xref{Special Shell Variables}, for some neutralizing values.  Also, see
16524 @ref{export, , Limitations of Builtins}, for
16525 the case of environment variables.
16527 @item @command{wait}
16528 @c -----------------
16529 @prindex @command{wait}
16530 The exit status of @command{wait} is not always reliable.
16531 @end table
16533 @node Limitations of Usual Tools
16534 @section Limitations of Usual Tools
16535 @cindex Limitations of usual tools
16537 The small set of tools you can expect to find on any machine can still
16538 include some limitations you should be aware of.
16540 @comment Between this list and the list of builtins above, we should
16541 @comment mention all the tools in GNU Coding Standards ``Utilities in
16542 @comment Makefiles''.
16544 @c This table includes things like `@command{expr} (|)', so we can't
16545 @c use @table @command.
16546 @table @asis
16547 @item @command{awk}
16548 @c ----------------
16549 @prindex @command{awk}
16550 Don't leave white space before the opening parenthesis in a user function call.
16551 Posix does not allow this and @acronym{GNU} Awk rejects it:
16553 @example
16554 $ @kbd{gawk 'function die () @{ print "Aaaaarg!"  @}
16555         BEGIN @{ die () @}'}
16556 gawk: cmd. line:2:         BEGIN @{ die () @}
16557 gawk: cmd. line:2:                      ^ parse error
16558 $ @kbd{gawk 'function die () @{ print "Aaaaarg!"  @}
16559         BEGIN @{ die() @}'}
16560 Aaaaarg!
16561 @end example
16563 Posix says that if a program contains only @samp{BEGIN} actions, and
16564 contains no instances of @code{getline}, then the program merely
16565 executes the actions without reading input.  However, traditional Awk
16566 implementations (such as Solaris 10 @command{awk}) read and discard
16567 input in this case.  Portable scripts can redirect input from
16568 @file{/dev/null} to work around the problem.  For example:
16570 @example
16571 awk 'BEGIN @{print "hello world"@}' </dev/null
16572 @end example
16574 Posix says that in an @samp{END} action, @samp{$NF} (and presumably,
16575 @samp{$1}) retain their value from the last record read, if no
16576 intervening @samp{getline} occurred.  However, some implementations
16577 (such as Solaris 10 @samp{/usr/bin/awk}, @samp{nawk}, or Darwin
16578 @samp{awk}) reset these variables.  A workaround is to use an
16579 intermediate variable prior to the @samp{END} block.  For example:
16581 @example
16582 $ @kbd{cat end.awk}
16583 @{ tmp = $1 @}
16584 END @{ print "a", $1, $NF, "b", tmp @}
16585 $ @kbd{echo 1 | awk -f end.awk}
16586 a   b 1
16587 $ @kbd{echo 1 | gawk -f end.awk}
16588 a 1 1 b 1
16589 @end example
16591 If you want your program to be deterministic, don't depend on @code{for}
16592 on arrays:
16594 @example
16595 $ @kbd{cat for.awk}
16596 END @{
16597   arr["foo"] = 1
16598   arr["bar"] = 1
16599   for (i in arr)
16600     print i
16602 $ @kbd{gawk -f for.awk </dev/null}
16605 $ @kbd{nawk -f for.awk </dev/null}
16608 @end example
16610 Some Awk implementations, such as @acronym{HP-UX} 11.0's native one,
16611 mishandle anchors:
16613 @example
16614 $ @kbd{echo xfoo | $AWK '/foo|^bar/ @{ print @}'}
16615 $ @kbd{echo bar | $AWK '/foo|^bar/ @{ print @}'}
16617 $ @kbd{echo xfoo | $AWK '/^bar|foo/ @{ print @}'}
16618 xfoo
16619 $ @kbd{echo bar | $AWK '/^bar|foo/ @{ print @}'}
16621 @end example
16623 @noindent
16624 Either do not depend on such patterns (i.e., use @samp{/^(.*foo|bar)/},
16625 or use a simple test to reject such implementations.
16627 On @samp{ia64-hp-hpux11.23}, Awk mishandles @code{printf} conversions
16628 after @code{%u}:
16630 @example
16631 $ @kbd{awk 'BEGIN @{ printf "%u %d\n", 0, -1 @}'}
16632 0 0
16633 @end example
16635 @acronym{AIX} version 5.2 has an arbitrary limit of 399 on the
16636 length of regular expressions and literal strings in an Awk program.
16638 Traditional Awk implementations derived from Unix version 7, such as
16639 Solaris @command{/bin/awk}, have many limitations and do not
16640 conform to Posix.  Nowadays @code{AC_PROG_AWK} (@pxref{Particular
16641 Programs}) finds you an Awk that doesn't have these problems, but if
16642 for some reason you prefer not to use @code{AC_PROG_AWK} you may need to
16643 address them.
16645 Traditional Awk does not support multidimensional arrays or user-defined
16646 functions.
16648 Traditional Awk does not support the @option{-v} option.  You can use
16649 assignments after the program instead, e.g., @code{$AWK '@{print v
16650 $1@}' v=x}; however, don't forget that such assignments are not
16651 evaluated until they are encountered (e.g., after any @code{BEGIN}
16652 action).
16654 Traditional Awk does not support the keywords @code{delete} or @code{do}.
16656 Traditional Awk does not support the expressions
16657 @code{@var{a}?@var{b}:@var{c}}, @code{!@var{a}}, @code{@var{a}^@var{b}},
16658 or @code{@var{a}^=@var{b}}.
16660 Traditional Awk does not support the predefined @code{CONVFMT} variable.
16662 Traditional Awk supports only the predefined functions @code{exp}, @code{index},
16663 @code{int}, @code{length}, @code{log}, @code{split}, @code{sprintf},
16664 @code{sqrt}, and @code{substr}.
16666 Traditional Awk @code{getline} is not at all compatible with Posix;
16667 avoid it.
16669 Traditional Awk has @code{for (i in a) @dots{}} but no other uses of the
16670 @code{in} keyword.  For example, it lacks @code{if (i in a) @dots{}}.
16672 In code portable to both traditional and modern Awk, @code{FS} must be a
16673 string containing just one ordinary character, and similarly for the
16674 field-separator argument to @code{split}.
16676 Traditional Awk has a limit of 99 fields in a record.  Since some Awk
16677 implementations, like Tru64's, split the input even if you don't refer
16678 to any field in the script, to circumvent this problem, set @samp{FS}
16679 to an unusual character and use @code{split}.
16681 Traditional Awk has a limit of at most 99 bytes in a number formatted by
16682 @code{OFMT}; for example, @code{OFMT="%.300e"; print 0.1;} typically
16683 dumps core.
16685 The original version of Awk had a limit of at most 99 bytes per
16686 @code{split} field, 99 bytes per @code{substr} substring, and 99 bytes
16687 per run of non-special characters in a @code{printf} format, but these
16688 bugs have been fixed on all practical hosts that we know of.
16690 HP-UX 11.00 and IRIX 6.5 Awk require that input files have a line length
16691 of at most 3070 bytes.
16693 @item @command{basename}
16694 @c ---------------------
16695 @prindex @command{basename}
16696 Not all hosts have a working @command{basename}.
16697 You can use @command{expr} instead.
16699 @c AS_BASENAME is to be replaced by a better API.
16700 @ignore
16701 Not all hosts have a working @command{basename}, and you should instead
16702 use @code{AS_BASENAME} (@pxref{Programming in M4sh}), followed by
16703 @command{expr} if you need to strip a suffix.  For example:
16705 @example
16706 a=`basename "$aname"`       # This is not portable.
16707 a=`AS_BASENAME(["$aname"])` # This is more portable.
16709 # This is not portable.
16710 c=`basename "$cname" .c`
16712 # This is more portable.
16713 c=`AS_BASENAME(["$cname"])`
16714 case $c in
16715 ?*.c) c=`expr "X$c" : 'X\(.*\)\.c'`;;
16716 esac
16717 @end example
16718 @end ignore
16721 @item @command{cat}
16722 @c ----------------
16723 @prindex @command{cat}
16724 Don't rely on any option.
16727 @item @command{cc}
16728 @c ---------------
16729 @prindex @command{cc}
16730 The command @samp{cc -c foo.c} traditionally produces an object file
16731 named @file{foo.o}.  Most compilers allow @option{-c} to be combined
16732 with @option{-o} to specify a different object file name, but
16733 Posix does not require this combination and a few compilers
16734 lack support for it.  @xref{C Compiler}, for how @acronym{GNU} Make
16735 tests for this feature with @code{AC_PROG_CC_C_O}.
16737 When a compilation such as @samp{cc -o foo foo.c} fails, some compilers
16738 (such as @sc{cds} on Reliant Unix) leave a @file{foo.o}.
16740 @acronym{HP-UX} @command{cc} doesn't accept @file{.S} files to preprocess and
16741 assemble.  @samp{cc -c foo.S} appears to succeed, but in fact does
16742 nothing.
16744 The default executable, produced by @samp{cc foo.c}, can be
16746 @itemize
16747 @item @file{a.out} --- usual Posix convention.
16748 @item @file{b.out} --- i960 compilers (including @command{gcc}).
16749 @item @file{a.exe} --- @acronym{DJGPP} port of @command{gcc}.
16750 @item @file{a_out.exe} --- GNV @command{cc} wrapper for DEC C on OpenVMS.
16751 @item @file{foo.exe} --- various MS-DOS compilers.
16752 @end itemize
16754 The C compiler's traditional name is @command{cc}, but other names like
16755 @command{gcc} are common.  Posix 1003.1-2001 specifies the
16756 name @command{c99}, but older Posix editions specified
16757 @command{c89} and anyway these standard names are rarely used in
16758 practice.  Typically the C compiler is invoked from makefiles that use
16759 @samp{$(CC)}, so the value of the @samp{CC} make variable selects the
16760 compiler name.
16762 @item @command{chgrp}
16763 @itemx @command{chown}
16764 @c -------------------
16765 @prindex @command{chgrp}
16766 @prindex @command{chown}
16767 It is not portable to change a file's group to a group that the owner
16768 does not belong to.
16770 @item @command{chmod}
16771 @c ------------------
16772 @prindex @command{chmod}
16773 Avoid usages like @samp{chmod -w file}; use @samp{chmod a-w file}
16774 instead, for two reasons.  First, plain @option{-w} does not necessarily
16775 make the file unwritable, since it does not affect mode bits that
16776 correspond to bits in the file mode creation mask.  Second,
16777 Posix says that the @option{-w} might be interpreted as an
16778 implementation-specific option, not as a mode; Posix suggests
16779 using @samp{chmod -- -w file} to avoid this confusion, but unfortunately
16780 @samp{--} does not work on some older hosts.
16783 @item @command{cmp}
16784 @c ----------------
16785 @prindex @command{cmp}
16786 @command{cmp} performs a raw data comparison of two files, while
16787 @command{diff} compares two text files.  Therefore, if you might compare
16788 DOS files, even if only checking whether two files are different, use
16789 @command{diff} to avoid spurious differences due to differences of
16790 newline encoding.
16793 @item @command{cp}
16794 @c ---------------
16795 @prindex @command{cp}
16796 Avoid the @option{-r} option, since Posix 1003.1-2004 marks it as
16797 obsolescent and its behavior on special files is implementation-defined.
16798 Use @option{-R} instead.  On @acronym{GNU} hosts the two options
16799 are equivalent, but on Solaris hosts (for example) @code{cp -r}
16800 reads from pipes instead of replicating them.
16802 Some @command{cp} implementations (e.g., @acronym{BSD/OS} 4.2) do not allow
16803 trailing slashes at the end of nonexistent destination directories.  To
16804 avoid this problem, omit the trailing slashes.  For example, use
16805 @samp{cp -R source /tmp/newdir} rather than @samp{cp -R source
16806 /tmp/newdir/} if @file{/tmp/newdir} does not exist.
16808 @c This is thanks to Ian.
16809 The ancient SunOS 4 @command{cp} does not support @option{-f}, although
16810 its @command{mv} does.
16812 @cindex timestamp resolution
16813 Traditionally, file timestamps had 1-second resolution, and @samp{cp
16814 -p} copied the timestamps exactly.  However, many modern file systems
16815 have timestamps with 1-nanosecond resolution.  Unfortunately, @samp{cp
16816 -p} implementations truncate timestamps when copying files, so this
16817 can result in the destination file appearing to be older than the
16818 source.  The exact amount of truncation depends on the resolution of
16819 the system calls that @command{cp} uses; traditionally this was
16820 @code{utime}, which has 1-second resolution, but some newer
16821 @command{cp} implementations use @code{utimes}, which has
16822 1-microsecond resolution.  These newer implementations include @acronym{GNU}
16823 Core Utilities 5.0.91 or later, and Solaris 8 (sparc) patch 109933-02 or
16824 later.  Unfortunately as of January 2006 there is still no system
16825 call to set timestamps to the full nanosecond resolution.
16827 Bob Proulx notes that @samp{cp -p} always @emph{tries} to copy
16828 ownerships.  But whether it actually does copy ownerships or not is a
16829 system dependent policy decision implemented by the kernel.  If the
16830 kernel allows it then it happens.  If the kernel does not allow it then
16831 it does not happen.  It is not something @command{cp} itself has control
16832 over.
16834 In Unix System V any user can chown files to any other user, and System
16835 V also has a non-sticky @file{/tmp}.  That probably derives from the
16836 heritage of System V in a business environment without hostile users.
16837 @acronym{BSD} changed this
16838 to be a more secure model where only root can @command{chown} files and
16839 a sticky @file{/tmp} is used.  That undoubtedly derives from the heritage
16840 of @acronym{BSD} in a campus environment.
16842 @acronym{GNU}/Linux and Solaris by default follow @acronym{BSD}, but
16843 can be configured to allow a System V style @command{chown}.  On the
16844 other hand, @acronym{HP-UX} follows System V, but can
16845 be configured to use the modern security model and disallow
16846 @command{chown}.  Since it is an administrator-configurable parameter
16847 you can't use the name of the kernel as an indicator of the behavior.
16851 @item @command{date}
16852 @c -----------------
16853 @prindex @command{date}
16854 Some versions of @command{date} do not recognize special @samp{%} directives,
16855 and unfortunately, instead of complaining, they just pass them through,
16856 and exit with success:
16858 @example
16859 $ @kbd{uname -a}
16860 OSF1 medusa.sis.pasteur.fr V5.1 732 alpha
16861 $ @kbd{date "+%s"}
16863 @end example
16866 @item @command{diff}
16867 @c -----------------
16868 @prindex @command{diff}
16869 Option @option{-u} is nonportable.
16871 Some implementations, such as Tru64's, fail when comparing to
16872 @file{/dev/null}.  Use an empty file instead.
16875 @item @command{dirname}
16876 @c --------------------
16877 @prindex @command{dirname}
16878 Not all hosts have a working @command{dirname}, and you should instead
16879 use @code{AS_DIRNAME} (@pxref{Programming in M4sh}).  For example:
16881 @example
16882 dir=`dirname "$file"`       # This is not portable.
16883 dir=`AS_DIRNAME(["$file"])` # This is more portable.
16884 @end example
16887 @item @command{egrep}
16888 @c ------------------
16889 @prindex @command{egrep}
16890 Posix 1003.1-2001 no longer requires @command{egrep},
16891 but many hosts do not yet support the Posix
16892 replacement @code{grep -E}.  Also, some traditional implementations do
16893 not work on long input lines.  To work around these problems, invoke
16894 @code{AC_PROG_EGREP} and then use @code{$EGREP}.
16896 Portable extended regular expressions should use @samp{\} only to escape
16897 characters in the string @samp{$()*+.?[\^@{|}.  For example, @samp{\@}}
16898 is not portable, even though it typically matches @samp{@}}.
16900 The empty alternative is not portable.  Use @samp{?} instead.  For
16901 instance with Digital Unix v5.0:
16903 @example
16904 > printf "foo\n|foo\n" | $EGREP '^(|foo|bar)$'
16905 |foo
16906 > printf "bar\nbar|\n" | $EGREP '^(foo|bar|)$'
16907 bar|
16908 > printf "foo\nfoo|\n|bar\nbar\n" | $EGREP '^(foo||bar)$'
16910 |bar
16911 @end example
16913 @command{$EGREP} also suffers the limitations of @command{grep}
16914 (@pxref{grep, , Limitations of Usual Tools}).
16916 @item @command{expr}
16917 @c -----------------
16918 @prindex @command{expr}
16919 Not all implementations obey the Posix rule that @samp{--} separates
16920 options from arguments; likewise, not all implementations provide the
16921 extension to Posix that the first argument can be treated as part of a
16922 valid expression rather than an invalid option if it begins with
16923 @samp{-}.  When performing arithmetic, use @samp{expr 0 + $var} if
16924 @samp{$var} might be a negative number, to keep @command{expr} from
16925 interpreting it as an option.
16927 No @command{expr} keyword starts with @samp{X}, so use @samp{expr
16928 X"@var{word}" : 'X@var{regex}'} to keep @command{expr} from
16929 misinterpreting @var{word}.
16931 Don't use @code{length}, @code{substr}, @code{match} and @code{index}.
16933 @item @command{expr} (@samp{|})
16934 @prindex @command{expr} (@samp{|})
16935 You can use @samp{|}.  Although Posix does require that @samp{expr
16936 ''} return the empty string, it does not specify the result when you
16937 @samp{|} together the empty string (or zero) with the empty string.  For
16938 example:
16940 @example
16941 expr '' \| ''
16942 @end example
16944 Posix 1003.2-1992 returns the empty string
16945 for this case, but traditional Unix returns @samp{0} (Solaris is
16946 one such example).  In Posix 1003.1-2001, the specification was
16947 changed to match traditional Unix's behavior (which is
16948 bizarre, but it's too late to fix this).  Please note that the same
16949 problem does arise when the empty string results from a computation,
16950 as in:
16952 @example
16953 expr bar : foo \| foo : bar
16954 @end example
16956 @noindent
16957 Avoid this portability problem by avoiding the empty string.
16960 @item @command{expr} (@samp{:})
16961 @c ----------------------------
16962 @prindex @command{expr}
16963 Portable @command{expr} regular expressions should use @samp{\} to
16964 escape only characters in the string @samp{$()*.0123456789[\^n@{@}}.
16965 For example, alternation, @samp{\|}, is common but Posix does not
16966 require its support, so it should be avoided in portable scripts.
16967 Similarly, @samp{\+} and @samp{\?} should be avoided.
16969 Portable @command{expr} regular expressions should not begin with
16970 @samp{^}.  Patterns are automatically anchored so leading @samp{^} is
16971 not needed anyway.
16973 On the other hand, the behavior of the @samp{$} anchor is not portable
16974 on multi-line strings.  Posix is ambiguous whether the anchor applies to
16975 each line, as was done in older versions of @acronym{GNU} Coreutils, or
16976 whether it applies only to the end of the overall string, as in
16977 Coreutils 6.0 and most other implementations.
16979 @example
16980 $ @kbd{baz='foo}
16981 > @kbd{bar'}
16982 $ @kbd{expr "X$baz" : 'X\(foo\)$'}
16984 $ @kbd{expr-5.97 "X$baz" : 'X\(foo\)$'}
16986 @end example
16988 The Posix standard is ambiguous as to whether
16989 @samp{expr 'a' : '\(b\)'} outputs @samp{0} or the empty string.
16990 In practice, it outputs the empty string on most platforms, but portable
16991 scripts should not assume this.  For instance, the @acronym{QNX} 4.25 native
16992 @command{expr} returns @samp{0}.
16994 One might think that a way to get a uniform behavior would be to use
16995 the empty string as a default value:
16997 @example
16998 expr a : '\(b\)' \| ''
16999 @end example
17001 @noindent
17002 Unfortunately this behaves exactly as the original expression; see the
17003 @command{expr} (@samp{|}) entry for more information.
17005 Some ancient @command{expr} implementations (e.g., SunOS 4 @command{expr} and
17006 Solaris 8 @command{/usr/ucb/expr}) have a silly length limit that causes
17007 @command{expr} to fail if the matched substring is longer than 120
17008 bytes.  In this case, you might want to fall back on @samp{echo|sed} if
17009 @command{expr} fails.  Nowadays this is of practical importance only for
17010 the rare installer who mistakenly puts @file{/usr/ucb} before
17011 @file{/usr/bin} in @env{PATH}.
17013 On Mac OS X 10.4, @command{expr} mishandles the pattern @samp{[^-]} in
17014 some cases.  For example, the command
17015 @example
17016 expr Xpowerpc-apple-darwin8.1.0 : 'X[^-]*-[^-]*-\(.*\)'
17017 @end example
17019 @noindent
17020 outputs @samp{apple-darwin8.1.0} rather than the correct @samp{darwin8.1.0}.
17021 This particular case can be worked around by substituting @samp{[^--]}
17022 for @samp{[^-]}.
17024 Don't leave, there is some more!
17026 The @acronym{QNX} 4.25 @command{expr}, in addition of preferring @samp{0} to
17027 the empty string, has a funny behavior in its exit status: it's always 1
17028 when parentheses are used!
17030 @example
17031 $ @kbd{val=`expr 'a' : 'a'`; echo "$?: $val"}
17032 0: 1
17033 $ @kbd{val=`expr 'a' : 'b'`; echo "$?: $val"}
17034 1: 0
17036 $ @kbd{val=`expr 'a' : '\(a\)'`; echo "?: $val"}
17037 1: a
17038 $ @kbd{val=`expr 'a' : '\(b\)'`; echo "?: $val"}
17039 1: 0
17040 @end example
17042 @noindent
17043 In practice this can be a big problem if you are ready to catch failures
17044 of @command{expr} programs with some other method (such as using
17045 @command{sed}), since you may get twice the result.  For instance
17047 @example
17048 $ @kbd{expr 'a' : '\(a\)' || echo 'a' | sed 's/^\(a\)$/\1/'}
17049 @end example
17051 @noindent
17052 outputs @samp{a} on most hosts, but @samp{aa} on @acronym{QNX} 4.25.  A
17053 simple workaround consists of testing @command{expr} and using a variable
17054 set to @command{expr} or to @command{false} according to the result.
17056 Tru64 @command{expr} incorrectly treats the result as a number, if it
17057 can be interpreted that way:
17059 @example
17060 $ @kbd{expr 00001 : '.*\(...\)'}
17062 @end example
17064 On @acronym{HP-UX} 11, @command{expr} only supports a single
17065 sub-expression.
17067 @example
17068 $ @kbd{expr 'Xfoo' : 'X\(f\(oo\)*\)$'}
17069 expr: More than one '\(' was used.
17070 @end example
17073 @item @command{fgrep}
17074 @c ------------------
17075 @prindex @command{fgrep}
17076 Posix 1003.1-2001 no longer requires @command{fgrep},
17077 but many hosts do not yet support the Posix
17078 replacement @code{grep -F}.  Also, some traditional implementations do
17079 not work on long input lines.  To work around these problems, invoke
17080 @code{AC_PROG_FGREP} and then use @code{$FGREP}.
17083 @item @command{find}
17084 @c -----------------
17085 @prindex @command{find}
17086 The option @option{-maxdepth} seems to be @acronym{GNU} specific.
17087 Tru64 v5.1, Net@acronym{BSD} 1.5 and Solaris @command{find}
17088 commands do not understand it.
17090 The replacement of @samp{@{@}} is guaranteed only if the argument is
17091 exactly @emph{@{@}}, not if it's only a part of an argument.  For
17092 instance on DU, and @acronym{HP-UX} 10.20 and @acronym{HP-UX} 11:
17094 @example
17095 $ @kbd{touch foo}
17096 $ @kbd{find . -name foo -exec echo "@{@}-@{@}" \;}
17097 @{@}-@{@}
17098 @end example
17100 @noindent
17101 while @acronym{GNU} @command{find} reports @samp{./foo-./foo}.
17104 @anchor{grep}
17105 @item @command{grep}
17106 @c -----------------
17107 @prindex @command{grep}
17108 Portable scripts can rely on the @command{grep} options @option{-c},
17109 @option{-l}, @option{-n}, and @option{-v}, but should avoid other
17110 options.  For example, don't use @option{-w}, as Posix does not require
17111 it and Irix 6.5.16m's @command{grep} does not support it.  Also,
17112 portable scripts should not combine @option{-c} with @option{-l},
17113 as Posix does not allow this.
17115 Some of the options required by Posix are not portable in practice.
17116 Don't use @samp{grep -q} to suppress output, because many @command{grep}
17117 implementations (e.g., Solaris) do not support @option{-q}.
17118 Don't use @samp{grep -s} to suppress output either, because Posix
17119 says @option{-s} does not suppress output, only some error messages;
17120 also, the @option{-s} option of traditional @command{grep} behaved
17121 like @option{-q} does in most modern implementations.  Instead,
17122 redirect the standard output and standard error (in case the file
17123 doesn't exist) of @code{grep} to @file{/dev/null}.  Check the exit
17124 status of @code{grep} to determine whether it found a match.
17126 Some traditional @command{grep} implementations do not work on long
17127 input lines.  On AIX the default @code{grep} silently truncates long
17128 lines on the input before matching.
17130 Also, many implementations do not support multiple regexps
17131 with @option{-e}: they either reject @option{-e} entirely (e.g., Solaris)
17132 or honor only the last pattern (e.g., @acronym{IRIX} 6.5 and NeXT).  To
17133 work around these problems, invoke @code{AC_PROG_GREP} and then use
17134 @code{$GREP}.
17136 Another possible workaround for the multiple @option{-e} problem is to
17137 separate the patterns by newlines, for example:
17139 @example
17140 grep 'foo
17141 bar' in.txt
17142 @end example
17144 @noindent
17145 except that this fails with traditional @command{grep}
17146 implementations and with Open@acronym{BSD} 3.8 @command{grep}.
17148 Traditional @command{grep} implementations (e.g., Solaris) do not
17149 support the @option{-E} or @option{-F} options.  To work around these
17150 problems, invoke @code{AC_PROG_EGREP} and then use @code{$EGREP}, and
17151 similarly for @code{AC_PROG_FGREP} and @code{$FGREP}.  Even if you are
17152 willing to require support for Posix @command{grep}, your script should
17153 not use both @option{-E} and @option{-F}, since Posix does not allow
17154 this combination.
17156 Portable @command{grep} regular expressions should use @samp{\} only to
17157 escape characters in the string @samp{$()*.0123456789[\^@{@}}.  For example,
17158 alternation, @samp{\|}, is common but Posix does not require its
17159 support in basic regular expressions, so it should be avoided in
17160 portable scripts.  Solaris and HP-UX @command{grep} do not support it.
17161 Similarly, the following escape sequences should also be avoided:
17162 @samp{\<}, @samp{\>}, @samp{\+}, @samp{\?}, @samp{\`}, @samp{\'},
17163 @samp{\B}, @samp{\b}, @samp{\S}, @samp{\s}, @samp{\W}, and @samp{\w}.
17165 Posix does not specify the behavior of @command{grep} on binary files.
17166 An example where this matters is using @acronym{BSD} @command{grep} to
17167 search text that includes embedded @acronym{ANSI} escape sequences for
17168 colored output to terminals (@samp{\033[m} is the sequence to restore
17169 normal output); the behavior depends on whether input is seekable:
17171 @example
17172 $ @kbd{printf 'esc\033[mape\n' > sample}
17173 $ @kbd{grep . sample}
17174 Binary file sample matches
17175 $ @kbd{cat sample | grep .}
17176 escape
17177 @end example
17180 @item @command{join}
17181 @c -----------------
17182 @prindex @command{join}
17183 Solaris 8 @command{join} has bugs when the second operand is standard
17184 input, and when standard input is a pipe.  For example, the following
17185 shell script causes Solaris 8 @command{join} to loop forever:
17187 @example
17188 cat >file <<'EOF'
17189 1 x
17190 2 y
17192 cat file | join file -
17193 @end example
17195 Use @samp{join - file} instead.
17198 @item @command{ln}
17199 @c ---------------
17200 @prindex @command{ln}
17201 @cindex Symbolic links
17202 Don't rely on @command{ln} having a @option{-f} option.  Symbolic links
17203 are not available on old systems; use @samp{$(LN_S)} as a portable substitute.
17205 For versions of the @acronym{DJGPP} before 2.04,
17206 @command{ln} emulates symbolic links
17207 to executables by generating a stub that in turn calls the real
17208 program.  This feature also works with nonexistent files like in the
17209 Posix spec.  So @samp{ln -s file link} generates @file{link.exe},
17210 which attempts to call @file{file.exe} if run.  But this feature only
17211 works for executables, so @samp{cp -p} is used instead for these
17212 systems.  @acronym{DJGPP} versions 2.04 and later have full support
17213 for symbolic links.
17216 @item @command{ls}
17217 @c ---------------
17218 @prindex @command{ls}
17219 @cindex Listing directories
17220 The portable options are @option{-acdilrtu}.  Current practice is for
17221 @option{-l} to output both owner and group, even though ancient versions
17222 of @command{ls} omitted the group.
17224 On ancient hosts, @samp{ls foo} sent the diagnostic @samp{foo not found}
17225 to standard output if @file{foo} did not exist.  Hence a shell command
17226 like @samp{sources=`ls *.c 2>/dev/null`} did not always work, since it
17227 was equivalent to @samp{sources='*.c not found'} in the absence of
17228 @samp{.c} files.  This is no longer a practical problem, since current
17229 @command{ls} implementations send diagnostics to standard error.
17231 The behavior of @command{ls} on a directory that is being concurrently
17232 modified is not always predictable, because of a data race where cached
17233 information returned by @code{readdir} does not match the current
17234 directory state.  In fact, MacOS 10.5 has an intermittent bug where
17235 @code{readdir}, and thus @command{ls}, sometimes lists a file more than
17236 once if other files were added or removed from the directory immediately
17237 prior to the @command{ls} call.  Since @command{ls} already sorts its
17238 output, the duplicate entries can be avoided by piping the results
17239 through @code{uniq}.
17241 @anchor{mkdir}
17242 @item @command{mkdir}
17243 @c ------------------
17244 @prindex @command{mkdir}
17245 @cindex Making directories
17246 No @command{mkdir} option is portable to older systems.  Instead of
17247 @samp{mkdir -p @var{file-name}}, you should use
17248 @code{AS_MKDIR_P(@var{file-name})} (@pxref{Programming in M4sh})
17249 or @code{AC_PROG_MKDIR_P} (@pxref{Particular Programs}).
17251 Combining the @option{-m} and @option{-p} options, as in @samp{mkdir -m
17252 go-w -p @var{dir}}, often leads to trouble.  Free@acronym{BSD}
17253 @command{mkdir} incorrectly attempts to change the permissions of
17254 @var{dir} even if it already exists.  @acronym{HP-UX} 11.23 and
17255 @acronym{IRIX} 6.5 @command{mkdir} often assign the wrong permissions to
17256 any newly-created parents of @var{dir}.
17258 Posix does not clearly specify whether @samp{mkdir -p foo}
17259 should succeed when @file{foo} is a symbolic link to an already-existing
17260 directory.  The @acronym{GNU} Core Utilities 5.1.0 @command{mkdir}
17261 succeeds, but Solaris @command{mkdir} fails.
17263 Traditional @code{mkdir -p} implementations suffer from race conditions.
17264 For example, if you invoke @code{mkdir -p a/b} and @code{mkdir -p a/c}
17265 at the same time, both processes might detect that @file{a} is missing,
17266 one might create @file{a}, then the other might try to create @file{a}
17267 and fail with a @code{File exists} diagnostic.  The @acronym{GNU} Core
17268 Utilities (@samp{fileutils} version 4.1), Free@acronym{BSD} 5.0,
17269 Net@acronym{BSD} 2.0.2, and Open@acronym{BSD} 2.4 are known to be
17270 race-free when two processes invoke @code{mkdir -p} simultaneously, but
17271 earlier versions are vulnerable.  Solaris @command{mkdir} is still
17272 vulnerable as of Solaris 10, and other traditional Unix systems are
17273 probably vulnerable too.  This possible race is harmful in parallel
17274 builds when several Make rules call @code{mkdir -p} to
17275 construct directories.  You may use
17276 @code{install-sh -d} as a safe replacement, provided this script is
17277 recent enough; the copy shipped with Autoconf 2.60 and Automake 1.10 is
17278 OK, but copies from older versions are vulnerable.
17281 @item @command{mkfifo}
17282 @itemx @command{mknod}
17283 @c -------------------
17284 @prindex @command{mkfifo}
17285 @prindex @command{mknod}
17286 The GNU Coding Standards state that @command{mknod} is safe to use on
17287 platforms where it has been tested to exist; but it is generally portable
17288 only for creating named FIFOs, since device numbers are
17289 platform-specific.  Autotest uses @command{mkfifo} to implement parallel
17290 testsuites.  Posix states that behavior is unspecified when opening a
17291 named FIFO for both reading and writing; on at least Cygwin, this
17292 results in failure on any attempt to read or write to that file
17293 descriptor.
17295 @item @command{mktemp}
17296 @c -------------------
17297 @prindex @command{mktemp}
17298 @cindex Creating temporary files
17299 Shell scripts can use temporary files safely with @command{mktemp}, but
17300 it does not exist on all systems.  A portable way to create a safe
17301 temporary file name is to create a temporary directory with mode 700 and
17302 use a file inside this directory.  Both methods prevent attackers from
17303 gaining control, though @command{mktemp} is far less likely to fail
17304 gratuitously under attack.
17306 Here is sample code to create a new temporary directory safely:
17308 @example
17309 # Create a temporary directory $tmp in $TMPDIR (default /tmp).
17310 # Use mktemp if possible; otherwise fall back on mkdir,
17311 # with $RANDOM to make collisions less likely.
17312 : $@{TMPDIR=/tmp@}
17314   tmp=`
17315     (umask 077 && mktemp -d "$TMPDIR/fooXXXXXX") 2>/dev/null
17316   ` &&
17317   test -n "$tmp" && test -d "$tmp"
17318 @} || @{
17319   tmp=$TMPDIR/foo$$-$RANDOM
17320   (umask 077 && mkdir "$tmp")
17321 @} || exit $?
17322 @end example
17325 @item @command{mv}
17326 @c ---------------
17327 @prindex @command{mv}
17328 @cindex Moving open files
17329 The only portable options are @option{-f} and @option{-i}.
17331 Moving individual files between file systems is portable (it was in Unix
17332 version 6),
17333 but it is not always atomic: when doing @samp{mv new existing}, there's
17334 a critical section where neither the old nor the new version of
17335 @file{existing} actually exists.
17337 On some systems moving files from @file{/tmp} can sometimes cause
17338 undesirable (but perfectly valid) warnings, even if you created these
17339 files.  This is because @file{/tmp} belongs to a group that ordinary
17340 users are not members of, and files created in @file{/tmp} inherit
17341 the group of @file{/tmp}.  When the file is copied, @command{mv} issues
17342 a diagnostic without failing:
17344 @smallexample
17345 $ @kbd{touch /tmp/foo}
17346 $ @kbd{mv /tmp/foo .}
17347 @error{}mv: ./foo: set owner/group (was: 100/0): Operation not permitted
17348 $ @kbd{echo $?}
17350 $ @kbd{ls foo}
17352 @end smallexample
17354 @noindent
17355 This annoying behavior conforms to Posix, unfortunately.
17357 Moving directories across mount points is not portable, use @command{cp}
17358 and @command{rm}.
17360 @acronym{DOS} variants cannot rename or remove open files, and do not
17361 support commands like @samp{mv foo bar >foo}, even though this is
17362 perfectly portable among Posix hosts.
17365 @item @command{od}
17366 @c ---------------
17367 @prindex @command{od}
17369 In Mac OS X 10.3, @command{od} does not support the
17370 standard Posix options @option{-A}, @option{-j}, @option{-N}, or
17371 @option{-t}, or the @acronym{XSI} option @option{-s}.  The only
17372 supported Posix option is @option{-v}, and the only supported
17373 @acronym{XSI} options are those in @option{-bcdox}.  The @acronym{BSD}
17374 @command{hexdump} program can be used instead.
17376 This problem no longer exists in Mac OS X 10.4.3.
17379 @item @command{rm}
17380 @c ---------------
17381 @prindex @command{rm}
17382 The @option{-f} and @option{-r} options are portable.
17384 It is not portable to invoke @command{rm} without operands.  For
17385 example, on many systems @samp{rm -f -r} (with no other arguments)
17386 silently succeeds without doing anything, but it fails with a diagnostic
17387 on Net@acronym{BSD} 2.0.2.
17389 A file might not be removed even if its parent directory is writable
17390 and searchable.  Many Posix hosts cannot remove a mount point, a named
17391 stream, a working directory, or a last link to a file that is being
17392 executed.
17394 @acronym{DOS} variants cannot rename or remove open files, and do not
17395 support commands like @samp{rm foo >foo}, even though this is
17396 perfectly portable among Posix hosts.
17398 @item @command{rmdir}
17399 @c ------------------
17400 @prindex @command{rmdir}
17401 Just as with @command{rm}, some platforms refuse to remove a working
17402 directory.
17404 @anchor{sed}
17405 @item @command{sed}
17406 @c ----------------
17407 @prindex @command{sed}
17408 Patterns should not include the separator (unless escaped), even as part
17409 of a character class.  In conformance with Posix, the Cray
17410 @command{sed} rejects @samp{s/[^/]*$//}: use @samp{s,[^/]*$,,}.
17412 Avoid empty patterns within parentheses (i.e., @samp{\(\)}).  Posix does
17413 not require support for empty patterns, and Unicos 9 @command{sed} rejects
17414 them.
17416 Unicos 9 @command{sed} loops endlessly on patterns like @samp{.*\n.*}.
17418 Sed scripts should not use branch labels longer than 7 characters and
17419 should not contain comments.  @acronym{HP-UX} sed has a limit of 99 commands
17420 (not counting @samp{:} commands) and
17421 48 labels, which can not be circumvented by using more than one script
17422 file.  It can execute up to 19 reads with the @samp{r} command per cycle.
17423 Solaris @command{/usr/ucb/sed} rejects usages that exceed a limit of
17424 about 6000 bytes for the internal representation of commands.
17426 Avoid redundant @samp{;}, as some @command{sed} implementations, such as
17427 Net@acronym{BSD} 1.4.2's, incorrectly try to interpret the second
17428 @samp{;} as a command:
17430 @example
17431 $ @kbd{echo a | sed 's/x/x/;;s/x/x/'}
17432 sed: 1: "s/x/x/;;s/x/x/": invalid command code ;
17433 @end example
17435 Input should not have unreasonably long lines, since some @command{sed}
17436 implementations have an input buffer limited to 4000 bytes.  Likewise,
17437 not all @command{sed} implementations can handle embedded @code{NUL} or
17438 a missing trailing newline.
17440 Portable @command{sed} regular expressions should use @samp{\} only to escape
17441 characters in the string @samp{$()*.0123456789[\^n@{@}}.  For example,
17442 alternation, @samp{\|}, is common but Posix does not require its
17443 support, so it should be avoided in portable scripts.  Solaris
17444 @command{sed} does not support alternation; e.g., @samp{sed '/a\|b/d'}
17445 deletes only lines that contain the literal string @samp{a|b}.
17446 Similarly, @samp{\+} and @samp{\?} should be avoided.
17448 Anchors (@samp{^} and @samp{$}) inside groups are not portable.
17450 Nested parentheses in patterns (e.g., @samp{\(\(a*\)b*)\)}) are
17451 quite portable to current hosts, but was not supported by some ancient
17452 @command{sed} implementations like SVR3.
17454 Some @command{sed} implementations, e.g., Solaris,
17455 restrict the special role of the asterisk to one-character regular expressions.
17456 This may lead to unexpected behavior:
17458 @example
17459 $ @kbd{echo '1*23*4' | /usr/bin/sed 's/\(.\)*/x/g'}
17460 x2x4
17461 $ @kbd{echo '1*23*4' | /usr/xpg4/bin/sed 's/\(.\)*/x/g'}
17463 @end example
17465 The @option{-e} option is mostly portable.
17466 However, its argument
17467 cannot start with @samp{a}, @samp{c}, or @samp{i},
17468 as this runs afoul of a Tru64 5.1 bug.
17469 Also, its argument cannot be empty, as this fails on @acronym{AIX} 5.3.
17470 Some people prefer to use @samp{-e}:
17472 @example
17473 sed -e '@var{command-1}' \
17474     -e '@var{command-2}'
17475 @end example
17477 @noindent
17478 as opposed to the equivalent:
17480 @example
17481 sed '
17482   @var{command-1}
17483   @var{command-2}
17485 @end example
17487 @noindent
17488 The following usage is sometimes equivalent:
17490 @example
17491 sed '@var{command-1};@var{command-2}'
17492 @end example
17494 but Posix says that this use of a semicolon has undefined effect if
17495 @var{command-1}'s verb is @samp{@{}, @samp{a}, @samp{b}, @samp{c},
17496 @samp{i}, @samp{r}, @samp{t}, @samp{w}, @samp{:}, or @samp{#}, so you
17497 should use semicolon only with simple scripts that do not use these
17498 verbs.
17500 Commands inside @{ @} brackets are further restricted.  Posix says that
17501 they cannot be preceded by addresses, @samp{!}, or @samp{;}, and that
17502 each command must be followed immediately by a newline, without any
17503 intervening blanks or semicolons.  The closing bracket must be alone on
17504 a line, other than white space preceding or following it.
17506 Contrary to yet another urban legend, you may portably use @samp{&} in
17507 the replacement part of the @code{s} command to mean ``what was
17508 matched''.  All descendants of Unix version 7 @command{sed}
17509 (at least; we
17510 don't have first hand experience with older @command{sed} implementations) have
17511 supported it.
17513 Posix requires that you must not have any white space between
17514 @samp{!} and the following command.  It is OK to have blanks between
17515 the address and the @samp{!}.  For instance, on Solaris:
17517 @example
17518 $ @kbd{echo "foo" | sed -n '/bar/ ! p'}
17519 @error{}Unrecognized command: /bar/ ! p
17520 $ @kbd{echo "foo" | sed -n '/bar/! p'}
17521 @error{}Unrecognized command: /bar/! p
17522 $ @kbd{echo "foo" | sed -n '/bar/ !p'}
17524 @end example
17526 Posix also says that you should not combine @samp{!} and @samp{;}.  If
17527 you use @samp{!}, it is best to put it on a command that is delimited by
17528 newlines rather than @samp{;}.
17530 Also note that Posix requires that the @samp{b}, @samp{t}, @samp{r}, and
17531 @samp{w} commands be followed by exactly one space before their argument.
17532 On the other hand, no white space is allowed between @samp{:} and the
17533 subsequent label name.
17535 If a sed script is specified on the command line and ends in an
17536 @samp{a}, @samp{c}, or @samp{i} command, the last line of inserted text
17537 should be followed by a newline.  Otherwise some @command{sed}
17538 implementations (e.g., Open@acronym{BSD} 3.9) do not append a newline to the
17539 inserted text.
17541 Many @command{sed} implementations (e.g., MacOS X 10.4,
17542 Open@acronym{BSD} 3.9, Solaris 10
17543 @command{/usr/ucb/sed}) strip leading white space from the text of
17544 @samp{a}, @samp{c}, and @samp{i} commands.  Prepend a backslash to
17545 work around this incompatibility with Posix:
17547 @example
17548 $ @kbd{echo flushleft | sed 'a\}
17549 > @kbd{   indented}
17550 > @kbd{'}
17551 flushleft
17552 indented
17553 $ @kbd{echo foo | sed 'a\}
17554 > @kbd{\   indented}
17555 > @kbd{'}
17556 flushleft
17557    indented
17558 @end example
17560 Posix requires that with an empty regular expression, the last non-empty
17561 regular expression from either an address specification or substitution
17562 command is applied.  However, busybox 1.6.1 complains when using a
17563 substitution command with a replacement containing a back-reference to
17564 an empty regular expression; the workaround is repeating the regular
17565 expression.
17567 @example
17568 $ @kbd{echo abc | busybox sed '/a\(b\)c/ s//\1/'}
17569 sed: No previous regexp.
17570 $ @kbd{echo abc | busybox sed '/a\(b\)c/ s/a\(b\)c/\1/'}
17572 @end example
17575 @item @command{sed} (@samp{t})
17576 @c ---------------------------
17577 @prindex @command{sed} (@samp{t})
17578 Some old systems have @command{sed} that ``forget'' to reset their
17579 @samp{t} flag when starting a new cycle.  For instance on @acronym{MIPS
17580 RISC/OS}, and on @sc{irix} 5.3, if you run the following @command{sed}
17581 script (the line numbers are not actual part of the texts):
17583 @example
17584 s/keep me/kept/g  # a
17585 t end             # b
17586 s/.*/deleted/g    # c
17587 :end              # d
17588 @end example
17590 @noindent
17593 @example
17594 delete me         # 1
17595 delete me         # 2
17596 keep me           # 3
17597 delete me         # 4
17598 @end example
17600 @noindent
17601 you get
17603 @example
17604 deleted
17605 delete me
17606 kept
17607 deleted
17608 @end example
17610 @noindent
17611 instead of
17613 @example
17614 deleted
17615 deleted
17616 kept
17617 deleted
17618 @end example
17620 Why?  When processing line 1, (c) matches, therefore sets the @samp{t}
17621 flag, and the output is produced.  When processing
17622 line 2, the @samp{t} flag is still set (this is the bug).  Command (a)
17623 fails to match, but @command{sed} is not supposed to clear the @samp{t}
17624 flag when a substitution fails.  Command (b) sees that the flag is set,
17625 therefore it clears it, and jumps to (d), hence you get @samp{delete me}
17626 instead of @samp{deleted}.  When processing line (3), @samp{t} is clear,
17627 (a) matches, so the flag is set, hence (b) clears the flags and jumps.
17628 Finally, since the flag is clear, line 4 is processed properly.
17630 There are two things one should remember about @samp{t} in @command{sed}.
17631 Firstly, always remember that @samp{t} jumps if @emph{some} substitution
17632 succeeded, not only the immediately preceding substitution.  Therefore,
17633 always use a fake @samp{t clear} followed by a @samp{:clear} on the next
17634 line, to reset the @samp{t} flag where needed.
17636 Secondly, you cannot rely on @command{sed} to clear the flag at each new
17637 cycle.
17639 One portable implementation of the script above is:
17641 @example
17642 t clear
17643 :clear
17644 s/keep me/kept/g
17645 t end
17646 s/.*/deleted/g
17647 :end
17648 @end example
17650 @item @command{sleep}
17651 @c ------------------
17652 @prindex @command{sleep}
17653 Using @command{sleep} is generally portable.  However, remember that
17654 adding a @command{sleep} to work around timestamp issues, with a minimum
17655 granularity of one second, doesn't scale well for parallel builds on
17656 modern machines with sub-second process completion.
17658 @item @command{sort}
17659 @c -----------------
17660 @prindex @command{sort}
17661 Remember that sort order is influenced by the current locale.  Inside
17662 @file{configure}, the C locale is in effect, but in Makefile snippets,
17663 you may need to specify @code{LC_ALL=C sort}.
17665 @item @command{tar}
17666 @c ----------------
17667 @prindex @command{tar}
17668 There are multiple file formats for @command{tar}; if you use Automake,
17669 the macro @code{AM_INIT_AUTOMAKE} has some options controlling which
17670 level of portability to use.
17672 @anchor{touch}
17673 @item @command{touch}
17674 @c ------------------
17675 @prindex @command{touch}
17676 @cindex timestamp resolution
17677 If you specify the desired timestamp (e.g., with the @option{-r}
17678 option), @command{touch} typically uses the @code{utime} or
17679 @code{utimes} system call, which can result in the same kind of
17680 timestamp truncation problems that @samp{cp -p} has.
17682 On ancient @acronym{BSD} systems, @command{touch} or any command that
17683 results in an empty file does not update the timestamps, so use a
17684 command like @command{echo} as a workaround.
17685 Also,
17686 @acronym{GNU} @command{touch} 3.16r (and presumably all before that)
17687 fails to work on SunOS 4.1.3 when the empty file is on an
17688 @acronym{NFS}-mounted 4.2 volume.
17689 However, these problems are no longer of practical concern.
17691 @item @command{tr}
17692 @c ---------------
17693 @prindex @command{tr}
17694 @cindex carriage return, deleting
17695 @cindex deleting carriage return
17696 Not all versions of @command{tr} handle all backslash character escapes.
17697 For example, Solaris 10 @command{/usr/ucb/tr} falls over, even though
17698 Solaris contains more modern @command{tr} in other locations.
17699 Therefore, it is more portable to use octal escapes, even though this
17700 ties the result to @acronym{ASCII}, when using @command{tr} to delete
17701 newlines or carriage returns.
17703 @example
17704 $ @kbd{@{ echo moon; echo light; @} | /usr/ucb/tr -d '\n' ; echo}
17706 light
17707 $ @kbd{@{ echo moon; echo light; @} | /usr/bin/tr -d '\n' ; echo}
17708 moonlight
17709 $ @kbd{@{ echo moon; echo light; @} | /usr/ucb/tr -d '\012' ; echo}
17710 moonlight
17711 @end example
17713 Posix requires @command{tr} to operate on binary files.  But at least
17714 Solaris @command{/usr/ucb/tr} still fails to handle @samp{\0} as the
17715 octal escape for @code{NUL}.  On Solaris, when using @command{tr} to
17716 neutralize a binary file by converting @code{NUL} to a different
17717 character, it is necessary to use @command{/usr/xpg4/bin/tr} instead.
17719 @example
17720 $ @kbd{printf 'a\0b\n' | /usr/ucb/tr '\0' '~' | wc -c}
17722 $ @kbd{printf 'a\0b\n' | /usr/xpg4/bin/tr '\0' '~' | wc -c}
17724 @end example
17726 @end table
17729 @node Portable Make
17730 @chapter Portable Make Programming
17731 @prindex @command{make}
17732 @cindex Limitations of @command{make}
17734 Writing portable makefiles is an art.  Since a makefile's commands are
17735 executed by the shell, you must consider the shell portability issues
17736 already mentioned.  However, other issues are specific to @command{make}
17737 itself.
17739 @menu
17740 * $< in Ordinary Make Rules::   $< in ordinary rules
17741 * Failure in Make Rules::       Failing portably in rules
17742 * Special Chars in Names::      Special Characters in Macro Names
17743 * Backslash-Newline-Newline::   Empty last lines in macro definitions
17744 * Backslash-Newline Comments::  Spanning comments across line boundaries
17745 * Long Lines in Makefiles::     Line length limitations
17746 * Macros and Submakes::         @code{make macro=value} and submakes
17747 * The Make Macro MAKEFLAGS::    @code{$(MAKEFLAGS)} portability issues
17748 * The Make Macro SHELL::        @code{$(SHELL)} portability issues
17749 * Parallel Make::               Parallel @command{make} quirks
17750 * Comments in Make Rules::      Other problems with Make comments
17751 * obj/ and Make::               Don't name a subdirectory @file{obj}
17752 * make -k Status::              Exit status of @samp{make -k}
17753 * VPATH and Make::              @code{VPATH} woes
17754 * Single Suffix Rules::         Single suffix rules and separated dependencies
17755 * Timestamps and Make::         Subsecond timestamp resolution
17756 @end menu
17758 @node $< in Ordinary Make Rules
17759 @section @code{$<} in Ordinary Make Rules
17761 Posix says that the @samp{$<} construct in makefiles can be
17762 used only in inference rules and in the @samp{.DEFAULT} rule; its
17763 meaning in ordinary rules is unspecified.  Solaris @command{make}
17764 for instance replaces it with the empty string.  Open@acronym{BSD} (3.0 and
17765 later) @command{make} diagnoses these uses and errors out.
17767 @node Failure in Make Rules
17768 @section Failure in Make Rules
17770 Posix 2008 requires that @command{make} must invoke each command with
17771 the equivalent of a @samp{sh -e -c} subshell, which causes the
17772 subshell to exit immediately if a subsidiary simple-command fails,
17773 although not all @command{make} implementations have historically
17774 followed this rule.  For
17775 example, the command @samp{touch T; rm -f U} may attempt to
17776 remove @file{U} even if the @command{touch} fails, although this is not
17777 permitted with Posix make.  One way to work around failures in simple
17778 commands is to reword them so that they always succeed, e.g., @samp{touch
17779 T || :; rm -f U}.
17780 However, even this approach can run into common bugs in @acronym{BSD}
17781 implementations of the @option{-e} option of @command{sh} and
17782 @command{set} (@pxref{set, , Limitations of Shell Builtins}), so if you
17783 are worried
17784 about porting to buggy @acronym{BSD} shells it may be simpler to migrate
17785 complicated @command{make} actions into separate scripts.
17787 @node Special Chars in Names
17788 @section Special Characters in Make Macro Names
17790 Posix limits macro names to nonempty strings containing only
17791 @acronym{ASCII} letters and digits, @samp{.}, and @samp{_}.  Many
17792 @command{make} implementations allow a wider variety of characters, but
17793 portable makefiles should avoid them.  It is portable to start a name
17794 with a special character, e.g., @samp{$(.FOO)}.
17796 Some ancient @command{make} implementations don't support leading
17797 underscores in macro names.  An example is @acronym{NEWS-OS} 4.2R.
17799 @example
17800 $ @kbd{cat Makefile}
17801 _am_include = #
17802 _am_quote =
17803 all:; @@echo this is test
17804 $ @kbd{make}
17805 Make: Must be a separator on rules line 2.  Stop.
17806 $ @kbd{cat Makefile2}
17807 am_include = #
17808 am_quote =
17809 all:; @@echo this is test
17810 $ @kbd{make -f Makefile2}
17811 this is test
17812 @end example
17814 @noindent
17815 However, this problem is no longer of practical concern.
17817 @node Backslash-Newline-Newline
17818 @section Backslash-Newline-Newline in Make Macro Values
17820 @c  This has been seen on ia64 hpux 11.20, and on one hppa hpux 10.20,
17821 @c  but another hppa hpux 10.20 didn't have it.  Bob Proulx
17822 @c  <bob@proulx.com> thinks it was in hpux 8.0 too.
17823 On some versions of @acronym{HP-UX}, @command{make} reads multiple newlines
17824 following a backslash, continuing to the next non-empty line.  For
17825 example,
17827 @example
17828 FOO = one \
17830 BAR = two
17832 test:
17833         : FOO is "$(FOO)"
17834         : BAR is "$(BAR)"
17835 @end example
17837 @noindent
17838 shows @code{FOO} equal to @code{one BAR = two}.  Other implementations
17839 sensibly let a backslash continue only to the immediately following
17840 line.
17842 @node Backslash-Newline Comments
17843 @section Backslash-Newline in Make Comments
17845 According to Posix, Make comments start with @code{#}
17846 and continue until an unescaped newline is reached.
17848 @example
17849 $ @kbd{cat Makefile}
17850 # A = foo \
17851       bar \
17852       baz
17854 all:
17855         @@echo ok
17856 $ @kbd{make}   # GNU make
17858 @end example
17860 @noindent
17861 However this is not always the case.  Some implementations
17862 discard everything from @code{#} through the end of the line, ignoring any
17863 trailing backslash.
17865 @example
17866 $ @kbd{pmake}  # BSD make
17867 "Makefile", line 3: Need an operator
17868 Fatal errors encountered -- cannot continue
17869 @end example
17871 @noindent
17872 Therefore, if you want to comment out a multi-line definition, prefix each
17873 line with @code{#}, not only the first.
17875 @example
17876 # A = foo \
17877 #     bar \
17878 #     baz
17879 @end example
17881 @node Long Lines in Makefiles
17882 @section Long Lines in Makefiles
17884 Tru64 5.1's @command{make} has been reported to crash when given a
17885 makefile with lines longer than around 20 kB.  Earlier versions are
17886 reported to exit with @code{Line too long} diagnostics.
17888 @node Macros and Submakes
17889 @section @code{make macro=value} and Submakes
17891 A command-line variable definition such as @code{foo=bar} overrides any
17892 definition of @code{foo} in a makefile.  Some @command{make}
17893 implementations (such as @acronym{GNU} @command{make}) propagate this
17894 override to subsidiary invocations of @command{make}.  Some other
17895 implementations do not pass the substitution along to submakes.
17897 @example
17898 $ @kbd{cat Makefile}
17899 foo = foo
17900 one:
17901         @@echo $(foo)
17902         $(MAKE) two
17903 two:
17904         @@echo $(foo)
17905 $ @kbd{make foo=bar}            # GNU make 3.79.1
17907 make two
17908 make[1]: Entering directory `/home/adl'
17910 make[1]: Leaving directory `/home/adl'
17911 $ @kbd{pmake foo=bar}           # BSD make
17913 pmake two
17915 @end example
17917 You have a few possibilities if you do want the @code{foo=bar} override
17918 to propagate to submakes.  One is to use the @option{-e}
17919 option, which causes all environment variables to have precedence over
17920 the makefile macro definitions, and declare foo as an environment
17921 variable:
17923 @example
17924 $ @kbd{env foo=bar make -e}
17925 @end example
17927 The @option{-e} option is propagated to submakes automatically,
17928 and since the environment is inherited between @command{make}
17929 invocations, the @code{foo} macro is overridden in
17930 submakes as expected.
17932 This syntax (@code{foo=bar make -e}) is portable only when used
17933 outside of a makefile, for instance from a script or from the
17934 command line.  When run inside a @command{make} rule, @acronym{GNU}
17935 @command{make} 3.80 and prior versions forget to propagate the
17936 @option{-e} option to submakes.
17938 Moreover, using @option{-e} could have unexpected side effects if your
17939 environment contains some other macros usually defined by the
17940 makefile.  (See also the note about @code{make -e} and @code{SHELL}
17941 below.)
17943 Another way to propagate overrides to submakes is to do it
17944 manually, from your makefile:
17946 @example
17947 foo = foo
17948 one:
17949         @@echo $(foo)
17950         $(MAKE) foo=$(foo) two
17951 two:
17952         @@echo $(foo)
17953 @end example
17955 You need to foresee all macros that a user might want to override if
17956 you do that.
17958 @node The Make Macro MAKEFLAGS
17959 @section The Make Macro MAKEFLAGS
17960 @cindex @code{MAKEFLAGS} and @command{make}
17961 @cindex @command{make} and @code{MAKEFLAGS}
17963 Posix requires @command{make} to use @code{MAKEFLAGS} to affect the
17964 current and recursive invocations of make, but allows implementations
17965 several formats for the variable.  It is tricky to parse
17966 @code{$MAKEFLAGS} to determine whether @option{-s} for silent execution
17967 or @option{-k} for continued execution are in effect.  For example, you
17968 cannot assume that the first space-separated word in @code{$MAKEFLAGS}
17969 contains single-letter options, since in the Cygwin version of
17970 @acronym{GNU} @command{make} it is either @option{--unix} or
17971 @option{--win32} with the second word containing single-letter options.
17973 @example
17974 $ @kbd{cat Makefile}
17975 all:
17976         @@echo MAKEFLAGS = $(MAKEFLAGS)
17977 $ @kbd{make}
17978 MAKEFLAGS = --unix
17979 $ @kbd{make -k}
17980 MAKEFLAGS = --unix -k
17981 @end example
17983 @node The Make Macro SHELL
17984 @section The Make Macro @code{SHELL}
17985 @cindex @code{SHELL} and @command{make}
17986 @cindex @command{make} and @code{SHELL}
17988 Posix-compliant @command{make} internally uses the @code{$(SHELL)}
17989 macro to spawn shell processes and execute Make rules.  This
17990 is a builtin macro supplied by @command{make}, but it can be modified
17991 by a makefile or by a command-line argument.
17993 Not all @command{make} implementations define this @code{SHELL} macro.
17994 Tru64
17995 @command{make} is an example; this implementation always uses
17996 @code{/bin/sh}.  So it's a good idea to always define @code{SHELL} in
17997 your makefiles.  If you use Autoconf, do
17999 @example
18000 SHELL = @@SHELL@@
18001 @end example
18003 @noindent
18004 If you use Automake, this is done for you.
18006 Do not force @code{SHELL = /bin/sh} because that is not correct
18007 everywhere.  Remember, @file{/bin/sh} is not Posix compliant on many
18008 systems, such as FreeBSD 4, NetBSD 3, AIX 3, Solaris 10, or Tru64.
18009 Additionally, @acronym{DJGPP} lacks @code{/bin/sh}, and when its
18010 @acronym{GNU} @command{make} port sees such a setting it enters a
18011 special emulation mode where features like pipes and redirections are
18012 emulated on top of DOS's @command{command.com}.  Unfortunately this
18013 emulation is incomplete; for instance it does not handle command
18014 substitutions.  Using @code{@@SHELL@@} means that your makefile will
18015 benefit from the same improved shell, such as @command{bash} or
18016 @command{ksh}, that was discovered during @command{configure}, so that
18017 you aren't fighting two different sets of shell bugs between the two
18018 contexts.
18020 Posix-compliant @command{make} should never acquire the value of
18021 $(SHELL) from the environment, even when @code{make -e} is used
18022 (otherwise, think about what would happen to your rules if
18023 @code{SHELL=/bin/tcsh}).
18025 However not all @command{make} implementations have this exception.
18026 For instance it's not surprising that Tru64 @command{make} doesn't
18027 protect @code{SHELL}, since it doesn't use it.
18029 @example
18030 $ @kbd{cat Makefile}
18031 SHELL = /bin/sh
18032 FOO = foo
18033 all:
18034         @@echo $(SHELL)
18035         @@echo $(FOO)
18036 $ @kbd{env SHELL=/bin/tcsh FOO=bar make -e}   # Tru64 Make
18037 /bin/tcsh
18039 $ @kbd{env SHELL=/bin/tcsh FOO=bar gmake -e}  # GNU make
18040 /bin/sh
18042 @end example
18044 Conversely, @command{make} is not supposed to export any changes to the
18045 macro @code{SHELL} to child processes.  Again, many implementations
18046 break this rule:
18048 @example
18049 $ @kbd{cat Makefile}
18050 all:
18051         @@echo $(SHELL)
18052         @@printenv SHELL
18053 $ @kbd{env SHELL=sh make -e SHELL=/bin/ksh}   # BSD Make, GNU make 3.80
18054 /bin/ksh
18055 /bin/ksh
18056 $ @kbd{env SHELL=sh gmake -e SHELL=/bin/ksh}  # GNU make 3.81
18057 /bin/ksh
18059 @end example
18061 @node Parallel Make
18062 @section Parallel Make
18063 @cindex Parallel @command{make}
18065 Support for parallel execution in @command{make} implementation varies.
18066 Generally, using @acronym{GNU} make is your best bet.  When NetBSD
18067 @command{make} is invoked with @option{-j@var{N}}, it will reuse the
18068 same shell for multiple commands within one recipe.  This can have
18069 unexpected consequences.@footnote{Note that @acronym{GNU} make has
18070 heuristics to avoid spawning a shell at all if the command is deemed
18071 safe to be executed directly.} For example, change of directories or
18072 variables persist between commands:
18074 @example
18075 all:
18076         @@var=value; cd /; pwd; echo $$var; echo $$$$
18077         @@pwd; echo $$var; echo $$$$
18078 @end example
18080 @noindent
18081 may output the following with @code{make -j1}:
18083 @example
18084 --- all ---
18086 value
18087 32235
18089 value
18090 32235
18091 @end example
18093 while without @option{-j1}, or with @option{-B}, the output looks less
18094 surprising:
18096 @example
18098 value
18099 32238
18100 /tmp
18102 32239
18103 @end example
18105 Another consequence of this is that, if one command in a recipe uses
18106 @code{exit 0} to indicate a successful exit, the shell will be gone
18107 and the remaining commands of this recipe will not be executed.
18109 The above example also shows additional status output NetBSD
18110 @command{make} produces in parallel mode for targets being updated.
18112 Furthermore, parallel NetBSD @command{make} will route standard error
18113 from commands that it spawns into its own standard output, and may
18114 remove leading whitespace from output lines.
18116 You can avoid these issues by using the @option{-B} option to enable
18117 compatibility semantics.  However, that will effectively also disable
18118 all parallelism as that will cause prerequisites to be updated in the
18119 order they are listed in a rule.
18121 @node Comments in Make Rules
18122 @section Comments in Make Rules
18123 @cindex Comments in @file{Makefile} rules
18124 @cindex @file{Makefile} rules and comments
18126 Never put comments in a rule.
18128 Some @command{make} treat anything starting with a tab as a command for
18129 the current rule, even if the tab is immediately followed by a @code{#}.
18130 The @command{make} from Tru64 Unix V5.1 is one of them.  The following
18131 makefile runs @code{# foo} through the shell.
18133 @example
18134 all:
18135         # foo
18136 @end example
18138 @node obj/ and Make
18139 @section The @file{obj/} Subdirectory and Make
18140 @cindex @file{obj/}, subdirectory
18141 @cindex @acronym{BSD} @command{make} and @file{obj/}
18143 Never name one of your subdirectories @file{obj/} if you don't like
18144 surprises.
18146 If an @file{obj/} directory exists, @acronym{BSD} @command{make} enters it
18147 before reading the makefile.  Hence the makefile in the
18148 current directory is not read.
18150 @example
18151 $ @kbd{cat Makefile}
18152 all:
18153         echo Hello
18154 $ @kbd{cat obj/Makefile}
18155 all:
18156         echo World
18157 $ @kbd{make}      # GNU make
18158 echo Hello
18159 Hello
18160 $ @kbd{pmake}     # BSD make
18161 echo World
18162 World
18163 @end example
18165 @node make -k Status
18166 @section Exit Status of @code{make -k}
18167 @cindex @code{make -k}
18169 Do not rely on the exit status of @code{make -k}.  Some implementations
18170 reflect whether they encountered an error in their exit status; other
18171 implementations always succeed.
18173 @example
18174 $ @kbd{cat Makefile}
18175 all:
18176         false
18177 $ @kbd{make -k; echo exit status: $?}    # GNU make
18178 false
18179 make: *** [all] Error 1
18180 exit status: 2
18181 $ @kbd{pmake -k; echo exit status: $?}   # BSD make
18182 false
18183 *** Error code 1 (continuing)
18184 exit status: 0
18185 @end example
18187 @node VPATH and Make
18188 @section @code{VPATH} and Make
18189 @cindex @code{VPATH}
18191 Posix does not specify the semantics of @code{VPATH}.  Typically,
18192 @command{make} supports @code{VPATH}, but its implementation is not
18193 consistent.
18195 Autoconf and Automake support makefiles whose usages of @code{VPATH} are
18196 portable to recent-enough popular implementations of @command{make}, but
18197 to keep the resulting makefiles portable, a package's makefile
18198 prototypes must take the following issues into account.  These issues
18199 are complicated and are often poorly understood, and installers who use
18200 @code{VPATH} should expect to find many bugs in this area.  If you use
18201 @code{VPATH}, the simplest way to avoid these portability bugs is to
18202 stick with @acronym{GNU} @command{make}, since it is the most
18203 commonly-used @command{make} among Autoconf users.
18205 Here are some known issues with some @code{VPATH}
18206 implementations.
18208 @menu
18209 * Variables listed in VPATH::   @code{VPATH} must be literal on ancient hosts
18210 * VPATH and Double-colon::      Problems with @samp{::} on ancient hosts
18211 * $< in Explicit Rules::        @code{$<} does not work in ordinary rules
18212 * Automatic Rule Rewriting::    @code{VPATH} goes wild on Solaris
18213 * Tru64 Directory Magic::       @command{mkdir} goes wild on Tru64
18214 * Make Target Lookup::          More details about @code{VPATH} lookup
18215 @end menu
18217 @node Variables listed in VPATH
18218 @subsection Variables listed in @code{VPATH}
18219 @cindex @code{VPATH} and variables
18220 @cindex variables and @code{VPATH}
18222 Do not set @code{VPATH} to the value of another variable, for example
18223 @samp{VPATH = $(srcdir)}, because some ancient versions of
18224 @command{make} do not do variable substitutions on the value of
18225 @code{VPATH}.  For example, use this
18227 @example
18228 srcdir = @@srcdir@@
18229 VPATH = @@srcdir@@
18230 @end example
18232 @noindent
18233 rather than @samp{VPATH = $(srcdir)}.  Note that with @acronym{GNU}
18234 Automake, there is no need to set this yourself.
18236 @node VPATH and Double-colon
18237 @subsection @code{VPATH} and Double-colon Rules
18238 @cindex @code{VPATH} and double-colon rules
18239 @cindex double-colon rules and @code{VPATH}
18241 With ancient versions of Sun @command{make},
18242 any assignment to @code{VPATH} causes @command{make} to execute only
18243 the first set of double-colon rules.
18244 However, this problem is no longer of practical concern.
18246 @node $< in Explicit Rules
18247 @subsection @code{$<} Not Supported in Explicit Rules
18248 @cindex explicit rules, @code{$<}, and @code{VPATH}
18249 @cindex @code{$<}, explicit rules, and @code{VPATH}
18250 @cindex @code{VPATH}, explicit rules, and @code{$<}
18252 Using @code{$<} in explicit rules is not portable.
18253 The prerequisite file must be named explicitly in the rule.  If you want
18254 to find the prerequisite via a @code{VPATH} search, you have to code the
18255 whole thing manually.  @xref{Build Directories}.
18257 @node Automatic Rule Rewriting
18258 @subsection Automatic Rule Rewriting
18259 @cindex @code{VPATH} and automatic rule rewriting
18260 @cindex automatic rule rewriting and @code{VPATH}
18262 Some @command{make} implementations, such as Solaris and Tru64,
18263 search for prerequisites in @code{VPATH} and
18264 then rewrite each occurrence as a plain word in the rule.
18265 For instance:
18267 @example
18268 # This isn't portable to GNU make.
18269 VPATH = ../pkg/src
18270 f.c: if.c
18271         cp if.c f.c
18272 @end example
18274 @noindent
18275 executes @code{cp ../pkg/src/if.c f.c} if @file{if.c} is
18276 found in @file{../pkg/src}.
18278 However, this rule leads to real problems in practice.  For example, if
18279 the source directory contains an ordinary file named @file{test} that is
18280 used in a dependency, Solaris @command{make} rewrites commands like
18281 @samp{if test -r foo; @dots{}} to @samp{if ../pkg/src/test -r foo;
18282 @dots{}}, which is typically undesirable.  To avoid this problem,
18283 portable makefiles should never mention a source file whose name is that
18284 of a shell keyword like @file{until} or a shell command like
18285 @command{cat} or @command{gcc} or @command{test}.
18287 Because of these problems @acronym{GNU} @command{make} and many other
18288 @command{make} implementations do not rewrite commands, so portable
18289 makefiles should
18290 search @code{VPATH} manually.  It is tempting to write this:
18292 @smallexample
18293 # This isn't portable to Solaris make.
18294 VPATH = ../pkg/src
18295 f.c: if.c
18296         cp `test -f if.c || echo $(VPATH)/`if.c f.c
18297 @end smallexample
18299 @noindent
18300 However, the ``prerequisite rewriting'' still applies here.  So if
18301 @file{if.c} is in @file{../pkg/src}, Solaris and Tru64 @command{make}
18302 execute
18304 @smallexample
18305 cp `test -f ../pkg/src/if.c || echo ../pkg/src/`if.c f.c
18306 @end smallexample
18308 @noindent
18309 which reduces to
18311 @example
18312 cp if.c f.c
18313 @end example
18315 @noindent
18316 and thus fails.  Oops.
18318 A simple workaround, and good practice anyway, is to use @samp{$?} and
18319 @samp{$@@} when possible:
18321 @smallexample
18322 VPATH = ../pkg/src
18323 f.c: if.c
18324         cp $? $@@
18325 @end smallexample
18327 @noindent
18328 but this does not generalize well to commands with multiple
18329 prerequisites.  A more general workaround is to rewrite the rule so that
18330 the prerequisite @file{if.c} never appears as a plain word.  For
18331 example, these three rules would be safe, assuming @file{if.c} is in
18332 @file{../pkg/src} and the other files are in the working directory:
18334 @smallexample
18335 VPATH = ../pkg/src
18336 f.c: if.c f1.c
18337         cat `test -f ./if.c || echo $(VPATH)/`if.c f1.c >$@@
18338 g.c: if.c g1.c
18339         cat `test -f 'if.c' || echo $(VPATH)/`if.c g1.c >$@@
18340 h.c: if.c h1.c
18341         cat `test -f "if.c" || echo $(VPATH)/`if.c h1.c >$@@
18342 @end smallexample
18344 Things get worse when your prerequisites are in a macro.
18346 @example
18347 VPATH = ../pkg/src
18348 HEADERS = f.h g.h h.h
18349 install-HEADERS: $(HEADERS)
18350         for i in $(HEADERS); do \
18351           $(INSTALL) -m 644 \
18352             `test -f $$i || echo $(VPATH)/`$$i \
18353             $(DESTDIR)$(includedir)/$$i; \
18354         done
18355 @end example
18357 The above @code{install-HEADERS} rule is not Solaris-proof because @code{for
18358 i in $(HEADERS);} is expanded to @code{for i in f.h g.h h.h;}
18359 where @code{f.h} and @code{g.h} are plain words and are hence
18360 subject to @code{VPATH} adjustments.
18362 If the three files are in @file{../pkg/src}, the rule is run as:
18364 @example
18365 for i in ../pkg/src/f.h ../pkg/src/g.h h.h; do \
18366   install -m 644 \
18367      `test -f $i || echo ../pkg/src/`$i \
18368      /usr/local/include/$i; \
18369 done
18370 @end example
18372 where the two first @command{install} calls fail.  For instance,
18373 consider the @code{f.h} installation:
18375 @example
18376 install -m 644 \
18377   `test -f ../pkg/src/f.h || \
18378     echo ../pkg/src/ \
18379   `../pkg/src/f.h \
18380   /usr/local/include/../pkg/src/f.h;
18381 @end example
18383 @noindent
18384 It reduces to:
18386 @example
18387 install -m 644 \
18388   ../pkg/src/f.h \
18389   /usr/local/include/../pkg/src/f.h;
18390 @end example
18392 Note that the manual @code{VPATH} search did not cause any problems here;
18393 however this command installs @file{f.h} in an incorrect directory.
18395 Trying to quote @code{$(HEADERS)} in some way, as we did for
18396 @code{foo.c} a few makefiles ago, does not help:
18398 @example
18399 install-HEADERS: $(HEADERS)
18400         headers='$(HEADERS)'; \
18401         for i in $$headers; do \
18402           $(INSTALL) -m 644 \
18403             `test -f $$i || echo $(VPATH)/`$$i \
18404             $(DESTDIR)$(includedir)/$$i; \
18405         done
18406 @end example
18408 Now, @code{headers='$(HEADERS)'} macro-expands to:
18410 @example
18411 headers='f.h g.h h.h'
18412 @end example
18414 @noindent
18415 but @code{g.h} is still a plain word.  (As an aside, the idiom
18416 @code{headers='$(HEADERS)'; for i in $$headers;} is a good
18417 idea if @code{$(HEADERS)} can be empty, because some shells diagnose a
18418 syntax error on @code{for i in;}.)
18420 One workaround is to strip this unwanted @file{../pkg/src/} prefix manually:
18422 @example
18423 VPATH = ../pkg/src
18424 HEADERS = f.h g.h h.h
18425 install-HEADERS: $(HEADERS)
18426         headers='$(HEADERS)'; \
18427         for i in $$headers; do \
18428           i=`expr "$$i" : '$(VPATH)/\(.*\)'`;
18429           $(INSTALL) -m 644 \
18430             `test -f $$i || echo $(VPATH)/`$$i \
18431             $(DESTDIR)$(includedir)/$$i; \
18432         done
18433 @end example
18435 Automake does something similar.  However the above hack works only if
18436 the files listed in @code{HEADERS} are in the current directory or a
18437 subdirectory; they should not be in an enclosing directory.  If we had
18438 @code{HEADERS = ../f.h}, the above fragment would fail in a VPATH
18439 build with Tru64 @command{make}.  The reason is that not only does
18440 Tru64 @command{make} rewrite dependencies, but it also simplifies
18441 them.  Hence @code{../f.h} becomes @code{../pkg/f.h} instead of
18442 @code{../pkg/src/../f.h}.  This obviously defeats any attempt to strip
18443 a leading @file{../pkg/src/} component.
18445 The following example makes the behavior of Tru64 @command{make}
18446 more apparent.
18448 @example
18449 $ @kbd{cat Makefile}
18450 VPATH = sub
18451 all: ../foo
18452         echo ../foo
18453 $ @kbd{ls}
18454 Makefile foo
18455 $ @kbd{make}
18456 echo foo
18458 @end example
18460 @noindent
18461 Dependency @file{../foo} was found in @file{sub/../foo}, but Tru64
18462 @command{make} simplified it as @file{foo}.  (Note that the @file{sub/}
18463 directory does not even exist, this just means that the simplification
18464 occurred before the file was checked for.)
18466 For the record here is how SunOS 4 @command{make} behaves on this
18467 example.
18469 @smallexample
18470 $ @kbd{make}
18471 make: Fatal error: Don't know how to make target `../foo'
18472 $ @kbd{mkdir sub}
18473 $ @kbd{make}
18474 echo sub/../foo
18475 sub/../foo
18476 @end smallexample
18479 @node Tru64 Directory Magic
18480 @subsection Tru64 @command{make} Creates Prerequisite Directories Magically
18481 @cindex @code{VPATH} and prerequisite directories
18482 @cindex prerequisite directories and @code{VPATH}
18484 When a prerequisite is a subdirectory of @code{VPATH}, Tru64
18485 @command{make} creates it in the current directory.
18487 @example
18488 $ @kbd{mkdir -p foo/bar build}
18489 $ @kbd{cd build}
18490 $ @kbd{cat >Makefile <<END
18491 VPATH = ..
18492 all: foo/bar
18493 END}
18494 $ @kbd{make}
18495 mkdir foo
18496 mkdir foo/bar
18497 @end example
18499 This can yield unexpected results if a rule uses a manual @code{VPATH}
18500 search as presented before.
18502 @example
18503 VPATH = ..
18504 all : foo/bar
18505         command `test -d foo/bar || echo ../`foo/bar
18506 @end example
18508 The above @command{command} is run on the empty @file{foo/bar}
18509 directory that was created in the current directory.
18511 @node Make Target Lookup
18512 @subsection Make Target Lookup
18513 @cindex @code{VPATH}, resolving target pathnames
18515 @acronym{GNU} @command{make} uses a complex algorithm to decide when it
18516 should use files found via a @code{VPATH} search.  @xref{Search
18517 Algorithm, , How Directory Searches are Performed, make, The @acronym{GNU} Make
18518 Manual}.
18520 If a target needs to be rebuilt, @acronym{GNU} @command{make} discards the
18521 file name found during the @code{VPATH} search for this target, and
18522 builds the file locally using the file name given in the makefile.
18523 If a target does not need to be rebuilt, @acronym{GNU} @command{make} uses the
18524 file name found during the @code{VPATH} search.
18526 Other @command{make} implementations, like Net@acronym{BSD} @command{make}, are
18527 easier to describe: the file name found during the @code{VPATH} search
18528 is used whether the target needs to be rebuilt or not.  Therefore
18529 new files are created locally, but existing files are updated at their
18530 @code{VPATH} location.
18532 Open@acronym{BSD} and Free@acronym{BSD} @command{make}, however,
18533 never perform a
18534 @code{VPATH} search for a dependency that has an explicit rule.
18535 This is extremely annoying.
18537 When attempting a @code{VPATH} build for an autoconfiscated package
18538 (e.g., @code{mkdir build && cd build && ../configure}), this means
18539 @acronym{GNU}
18540 @command{make} builds everything locally in the @file{build}
18541 directory, while @acronym{BSD} @command{make} builds new files locally and
18542 updates existing files in the source directory.
18544 @example
18545 $ @kbd{cat Makefile}
18546 VPATH = ..
18547 all: foo.x bar.x
18548 foo.x bar.x: newer.x
18549         @@echo Building $@@
18550 $ @kbd{touch ../bar.x}
18551 $ @kbd{touch ../newer.x}
18552 $ @kbd{make}        # GNU make
18553 Building foo.x
18554 Building bar.x
18555 $ @kbd{pmake}       # NetBSD make
18556 Building foo.x
18557 Building ../bar.x
18558 $ @kbd{fmake}       # FreeBSD make, OpenBSD make
18559 Building foo.x
18560 Building bar.x
18561 $ @kbd{tmake}       # Tru64 make
18562 Building foo.x
18563 Building bar.x
18564 $ @kbd{touch ../bar.x}
18565 $ @kbd{make}        # GNU make
18566 Building foo.x
18567 $ @kbd{pmake}       # NetBSD make
18568 Building foo.x
18569 $ @kbd{fmake}       # FreeBSD make, OpenBSD make
18570 Building foo.x
18571 Building bar.x
18572 $ @kbd{tmake}       # Tru64 make
18573 Building foo.x
18574 Building bar.x
18575 @end example
18577 Note how Net@acronym{BSD} @command{make} updates @file{../bar.x} in its
18578 VPATH location, and how Free@acronym{BSD}, Open@acronym{BSD}, and Tru64
18579 @command{make} always
18580 update @file{bar.x}, even when @file{../bar.x} is up to date.
18582 Another point worth mentioning is that once @acronym{GNU} @command{make} has
18583 decided to ignore a @code{VPATH} file name (e.g., it ignored
18584 @file{../bar.x} in the above example) it continues to ignore it when
18585 the target occurs as a prerequisite of another rule.
18587 The following example shows that @acronym{GNU} @command{make} does not look up
18588 @file{bar.x} in @code{VPATH} before performing the @code{.x.y} rule,
18589 because it ignored the @code{VPATH} result of @file{bar.x} while running
18590 the @code{bar.x: newer.x} rule.
18592 @example
18593 $ @kbd{cat Makefile}
18594 VPATH = ..
18595 all: bar.y
18596 bar.x: newer.x
18597         @@echo Building $@@
18598 .SUFFIXES: .x .y
18599 .x.y:
18600         cp $< $@@
18601 $ @kbd{touch ../bar.x}
18602 $ @kbd{touch ../newer.x}
18603 $ @kbd{make}        # GNU make
18604 Building bar.x
18605 cp bar.x bar.y
18606 cp: cannot stat `bar.x': No such file or directory
18607 make: *** [bar.y] Error 1
18608 $ @kbd{pmake}       # NetBSD make
18609 Building ../bar.x
18610 cp ../bar.x bar.y
18611 $ @kbd{rm bar.y}
18612 $ @kbd{fmake}       # FreeBSD make, OpenBSD make
18613 echo Building bar.x
18614 cp bar.x bar.y
18615 cp: cannot stat `bar.x': No such file or directory
18616 *** Error code 1
18617 $ @kbd{tmake}       # Tru64 make
18618 Building bar.x
18619 cp: bar.x: No such file or directory
18620 *** Exit 1
18621 @end example
18623 Note that if you drop away the command from the @code{bar.x: newer.x}
18624 rule, @acronym{GNU} @command{make} magically starts to work: it
18625 knows that @code{bar.x} hasn't been updated, therefore it doesn't
18626 discard the result from @code{VPATH} (@file{../bar.x}) in succeeding
18627 uses.  Tru64 also works, but Free@acronym{BSD} and Open@acronym{BSD}
18628 still don't.
18630 @example
18631 $ @kbd{cat Makefile}
18632 VPATH = ..
18633 all: bar.y
18634 bar.x: newer.x
18635 .SUFFIXES: .x .y
18636 .x.y:
18637         cp $< $@@
18638 $ @kbd{touch ../bar.x}
18639 $ @kbd{touch ../newer.x}
18640 $ @kbd{make}        # GNU make
18641 cp ../bar.x bar.y
18642 $ @kbd{rm bar.y}
18643 $ @kbd{pmake}       # NetBSD make
18644 cp ../bar.x bar.y
18645 $ @kbd{rm bar.y}
18646 $ @kbd{fmake}       # FreeBSD make, OpenBSD make
18647 cp bar.x bar.y
18648 cp: cannot stat `bar.x': No such file or directory
18649 *** Error code 1
18650 $ @kbd{tmake}       # Tru64 make
18651 cp ../bar.x bar.y
18652 @end example
18654 It seems the sole solution that would please every @command{make}
18655 implementation is to never rely on @code{VPATH} searches for targets.
18656 In other words, @code{VPATH} should be reserved to unbuilt sources.
18659 @node Single Suffix Rules
18660 @section Single Suffix Rules and Separated Dependencies
18661 @cindex Single Suffix Inference Rule
18662 @cindex Rule, Single Suffix Inference
18663 A @dfn{Single Suffix Rule} is basically a usual suffix (inference) rule
18664 (@samp{.from.to:}), but which @emph{destination} suffix is empty
18665 (@samp{.from:}).
18667 @cindex Separated Dependencies
18668 @dfn{Separated dependencies} simply refers to listing the prerequisite
18669 of a target, without defining a rule.  Usually one can list on the one
18670 hand side, the rules, and on the other hand side, the dependencies.
18672 Solaris @command{make} does not support separated dependencies for
18673 targets defined by single suffix rules:
18675 @example
18676 $ @kbd{cat Makefile}
18677 .SUFFIXES: .in
18678 foo: foo.in
18679 .in:
18680         cp $< $@@
18681 $ @kbd{touch foo.in}
18682 $ @kbd{make}
18683 $ @kbd{ls}
18684 Makefile  foo.in
18685 @end example
18687 @noindent
18688 while @acronym{GNU} Make does:
18690 @example
18691 $ @kbd{gmake}
18692 cp foo.in foo
18693 $ @kbd{ls}
18694 Makefile  foo       foo.in
18695 @end example
18697 Note it works without the @samp{foo: foo.in} dependency.
18699 @example
18700 $ @kbd{cat Makefile}
18701 .SUFFIXES: .in
18702 .in:
18703         cp $< $@@
18704 $ @kbd{make foo}
18705 cp foo.in foo
18706 @end example
18708 @noindent
18709 and it works with double suffix inference rules:
18711 @example
18712 $ @kbd{cat Makefile}
18713 foo.out: foo.in
18714 .SUFFIXES: .in .out
18715 .in.out:
18716         cp $< $@@
18717 $ @kbd{make}
18718 cp foo.in foo.out
18719 @end example
18721 As a result, in such a case, you have to write target rules.
18723 @node Timestamps and Make
18724 @section Timestamp Resolution and Make
18725 @cindex timestamp resolution
18726 Traditionally, file timestamps had 1-second resolution, and
18727 @command{make} used those timestamps to determine whether one file was
18728 newer than the other.  However, many modern file systems have
18729 timestamps with 1-nanosecond resolution.  Some @command{make}
18730 implementations look at the entire timestamp; others ignore the
18731 fractional part, which can lead to incorrect results.  Normally this
18732 is not a problem, but in some extreme cases you may need to use tricks
18733 like @samp{sleep 1} to work around timestamp truncation bugs.
18735 Commands like @samp{cp -p} and @samp{touch -r} typically do not copy
18736 file timestamps to their full resolutions (@pxref{touch, , Limitations of Usual
18737 Tools}).  Hence you should be wary of rules like this:
18739 @example
18740 dest: src
18741         cp -p src dest
18742 @end example
18744 as @file{dest} often appears to be older than @file{src} after the
18745 timestamp is truncated, and this can cause @command{make} to do
18746 needless rework the next time it is invoked.  To work around this
18747 problem, you can use a timestamp file, e.g.:
18749 @example
18750 dest-stamp: src
18751         cp -p src dest
18752         date >dest-stamp
18753 @end example
18758 @c ======================================== Portable C and C++ Programming
18760 @node Portable C and C++
18761 @chapter Portable C and C++ Programming
18762 @cindex Portable C and C++ programming
18764 C and C++ programs often use low-level features of the underlying
18765 system, and therefore are often more difficult to make portable to other
18766 platforms.
18768 Several standards have been developed to help make your programs more
18769 portable.  If you write programs with these standards in mind, you can
18770 have greater confidence that your programs work on a wide variety
18771 of systems.  @xref{Standards, , Language Standards Supported by
18772 @acronym{GCC}, gcc, Using the @acronym{GNU} Compiler Collection
18773 (@acronym{GCC})}, for a list of C-related
18774 standards.  Many programs also assume the
18775 @uref{http://@/www.opengroup.org/@/susv3, Posix standard}.
18777 Some old code is written to be portable to K&R C, which predates any C
18778 standard.  K&R C compilers are no longer of practical interest, though,
18779 and the rest of section assumes at least C89, the first C standard.
18781 Program portability is a huge topic, and this section can only briefly
18782 introduce common pitfalls.  @xref{System Portability, , Portability
18783 between System Types, standards, @acronym{GNU} Coding Standards}, for
18784 more information.
18786 @menu
18787 * Varieties of Unportability::  How to make your programs unportable
18788 * Integer Overflow::            When integers get too large
18789 * Preprocessor Arithmetic::     @code{#if} expression problems
18790 * Null Pointers::               Properties of null pointers
18791 * Buffer Overruns::             Subscript errors and the like
18792 * Volatile Objects::            @code{volatile} and signals
18793 * Floating Point Portability::  Portable floating-point arithmetic
18794 * Exiting Portably::            Exiting and the exit status
18795 @end menu
18797 @node Varieties of Unportability
18798 @section Varieties of Unportability
18799 @cindex portability
18801 Autoconf tests and ordinary programs often need to test what is allowed
18802 on a system, and therefore they may need to deliberately exceed the
18803 boundaries of what the standards allow, if only to see whether an
18804 optional feature is present.  When you write such a program, you should
18805 keep in mind the difference between constraints, unspecified behavior,
18806 and undefined behavior.
18808 In C, a @dfn{constraint} is a rule that the compiler must enforce.  An
18809 example constraint is that C programs must not declare a bit-field with
18810 negative width.  Tests can therefore reliably assume that programs with
18811 negative-width bit-fields are rejected by a compiler that conforms
18812 to the standard.
18814 @dfn{Unspecified behavior} is valid behavior, where the standard allows
18815 multiple possibilities.  For example, the order of evaluation of
18816 function arguments is unspecified.  Some unspecified behavior is
18817 @dfn{implementation-defined}, i.e., documented by the implementation,
18818 but since Autoconf tests cannot read the documentation they cannot
18819 distinguish between implementation-defined and other unspecified
18820 behavior.  It is common for Autoconf tests to probe implementations to
18821 determine otherwise-unspecified behavior.
18823 @dfn{Undefined behavior} is invalid behavior, where the standard allows
18824 the implementation to do anything it pleases.  For example,
18825 dereferencing a null pointer leads to undefined behavior.  If possible,
18826 test programs should avoid undefined behavior, since a program with
18827 undefined behavior might succeed on a test that should fail.
18829 The above rules apply to programs that are intended to conform to the
18830 standard.  However, strictly-conforming programs are quite rare, since
18831 the standards are so limiting.  A major goal of Autoconf is to support
18832 programs that use implementation features not described by the standard,
18833 and it is fairly common for test programs to violate the above rules, if
18834 the programs work well enough in practice.
18836 @node Integer Overflow
18837 @section Integer Overflow
18838 @cindex integer overflow
18839 @cindex overflow, signed integer
18840 @cindex signed integer overflow
18841 @cindex wraparound arithmetic
18843 In practice many portable C programs assume that signed integer overflow wraps
18844 around reliably using two's complement arithmetic.  Yet the C standard
18845 says that program behavior is undefined on overflow, and in a few cases
18846 C programs do not work on some modern implementations because their
18847 overflows do not wrap around as their authors expected.  Conversely, in
18848 signed integer remainder, the C standard requires overflow
18849 behavior that is commonly not implemented.
18851 @menu
18852 * Integer Overflow Basics::      Why integer overflow is a problem
18853 * Signed Overflow Examples::     Examples of code assuming wraparound
18854 * Optimization and Wraparound::  Optimizations that break uses of wraparound
18855 * Signed Overflow Advice::       Practical advice for signed overflow issues
18856 * Signed Integer Division::      @code{INT_MIN / -1} and @code{INT_MIN % -1}
18857 @end menu
18859 @node Integer Overflow Basics
18860 @subsection Basics of Integer Overflow
18861 @cindex integer overflow
18862 @cindex overflow, signed integer
18863 @cindex signed integer overflow
18864 @cindex wraparound arithmetic
18866 In languages like C, unsigned integer overflow reliably wraps around;
18867 e.g., @code{UINT_MAX + 1} yields zero.
18868 This is guaranteed by the C standard and is
18869 portable in practice, unless you specify aggressive,
18870 nonstandard optimization options
18871 suitable only for special applications.
18873 In contrast, the C standard says that signed integer overflow leads to
18874 undefined behavior where a program can do anything, including dumping
18875 core or overrunning a buffer.  The misbehavior can even precede the
18876 overflow.  Such an overflow can occur during addition, subtraction,
18877 multiplication, division, and left shift.
18879 Despite this requirement of the standard, many C programs and Autoconf
18880 tests assume that signed integer overflow silently wraps around modulo a
18881 power of two, using two's complement arithmetic, so long as you cast the
18882 resulting value to a signed integer type or store it into a signed
18883 integer variable.  If you use conservative optimization flags, such
18884 programs are generally portable to the vast majority of modern
18885 platforms, with a few exceptions discussed later.
18887 For historical reasons the C standard also allows implementations with
18888 ones' complement or signed magnitude arithmetic, but it is safe to
18889 assume two's complement nowadays.
18891 Also, overflow can occur when converting an out-of-range value to a
18892 signed integer type.  Here a standard implementation must define what
18893 happens, but this might include raising an exception.  In practice all
18894 known implementations support silent wraparound in this case, so you need
18895 not worry about other possibilities.
18897 @node Signed Overflow Examples
18898 @subsection Examples of Code Assuming Wraparound Overflow
18899 @cindex integer overflow
18900 @cindex overflow, signed integer
18901 @cindex signed integer overflow
18902 @cindex wraparound arithmetic
18904 There has long been a tension between what the C standard requires for
18905 signed integer overflow, and what C programs commonly assume.  The
18906 standard allows aggressive optimizations based on assumptions that
18907 overflow never occurs, but many practical C programs rely on overflow
18908 wrapping around.  These programs do not conform to the standard, but
18909 they commonly work in practice because compiler writers are
18910 understandably reluctant to implement optimizations that would break
18911 many programs, unless perhaps a user specifies aggressive optimization.
18913 The C Standard says that if a program has signed integer overflow its
18914 behavior is undefined, and the undefined behavior can even precede the
18915 overflow.  To take an extreme example:
18917 @c Inspired by Robert Dewar's example in
18918 @c <http://gcc.gnu.org/ml/gcc/2007-01/msg00038.html> (2007-01-01).
18919 @example
18920 if (password == expected_password)
18921   allow_superuser_privileges ();
18922 else if (counter++ == INT_MAX)
18923   abort ();
18924 else
18925   printf ("%d password mismatches\n", counter);
18926 @end example
18928 @noindent
18929 If the @code{int} variable @code{counter} equals @code{INT_MAX},
18930 @code{counter++} must overflow and the behavior is undefined, so the C
18931 standard allows the compiler to optimize away the test against
18932 @code{INT_MAX} and the @code{abort} call.
18933 Worse, if an earlier bug in the program lets the compiler deduce that
18934 @code{counter == INT_MAX} or that @code{counter} previously overflowed,
18935 the C standard allows the compiler to optimize away the password test
18936 and generate code that allows superuser privileges unconditionally.
18938 Despite this requirement by the standard, it has long been common for C
18939 code to assume wraparound arithmetic after signed overflow, and all
18940 known practical C implementations support some C idioms that assume
18941 wraparound signed arithmetic, even if the idioms do not conform
18942 strictly to the standard.  If your code looks like the following
18943 examples it will almost surely work with real-world compilers.
18945 Here is an example derived from the 7th Edition Unix implementation of
18946 @code{atoi} (1979-01-10):
18948 @example
18949 char *p;
18950 int f, n;
18951 @dots{}
18952 while (*p >= '0' && *p <= '9')
18953   n = n * 10 + *p++ - '0';
18954 return (f ? -n : n);
18955 @end example
18957 @noindent
18958 Even if the input string is in range, on most modern machines this has
18959 signed overflow when computing the most negative integer (the @code{-n}
18960 overflows) or a value near an extreme integer (the first @code{+}
18961 overflows).
18963 Here is another example, derived from the 7th Edition implementation of
18964 @code{rand} (1979-01-10).  Here the programmer expects both
18965 multiplication and addition to wrap on overflow:
18967 @example
18968 static long int randx = 1;
18969 @dots{}
18970 randx = randx * 1103515245 + 12345;
18971 return (randx >> 16) & 077777;
18972 @end example
18974 In the following example, derived from the @acronym{GNU} C Library 2.5
18975 implementation of @code{mktime} (2006-09-09), the code assumes
18976 wraparound arithmetic in @code{+} to detect signed overflow:
18978 @example
18979 time_t t, t1, t2;
18980 int sec_requested, sec_adjustment;
18981 @dots{}
18982 t1 = t + sec_requested;
18983 t2 = t1 + sec_adjustment;
18984 if (((t1 < t) != (sec_requested < 0))
18985     | ((t2 < t1) != (sec_adjustment < 0)))
18986   return -1;
18987 @end example
18989 If your code looks like these examples, it is probably safe even though
18990 it does not strictly conform to the C standard.  This might lead one to
18991 believe that one can generally assume wraparound on overflow, but that
18992 is not always true, as can be seen in the next section.
18994 @node Optimization and Wraparound
18995 @subsection Optimizations That Break Wraparound Arithmetic
18996 @cindex loop induction
18998 Compilers sometimes generate code that is incompatible with wraparound
18999 integer arithmetic.  A simple example is an algebraic simplification: a
19000 compiler might translate @code{(i * 2000) / 1000} to @code{i * 2}
19001 because it assumes that @code{i * 2000} does not overflow.  The
19002 translation is not equivalent to the original when overflow occurs:
19003 e.g., in the typical case of 32-bit signed two's complement wraparound
19004 @code{int}, if @code{i} has type @code{int} and value @code{1073742},
19005 the original expression returns @minus{}2147483 but the optimized
19006 version returns the mathematically correct value 2147484.
19008 More subtly, loop induction optimizations often exploit the undefined
19009 behavior of signed overflow.  Consider the following contrived function
19010 @code{sumc}:
19012 @example
19014 sumc (int lo, int hi)
19016   int sum = 0;
19017   int i;
19018   for (i = lo; i <= hi; i++)
19019     sum ^= i * 53;
19020   return sum;
19022 @end example
19024 @noindent
19025 To avoid multiplying by 53 each time through the loop, an optimizing
19026 compiler might internally transform @code{sumc} to the equivalent of the
19027 following:
19029 @example
19031 transformed_sumc (int lo, int hi)
19033   int sum = 0;
19034   int hic = hi * 53;
19035   int ic;
19036   for (ic = lo * 53; ic <= hic; ic += 53)
19037     sum ^= ic;
19038   return sum;
19040 @end example
19042 @noindent
19043 This transformation is allowed by the C standard, but it is invalid for
19044 wraparound arithmetic when @code{INT_MAX / 53 < hi}, because then the
19045 overflow in computing expressions like @code{hi * 53} can cause the
19046 expression @code{i <= hi} to yield a different value from the
19047 transformed expression @code{ic <= hic}.
19049 For this reason, compilers that use loop induction and similar
19050 techniques often do not support reliable wraparound arithmetic when a
19051 loop induction variable like @code{ic} is involved.  Since loop
19052 induction variables are generated by the compiler, and are not visible
19053 in the source code, it is not always trivial to say whether the problem
19054 affects your code.
19056 Hardly any code actually depends on wraparound arithmetic in cases like
19057 these, so in practice these loop induction optimizations are almost
19058 always useful.  However, edge cases in this area can cause problems.
19059 For example:
19061 @example
19062 int j;
19063 for (j = 1; 0 < j; j *= 2)
19064   test (j);
19065 @end example
19067 @noindent
19068 Here, the loop attempts to iterate through all powers of 2 that
19069 @code{int} can represent, but the C standard allows a compiler to
19070 optimize away the comparison and generate an infinite loop,
19071 under the argument that behavior is undefined on overflow.  As of this
19072 writing this optimization is not done by any production version of
19073 @acronym{GCC} with @option{-O2}, but it might be performed by other
19074 compilers, or by more aggressive @acronym{GCC} optimization options,
19075 and the @acronym{GCC} developers have not decided whether it will
19076 continue to work with @acronym{GCC} and @option{-O2}.
19078 @node Signed Overflow Advice
19079 @subsection Practical Advice for Signed Overflow Issues
19080 @cindex integer overflow
19081 @cindex overflow, signed integer
19082 @cindex signed integer overflow
19083 @cindex wraparound arithmetic
19085 Ideally the safest approach is to avoid signed integer overflow
19086 entirely.  For example, instead of multiplying two signed integers, you
19087 can convert them to unsigned integers, multiply the unsigned values,
19088 then test whether the result is in signed range.
19090 Rewriting code in this way will be inconvenient, though, particularly if
19091 the signed values might be negative.  Also, it may hurt
19092 performance.  Using unsigned arithmetic to check for overflow is
19093 particularly painful to do portably and efficiently when dealing with an
19094 integer type like @code{uid_t} whose width and signedness vary from
19095 platform to platform.
19097 Furthermore, many C applications pervasively assume wraparound behavior
19098 and typically it is not easy to find and remove all these assumptions.
19099 Hence it is often useful to maintain nonstandard code that assumes
19100 wraparound on overflow, instead of rewriting the code.  The rest of this
19101 section attempts to give practical advice for this situation.
19103 If your code wants to detect signed integer overflow in @code{sum = a +
19104 b}, it is generally safe to use an expression like @code{(sum < a) != (b
19105 < 0)}.
19107 If your code uses a signed loop index, make sure that the index cannot
19108 overflow, along with all signed expressions derived from the index.
19109 Here is a contrived example of problematic code with two instances of
19110 overflow.
19112 @example
19113 for (i = INT_MAX - 10; i <= INT_MAX; i++)
19114   if (i + 1 < 0)
19115     @{
19116       report_overflow ();
19117       break;
19118     @}
19119 @end example
19121 @noindent
19122 Because of the two overflows, a compiler might optimize away or
19123 transform the two comparisons in a way that is incompatible with the
19124 wraparound assumption.
19126 If your code uses an expression like @code{(i * 2000) / 1000} and you
19127 actually want the multiplication to wrap around on overflow, use
19128 unsigned arithmetic
19129 to do it, e.g., @code{((int) (i * 2000u)) / 1000}.
19131 If your code assumes wraparound behavior and you want to insulate it
19132 against any @acronym{GCC} optimizations that would fail to support that
19133 behavior, you should use @acronym{GCC}'s @option{-fwrapv} option, which
19134 causes signed overflow to wrap around reliably (except for division and
19135 remainder, as discussed in the next section).
19137 If you need to port to platforms where signed integer overflow does not
19138 reliably wrap around (e.g., due to hardware overflow checking, or to
19139 highly aggressive optimizations), you should consider debugging with
19140 @acronym{GCC}'s @option{-ftrapv} option, which causes signed overflow to
19141 raise an exception.
19143 @node Signed Integer Division
19144 @subsection Signed Integer Division and Integer Overflow
19145 @cindex division, integer
19147 Overflow in signed
19148 integer division is not always harmless: for example, on CPUs of the
19149 i386 family, dividing @code{INT_MIN} by @code{-1} yields a SIGFPE signal
19150 which by default terminates the program.  Worse, taking the remainder
19151 of these two values typically yields the same signal on these CPUs,
19152 even though the C standard requires @code{INT_MIN % -1} to yield zero
19153 because the expression does not overflow.
19155 @node Preprocessor Arithmetic
19156 @section Preprocessor Arithmetic
19157 @cindex preprocessor arithmetic
19159 In C99, preprocessor arithmetic, used for @code{#if} expressions, must
19160 be evaluated as if all signed values are of type @code{intmax_t} and all
19161 unsigned values of type @code{uintmax_t}.  Many compilers are buggy in
19162 this area, though.  For example, as of 2007, Sun C mishandles @code{#if
19163 LLONG_MIN < 0} on a platform with 32-bit @code{long int} and 64-bit
19164 @code{long long int}.  Also, some older preprocessors mishandle
19165 constants ending in @code{LL}.  To work around these problems, you can
19166 compute the value of expressions like @code{LONG_MAX < LLONG_MAX} at
19167 @code{configure}-time rather than at @code{#if}-time.
19169 @node Null Pointers
19170 @section Properties of Null Pointers
19171 @cindex null pointers
19173 Most modern hosts reliably fail when you attempt to dereference a null
19174 pointer.
19176 On almost all modern hosts, null pointers use an all-bits-zero internal
19177 representation, so you can reliably use @code{memset} with 0 to set all
19178 the pointers in an array to null values.
19180 If @code{p} is a null pointer to an object type, the C expression
19181 @code{p + 0} always evaluates to @code{p} on modern hosts, even though
19182 the standard says that it has undefined behavior.
19184 @node Buffer Overruns
19185 @section Buffer Overruns and Subscript Errors
19186 @cindex buffer overruns
19188 Buffer overruns and subscript errors are the most common dangerous
19189 errors in C programs.  They result in undefined behavior because storing
19190 outside an array typically modifies storage that is used by some other
19191 object, and most modern systems lack runtime checks to catch these
19192 errors.  Programs should not rely on buffer overruns being caught.
19194 There is one exception to the usual rule that a portable program cannot
19195 address outside an array.  In C, it is valid to compute the address just
19196 past an object, e.g., @code{&a[N]} where @code{a} has @code{N} elements,
19197 so long as you do not dereference the resulting pointer.  But it is not
19198 valid to compute the address just before an object, e.g., @code{&a[-1]};
19199 nor is it valid to compute two past the end, e.g., @code{&a[N+1]}.  On
19200 most platforms @code{&a[-1] < &a[0] && &a[N] < &a[N+1]}, but this is not
19201 reliable in general, and it is usually easy enough to avoid the
19202 potential portability problem, e.g., by allocating an extra unused array
19203 element at the start or end.
19205 @uref{http://@/valgrind.org/, Valgrind} can catch many overruns.
19206 @acronym{GCC}
19207 users might also consider using the @option{-fmudflap} option to catch
19208 overruns.
19210 Buffer overruns are usually caused by off-by-one errors, but there are
19211 more subtle ways to get them.
19213 Using @code{int} values to index into an array or compute array sizes
19214 causes problems on typical 64-bit hosts where an array index might
19215 be @math{2^31} or larger.  Index values of type @code{size_t} avoid this
19216 problem, but cannot be negative.  Index values of type @code{ptrdiff_t}
19217 are signed, and are wide enough in practice.
19219 If you add or multiply two numbers to calculate an array size, e.g.,
19220 @code{malloc (x * sizeof y + z)}, havoc ensues if the addition or
19221 multiplication overflows.
19223 Many implementations of the @code{alloca} function silently misbehave
19224 and can generate buffer overflows if given sizes that are too large.
19225 The size limits are implementation dependent, but are at least 4000
19226 bytes on all platforms that we know about.
19228 The standard functions @code{asctime}, @code{asctime_r}, @code{ctime},
19229 @code{ctime_r}, and @code{gets} are prone to buffer overflows, and
19230 portable code should not use them unless the inputs are known to be
19231 within certain limits.  The time-related functions can overflow their
19232 buffers if given timestamps out of range (e.g., a year less than -999
19233 or greater than 9999).  Time-related buffer overflows cannot happen with
19234 recent-enough versions of the @acronym{GNU} C library, but are possible
19235 with other
19236 implementations.  The @code{gets} function is the worst, since it almost
19237 invariably overflows its buffer when presented with an input line larger
19238 than the buffer.
19240 @node Volatile Objects
19241 @section Volatile Objects
19242 @cindex volatile objects
19244 The keyword @code{volatile} is often misunderstood in portable code.
19245 Its use inhibits some memory-access optimizations, but programmers often
19246 wish that it had a different meaning than it actually does.
19248 @code{volatile} was designed for code that accesses special objects like
19249 memory-mapped device registers whose contents spontaneously change.
19250 Such code is inherently low-level, and it is difficult to specify
19251 portably what @code{volatile} means in these cases.  The C standard
19252 says, ``What constitutes an access to an object that has
19253 volatile-qualified type is implementation-defined,'' so in theory each
19254 implementation is supposed to fill in the gap by documenting what
19255 @code{volatile} means for that implementation.  In practice, though,
19256 this documentation is usually absent or incomplete.
19258 One area of confusion is the distinction between objects defined with
19259 volatile types, and volatile lvalues.  From the C standard's point of
19260 view, an object defined with a volatile type has externally visible
19261 behavior.  You can think of such objects as having little oscilloscope
19262 probes attached to them, so that the user can observe some properties of
19263 accesses to them, just as the user can observe data written to output
19264 files.  However, the standard does not make it clear whether users can
19265 observe accesses by volatile lvalues to ordinary objects.  For example:
19267 @example
19268 /* Declare and access a volatile object.
19269    Accesses to X are "visible" to users.  */
19270 static int volatile x;
19271 x = 1;
19273 /* Access two ordinary objects via a volatile lvalue.
19274    It's not clear whether accesses to *P are "visible".  */
19275 int y;
19276 int *z = malloc (sizeof (int));
19277 int volatile *p;
19278 p = &y;
19279 *p = 1;
19280 p = z;
19281 *p = 1;
19282 @end example
19284 Programmers often wish that @code{volatile} meant ``Perform the memory
19285 access here and now, without merging several memory accesses, without
19286 changing the memory word size, and without reordering.''  But the C
19287 standard does not require this.  For objects defined with a volatile
19288 type, accesses must be done before the next sequence point; but
19289 otherwise merging, reordering, and word-size change is allowed.  Worse,
19290 it is not clear from the standard whether volatile lvalues provide more
19291 guarantees in general than nonvolatile lvalues, if the underlying
19292 objects are ordinary.
19294 Even when accessing objects defined with a volatile type,
19295 the C standard allows only
19296 extremely limited signal handlers: the behavior is undefined if a signal
19297 handler reads any nonlocal object, or writes to any nonlocal object
19298 whose type is not @code{sig_atomic_t volatile}, or calls any standard
19299 library function other than @code{abort}, @code{signal}, and (if C99)
19300 @code{_Exit}.  Hence C compilers need not worry about a signal handler
19301 disturbing ordinary computation, unless the computation accesses a
19302 @code{sig_atomic_t volatile} lvalue that is not a local variable.
19303 (There is an obscure exception for accesses via a pointer to a volatile
19304 character, since it may point into part of a @code{sig_atomic_t
19305 volatile} object.)  Posix
19306 adds to the list of library functions callable from a portable signal
19307 handler, but otherwise is like the C standard in this area.
19309 Some C implementations allow memory-access optimizations within each
19310 translation unit, such that actual behavior agrees with the behavior
19311 required by the standard only when calling a function in some other
19312 translation unit, and a signal handler acts like it was called from a
19313 different translation unit.  The C standard hints that in these
19314 implementations, objects referred to by signal handlers ``would require
19315 explicit specification of @code{volatile} storage, as well as other
19316 implementation-defined restrictions.''  But unfortunately even for this
19317 special case these other restrictions are often not documented well.
19318 @xref{Volatiles, , When is a Volatile Object Accessed?, gcc, Using the
19319 @acronym{GNU} Compiler Collection (@acronym{GCC})}, for some
19320 restrictions imposed by @acronym{GCC}.  @xref{Defining Handlers, ,
19321 Defining Signal Handlers, libc, The @acronym{GNU} C Library}, for some
19322 restrictions imposed by the @acronym{GNU} C library.  Restrictions
19323 differ on other platforms.
19325 If possible, it is best to use a signal handler that fits within the
19326 limits imposed by the C and Posix standards.
19328 If this is not practical, you can try the following rules of thumb.  A
19329 signal handler should access only volatile lvalues, preferably lvalues
19330 that refer to objects defined with a volatile type, and should not
19331 assume that the accessed objects have an internally consistent state
19332 if they are larger than a machine word.  Furthermore, installers
19333 should employ compilers and compiler options that are commonly used
19334 for building operating system kernels, because kernels often need more
19335 from @code{volatile} than the C Standard requires, and installers who
19336 compile an application in a similar environment can sometimes benefit
19337 from the extra constraints imposed by kernels on compilers.
19338 Admittedly we are handwaving somewhat here, as there are few
19339 guarantees in this area; the rules of thumb may help to fix some bugs
19340 but there is a good chance that they will not fix them all.
19342 For @code{volatile}, C++ has the same problems that C does.
19343 Multithreaded applications have even more problems with @code{volatile},
19344 but they are beyond the scope of this section.
19346 The bottom line is that using @code{volatile} typically hurts
19347 performance but should not hurt correctness.  In some cases its use
19348 does help correctness, but these cases are often so poorly understood
19349 that all too often adding @code{volatile} to a data structure merely
19350 alleviates some symptoms of a bug while not fixing the bug in general.
19352 @node Floating Point Portability
19353 @section Floating Point Portability
19354 @cindex floating point
19356 Almost all modern systems use IEEE-754 floating point, and it is safe to
19357 assume IEEE-754 in most portable code these days.  For more information,
19358 please see David Goldberg's classic paper
19359 @uref{http://@/www.validlab.com/@/goldberg/@/paper.pdf, What Every Computer
19360 Scientist Should Know About Floating-Point Arithmetic}.
19362 @node Exiting Portably
19363 @section Exiting Portably
19364 @cindex exiting portably
19366 A C or C++ program can exit with status @var{N} by returning
19367 @var{N} from the @code{main} function.  Portable programs are supposed
19368 to exit either with status 0 or @code{EXIT_SUCCESS} to succeed, or with
19369 status @code{EXIT_FAILURE} to fail, but in practice it is portable to
19370 fail by exiting with status 1, and test programs that assume Posix can
19371 fail by exiting with status values from 1 through 255.  Programs on
19372 SunOS 2.0 (1985) through 3.5.2 (1988) incorrectly exited with zero
19373 status when @code{main} returned nonzero, but ancient systems like these
19374 are no longer of practical concern.
19376 A program can also exit with status @var{N} by passing @var{N} to the
19377 @code{exit} function, and a program can fail by calling the @code{abort}
19378 function.  If a program is specialized to just some platforms, it can fail
19379 by calling functions specific to those platforms, e.g., @code{_exit}
19380 (Posix) and @code{_Exit} (C99).  However, like other functions, an exit
19381 function should be declared, typically by including a header.  For
19382 example, if a C program calls @code{exit}, it should include @file{stdlib.h}
19383 either directly or via the default includes (@pxref{Default Includes}).
19385 A program can fail due to undefined behavior such as dereferencing a null
19386 pointer, but this is not recommended as undefined behavior allows an
19387 implementation to do whatever it pleases and this includes exiting
19388 successfully.
19391 @c ================================================== Manual Configuration
19393 @node Manual Configuration
19394 @chapter Manual Configuration
19396 A few kinds of features can't be guessed automatically by running test
19397 programs.  For example, the details of the object-file format, or
19398 special options that need to be passed to the compiler or linker.  You
19399 can check for such features using ad-hoc means, such as having
19400 @command{configure} check the output of the @code{uname} program, or
19401 looking for libraries that are unique to particular systems.  However,
19402 Autoconf provides a uniform method for handling unguessable features.
19404 @menu
19405 * Specifying Target Triplets::  Specifying target triplets
19406 * Canonicalizing::              Getting the canonical system type
19407 * Using System Type::           What to do with the system type
19408 @end menu
19410 @node Specifying Target Triplets
19411 @section Specifying target triplets
19412 @cindex System type
19413 @cindex Target triplet
19414 @c This node used to be named Specifying Names.  The @anchor allows old
19415 @c links to still work.
19416 @anchor{Specifying Names}
19418 Autoconf-generated
19419 @command{configure} scripts can make decisions based on a canonical name
19420 for the system type, or @dfn{target triplet}, which has the form:
19421 @samp{@var{cpu}-@var{vendor}-@var{os}}, where @var{os} can be
19422 @samp{@var{system}} or @samp{@var{kernel}-@var{system}}
19424 @command{configure} can usually guess the canonical name for the type of
19425 system it's running on.  To do so it runs a script called
19426 @command{config.guess}, which infers the name using the @code{uname}
19427 command or symbols predefined by the C preprocessor.
19429 Alternately, the user can specify the system type with command line
19430 arguments to @command{configure} (@pxref{System Type}.  Doing so is
19431 necessary when
19432 cross-compiling.  In the most complex case of cross-compiling, three
19433 system types are involved.  The options to specify them are:
19435 @table @option
19436 @item --build=@var{build-type}
19437 the type of system on which the package is being configured and
19438 compiled.  It defaults to the result of running @command{config.guess}.
19440 @item --host=@var{host-type}
19441 the type of system on which the package runs.  By default it is the
19442 same as the build machine.  Specifying it enables the cross-compilation
19443 mode.
19445 @item --target=@var{target-type}
19446 the type of system for which any compiler tools in the package
19447 produce code (rarely needed).  By default, it is the same as host.
19448 @end table
19450 If you mean to override the result of @command{config.guess}, use
19451 @option{--build}, not @option{--host}, since the latter enables
19452 cross-compilation.  For historical reasons,
19453 whenever you specify @option{--host},
19454 be sure to specify @option{--build} too; this will be fixed in the
19455 future.  So, to enter cross-compilation mode, use a command like this
19457 @example
19458 ./configure --build=i686-pc-linux-gnu --host=m68k-coff
19459 @end example
19461 @noindent
19462 Note that if you do not specify @option{--host}, @command{configure}
19463 fails if it can't run the code generated by the specified compiler.  For
19464 example, configuring as follows fails:
19466 @example
19467 ./configure CC=m68k-coff-gcc
19468 @end example
19470 When cross-compiling, @command{configure} will warn about any tools
19471 (compilers, linkers, assemblers) whose name is not prefixed with the
19472 host type.  This is an aid to users performing cross-compilation.
19473 Continuing the example above, if a cross-compiler named @command{cc} is
19474 used with a native @command{pkg-config}, then libraries found by
19475 @command{pkg-config} will likely cause subtle build failures; but using
19476 the names @command{m68k-coff-cc} and @command{m68k-coff-pkg-config}
19477 avoids any confusion.  Avoiding the warning is as simple as creating the
19478 correct symlinks naming the cross tools.
19480 @cindex @command{config.sub}
19481 @command{configure} recognizes short aliases for many system types; for
19482 example, @samp{decstation} can be used instead of
19483 @samp{mips-dec-ultrix4.2}.  @command{configure} runs a script called
19484 @command{config.sub} to canonicalize system type aliases.
19486 This section deliberately omits the description of the obsolete
19487 interface; see @ref{Hosts and Cross-Compilation}.
19490 @node Canonicalizing
19491 @section Getting the Canonical System Type
19492 @cindex System type
19493 @cindex Canonical system type
19495 The following macros make the system type available to @command{configure}
19496 scripts.
19498 @ovindex build_alias
19499 @ovindex host_alias
19500 @ovindex target_alias
19502 The variables @samp{build_alias}, @samp{host_alias}, and
19503 @samp{target_alias} are always exactly the arguments of @option{--build},
19504 @option{--host}, and @option{--target}; in particular, they are left empty
19505 if the user did not use them, even if the corresponding
19506 @code{AC_CANONICAL} macro was run.  Any configure script may use these
19507 variables anywhere.  These are the variables that should be used when in
19508 interaction with the user.
19510 If you need to recognize some special environments based on their system
19511 type, run the following macros to get canonical system names.  These
19512 variables are not set before the macro call.
19514 If you use these macros, you must distribute @command{config.guess} and
19515 @command{config.sub} along with your source code.  @xref{Output}, for
19516 information about the @code{AC_CONFIG_AUX_DIR} macro which you can use
19517 to control in which directory @command{configure} looks for those scripts.
19520 @defmac AC_CANONICAL_BUILD
19521 @acindex{CANONICAL_BUILD}
19522 @ovindex build
19523 @ovindex build_cpu
19524 @ovindex build_vendor
19525 @ovindex build_os
19526 Compute the canonical build-system type variable, @code{build}, and its
19527 three individual parts @code{build_cpu}, @code{build_vendor}, and
19528 @code{build_os}.
19530 If @option{--build} was specified, then @code{build} is the
19531 canonicalization of @code{build_alias} by @command{config.sub},
19532 otherwise it is determined by the shell script @command{config.guess}.
19533 @end defmac
19535 @defmac AC_CANONICAL_HOST
19536 @acindex{CANONICAL_HOST}
19537 @ovindex host
19538 @ovindex host_cpu
19539 @ovindex host_vendor
19540 @ovindex host_os
19541 Compute the canonical host-system type variable, @code{host}, and its
19542 three individual parts @code{host_cpu}, @code{host_vendor}, and
19543 @code{host_os}.
19545 If @option{--host} was specified, then @code{host} is the
19546 canonicalization of @code{host_alias} by @command{config.sub},
19547 otherwise it defaults to @code{build}.
19548 @end defmac
19550 @defmac AC_CANONICAL_TARGET
19551 @acindex{CANONICAL_TARGET}
19552 @ovindex target
19553 @ovindex target_cpu
19554 @ovindex target_vendor
19555 @ovindex target_os
19556 Compute the canonical target-system type variable, @code{target}, and its
19557 three individual parts @code{target_cpu}, @code{target_vendor}, and
19558 @code{target_os}.
19560 If @option{--target} was specified, then @code{target} is the
19561 canonicalization of @code{target_alias} by @command{config.sub},
19562 otherwise it defaults to @code{host}.
19563 @end defmac
19565 Note that there can be artifacts due to the backward compatibility
19566 code.  See @xref{Hosts and Cross-Compilation}, for more.
19568 @node Using System Type
19569 @section Using the System Type
19571 In @file{configure.ac} the system type is generally used by one or more
19572 @code{case} statements to select system-specifics.  Shell wildcards can
19573 be used to match a group of system types.
19575 For example, an extra assembler code object file could be chosen, giving
19576 access to a CPU cycle counter register.  @code{$(CYCLE_OBJ)} in the
19577 following would be used in a makefile to add the object to a
19578 program or library.
19580 @example
19581 AS_CASE([$host],
19582   [alpha*-*-*], [CYCLE_OBJ=rpcc.o],
19583   [i?86-*-*],   [CYCLE_OBJ=rdtsc.o],
19584   [CYCLE_OBJ=""]
19586 AC_SUBST([CYCLE_OBJ])
19587 @end example
19589 @code{AC_CONFIG_LINKS} (@pxref{Configuration Links}) is another good way
19590 to select variant source files, for example optimized code for some
19591 CPUs.  The configured CPU type doesn't always indicate exact CPU types,
19592 so some runtime capability checks may be necessary too.
19594 @example
19595 case $host in
19596   alpha*-*-*)   AC_CONFIG_LINKS([dither.c:alpha/dither.c]) ;;
19597   powerpc*-*-*) AC_CONFIG_LINKS([dither.c:powerpc/dither.c]) ;;
19598   *-*-*)        AC_CONFIG_LINKS([dither.c:generic/dither.c]) ;;
19599 esac
19600 @end example
19602 The host system type can also be used to find cross-compilation tools
19603 with @code{AC_CHECK_TOOL} (@pxref{Generic Programs}).
19605 The above examples all show @samp{$host}, since this is where the code
19606 is going to run.  Only rarely is it necessary to test @samp{$build}
19607 (which is where the build is being done).
19609 Whenever you're tempted to use @samp{$host} it's worth considering
19610 whether some sort of probe would be better.  New system types come along
19611 periodically or previously missing features are added.  Well-written
19612 probes can adapt themselves to such things, but hard-coded lists of
19613 names can't.  Here are some guidelines,
19615 @itemize @bullet
19616 @item
19617 Availability of libraries and library functions should always be checked
19618 by probing.
19619 @item
19620 Variant behavior of system calls is best identified with runtime tests
19621 if possible, but bug workarounds or obscure difficulties might have to
19622 be driven from @samp{$host}.
19623 @item
19624 Assembler code is inevitably highly CPU-specific and is best selected
19625 according to @samp{$host_cpu}.
19626 @item
19627 Assembler variations like underscore prefix on globals or ELF versus
19628 COFF type directives are however best determined by probing, perhaps
19629 even examining the compiler output.
19630 @end itemize
19632 @samp{$target} is for use by a package creating a compiler or similar.
19633 For ordinary packages it's meaningless and should not be used.  It
19634 indicates what the created compiler should generate code for, if it can
19635 cross-compile.  @samp{$target} generally selects various hard-coded CPU
19636 and system conventions, since usually the compiler or tools under
19637 construction themselves determine how the target works.
19640 @c ===================================================== Site Configuration.
19642 @node Site Configuration
19643 @chapter Site Configuration
19645 @command{configure} scripts support several kinds of local configuration
19646 decisions.  There are ways for users to specify where external software
19647 packages are, include or exclude optional features, install programs
19648 under modified names, and set default values for @command{configure}
19649 options.
19651 @menu
19652 * Help Formatting::             Customizing @samp{configure --help}
19653 * External Software::           Working with other optional software
19654 * Package Options::             Selecting optional features
19655 * Pretty Help Strings::         Formatting help string
19656 * Option Checking::             Controlling checking of @command{configure} options
19657 * Site Details::                Configuring site details
19658 * Transforming Names::          Changing program names when installing
19659 * Site Defaults::               Giving @command{configure} local defaults
19660 @end menu
19662 @node Help Formatting
19663 @section Controlling Help Output
19665 Users consult @samp{configure --help} to learn of configuration
19666 decisions specific to your package.  By default, @command{configure}
19667 breaks this output into sections for each type of option; within each
19668 section, help strings appear in the order @file{configure.ac} defines
19669 them:
19671 @example
19672 Optional Features:
19673   @dots{}
19674   --enable-bar            include bar
19676 Optional Packages:
19677   @dots{}
19678   --with-foo              use foo
19679 @end example
19681 @defmac AC_PRESERVE_HELP_ORDER
19682 @acindex{PRESERVE_HELP_ORDER}
19684 Request an alternate @option{--help} format, in which options of all
19685 types appear together, in the order defined.  Call this macro before any
19686 @code{AC_ARG_ENABLE} or @code{AC_ARG_WITH}.
19688 @example
19689 Optional Features and Packages:
19690   @dots{}
19691   --enable-bar            include bar
19692   --with-foo              use foo
19693 @end example
19695 @end defmac
19697 @node External Software
19698 @section Working With External Software
19699 @cindex External software
19701 Some packages require, or can optionally use, other software packages
19702 that are already installed.  The user can give @command{configure}
19703 command line options to specify which such external software to use.
19704 The options have one of these forms:
19706 @c FIXME: Can't use @ovar here, Texinfo 4.0 goes lunatic and emits something
19707 @c awful.
19708 @example
19709 --with-@var{package}[=@var{arg}]
19710 --without-@var{package}
19711 @end example
19713 For example, @option{--with-gnu-ld} means work with the @acronym{GNU} linker
19714 instead of some other linker.  @option{--with-x} means work with The X
19715 Window System.
19717 The user can give an argument by following the package name with
19718 @samp{=} and the argument.  Giving an argument of @samp{no} is for
19719 packages that are used by default; it says to @emph{not} use the
19720 package.  An argument that is neither @samp{yes} nor @samp{no} could
19721 include a name or number of a version of the other package, to specify
19722 more precisely which other package this program is supposed to work
19723 with.  If no argument is given, it defaults to @samp{yes}.
19724 @option{--without-@var{package}} is equivalent to
19725 @option{--with-@var{package}=no}.
19727 Normally @command{configure} scripts complain about
19728 @option{--with-@var{package}} options that they do not support.
19729 @xref{Option Checking}, for details, and for how to override the
19730 defaults.
19732 For each external software package that may be used, @file{configure.ac}
19733 should call @code{AC_ARG_WITH} to detect whether the @command{configure}
19734 user asked to use it.  Whether each package is used or not by default,
19735 and which arguments are valid, is up to you.
19737 @anchor{AC_ARG_WITH}
19738 @defmac AC_ARG_WITH (@var{package}, @var{help-string}, @
19739   @ovar{action-if-given}, @ovar{action-if-not-given})
19740 @acindex{ARG_WITH}
19741 If the user gave @command{configure} the option @option{--with-@var{package}}
19742 or @option{--without-@var{package}}, run shell commands
19743 @var{action-if-given}.  If neither option was given, run shell commands
19744 @var{action-if-not-given}.  The name @var{package} indicates another
19745 software package that this program should work with.  It should consist
19746 only of alphanumeric characters, dashes, and dots.
19748 The option's argument is available to the shell commands
19749 @var{action-if-given} in the shell variable @code{withval}, which is
19750 actually just the value of the shell variable named
19751 @code{with_@var{package}}, with any non-alphanumeric characters in
19752 @var{package} changed into @samp{_}.  You may use that variable instead,
19753 if you wish.
19755 The argument @var{help-string} is a description of the option that
19756 looks like this:
19757 @example
19758   --with-readline         support fancy command line editing
19759 @end example
19761 @noindent
19762 @var{help-string} may be more than one line long, if more detail is
19763 needed.  Just make sure the columns line up in @samp{configure
19764 --help}.  Avoid tabs in the help string.  The easiest way to provide the
19765 proper leading whitespace is to format your @var{help-string} with the macro
19766 @code{AS_HELP_STRING} (@pxref{Pretty Help Strings}).
19768 The following example shows how to use the @code{AC_ARG_WITH} macro in
19769 a common situation.  You want to let the user decide whether to enable
19770 support for an external library (e.g., the readline library); if the user
19771 specified neither @option{--with-readline} nor @option{--without-readline},
19772 you want to enable support for readline only if the library is available
19773 on the system.
19775 @c FIXME: Remove AS_IF when the problem of AC_REQUIRE within `if' is solved.
19776 @example
19777 AC_ARG_WITH([readline],
19778   [AS_HELP_STRING([--with-readline],
19779     [support fancy command line editing @@<:@@default=check@@:>@@])],
19780   [],
19781   [with_readline=check])
19783 LIBREADLINE=
19784 AS_IF([test "x$with_readline" != xno],
19785   [AC_CHECK_LIB([readline], [main],
19786     [AC_SUBST([LIBREADLINE], ["-lreadline -lncurses"])
19787      AC_DEFINE([HAVE_LIBREADLINE], [1],
19788                [Define if you have libreadline])
19789     ],
19790     [if test "x$with_readline" != xcheck; then
19791        AC_MSG_FAILURE(
19792          [--with-readline was given, but test for readline failed])
19793      fi
19794     ], -lncurses)])
19795 @end example
19797 The next example shows how to use @code{AC_ARG_WITH} to give the user the
19798 possibility to enable support for the readline library, in case it is still
19799 experimental and not well tested, and is therefore disabled by default.
19801 @c FIXME: Remove AS_IF when the problem of AC_REQUIRE within `if' is solved.
19802 @example
19803 AC_ARG_WITH([readline],
19804   [AS_HELP_STRING([--with-readline],
19805     [enable experimental support for readline])],
19806   [],
19807   [with_readline=no])
19809 LIBREADLINE=
19810 AS_IF([test "x$with_readline" != xno],
19811   [AC_CHECK_LIB([readline], [main],
19812     [AC_SUBST([LIBREADLINE], ["-lreadline -lncurses"])
19813      AC_DEFINE([HAVE_LIBREADLINE], [1],
19814                [Define if you have libreadline])
19815     ],
19816     [AC_MSG_FAILURE(
19817        [--with-readline was given, but test for readline failed])],
19818     [-lncurses])])
19819 @end example
19821 The last example shows how to use @code{AC_ARG_WITH} to give the user the
19822 possibility to disable support for the readline library, given that it is
19823 an important feature and that it should be enabled by default.
19825 @c FIXME: Remove AS_IF when the problem of AC_REQUIRE within `if' is solved.
19826 @example
19827 AC_ARG_WITH([readline],
19828   [AS_HELP_STRING([--without-readline],
19829     [disable support for readline])],
19830   [],
19831   [with_readline=yes])
19833 LIBREADLINE=
19834 AS_IF([test "x$with_readline" != xno],
19835   [AC_CHECK_LIB([readline], [main],
19836     [AC_SUBST([LIBREADLINE], ["-lreadline -lncurses"])
19837      AC_DEFINE([HAVE_LIBREADLINE], [1],
19838                [Define if you have libreadline])
19839     ],
19840     [AC_MSG_FAILURE(
19841        [readline test failed (--without-readline to disable)])],
19842     [-lncurses])])
19843 @end example
19845 These three examples can be easily adapted to the case where
19846 @code{AC_ARG_ENABLE} should be preferred to @code{AC_ARG_WITH} (see
19847 @ref{Package Options}).
19848 @end defmac
19850 @node Package Options
19851 @section Choosing Package Options
19852 @cindex Package options
19853 @cindex Options, package
19855 If a software package has optional compile-time features, the user can
19856 give @command{configure} command line options to specify whether to
19857 compile them.  The options have one of these forms:
19859 @c FIXME: Can't use @ovar here, Texinfo 4.0 goes lunatic and emits something
19860 @c awful.
19861 @example
19862 --enable-@var{feature}[=@var{arg}]
19863 --disable-@var{feature}
19864 @end example
19866 These options allow users to choose which optional features to build and
19867 install.  @option{--enable-@var{feature}} options should never make a
19868 feature behave differently or cause one feature to replace another.
19869 They should only cause parts of the program to be built rather than left
19870 out.
19872 The user can give an argument by following the feature name with
19873 @samp{=} and the argument.  Giving an argument of @samp{no} requests
19874 that the feature @emph{not} be made available.  A feature with an
19875 argument looks like @option{--enable-debug=stabs}.  If no argument is
19876 given, it defaults to @samp{yes}.  @option{--disable-@var{feature}} is
19877 equivalent to @option{--enable-@var{feature}=no}.
19879 Normally @command{configure} scripts complain about
19880 @option{--enable-@var{package}} options that they do not support.
19881 @xref{Option Checking}, for details, and for how to override the
19882 defaults.
19884 For each optional feature, @file{configure.ac} should call
19885 @code{AC_ARG_ENABLE} to detect whether the @command{configure} user asked
19886 to include it.  Whether each feature is included or not by default, and
19887 which arguments are valid, is up to you.
19889 @anchor{AC_ARG_ENABLE}
19890 @defmac AC_ARG_ENABLE (@var{feature}, @var{help-string}, @
19891   @ovar{action-if-given}, @ovar{action-if-not-given})
19892 @acindex{ARG_ENABLE}
19893 If the user gave @command{configure} the option
19894 @option{--enable-@var{feature}} or @option{--disable-@var{feature}}, run
19895 shell commands @var{action-if-given}.  If neither option was given, run
19896 shell commands @var{action-if-not-given}.  The name @var{feature}
19897 indicates an optional user-level facility.  It should consist only of
19898 alphanumeric characters, dashes, and dots.
19900 The option's argument is available to the shell commands
19901 @var{action-if-given} in the shell variable @code{enableval}, which is
19902 actually just the value of the shell variable named
19903 @code{enable_@var{feature}}, with any non-alphanumeric characters in
19904 @var{feature} changed into @samp{_}.  You may use that variable instead,
19905 if you wish.  The @var{help-string} argument is like that of
19906 @code{AC_ARG_WITH} (@pxref{External Software}).
19908 You should format your @var{help-string} with the macro
19909 @code{AS_HELP_STRING} (@pxref{Pretty Help Strings}).
19911 See the examples suggested with the definition of @code{AC_ARG_WITH}
19912 (@pxref{External Software}) to get an idea of possible applications of
19913 @code{AC_ARG_ENABLE}.
19914 @end defmac
19916 @node Pretty Help Strings
19917 @section Making Your Help Strings Look Pretty
19918 @cindex Help strings
19920 Properly formatting the @samp{help strings} which are used in
19921 @code{AC_ARG_WITH} (@pxref{External Software}) and @code{AC_ARG_ENABLE}
19922 (@pxref{Package Options}) can be challenging.  Specifically, you want
19923 your own @samp{help strings} to line up in the appropriate columns of
19924 @samp{configure --help} just like the standard Autoconf @samp{help
19925 strings} do.  This is the purpose of the @code{AS_HELP_STRING} macro.
19927 @anchor{AS_HELP_STRING}
19928 @defmac AS_HELP_STRING (@var{left-hand-side}, @var{right-hand-side} @
19929   @dvar{indent-column, 26}, @dvar{wrap-column, 79})
19930 @asindex{HELP_STRING}
19932 Expands into a help string that looks pretty when the user executes
19933 @samp{configure --help}.  It is typically used in @code{AC_ARG_WITH}
19934 (@pxref{External Software}) or @code{AC_ARG_ENABLE} (@pxref{Package
19935 Options}).  The following example makes this clearer.
19937 @example
19938 AC_ARG_WITH([foo],
19939   [AS_HELP_STRING([--with-foo],
19940      [use foo (default is no)])],
19941   [use_foo=$withval],
19942   [use_foo=no])
19943 @end example
19945 Then the last few lines of @samp{configure --help} appear like
19946 this:
19948 @example
19949 --enable and --with options recognized:
19950   --with-foo              use foo (default is no)
19951 @end example
19953 Macro expansion is performed on the first argument.  However, the second
19954 argument of @code{AS_HELP_STRING} is treated as a whitespace separated
19955 list of text to be reformatted, and is not subject to macro expansion.
19956 Since it is not expanded, it should not be double quoted.
19957 @xref{Autoconf Language}, for a more detailed explanation.
19959 The @code{AS_HELP_STRING} macro is particularly helpful when the
19960 @var{left-hand-side} and/or @var{right-hand-side} are composed of macro
19961 arguments, as shown in the following example.  Be aware that
19962 @var{left-hand-side} may not expand to unbalanced quotes,
19963 although quadrigraphs can be used.
19965 @example
19966 AC_DEFUN([MY_ARG_WITH],
19967   [AC_ARG_WITH(m4_translit([[$1]], [_], [-]),
19968      [AS_HELP_STRING([--with-m4_translit([$1], [_], [-])],
19969                      [use $1 (default is $2)])],
19970      [use_[]$1=$withval],
19971      [use_[]$1=$2])])
19972 MY_ARG_WITH([a_b], [no])
19973 @end example
19974 @noindent
19975 Here, the last few lines of @samp{configure --help} will include:
19977 @example
19978 --enable and --with options recognized:
19979   --with-a-b              use a_b (default is no)
19980 @end example
19982 The parameters @var{indent-column} and @var{wrap-column} were introduced
19983 in Autoconf 2.62.  Generally, they should not be specified; they exist
19984 for fine-tuning of the wrapping.
19985 @example
19986 AS_HELP_STRING([--option], [description of option])
19987 @result{}  --option                description of option
19988 AS_HELP_STRING([--option], [description of option], [15], [30])
19989 @result{}  --option     description of
19990 @result{}               option
19991 @end example
19992 @end defmac
19995 @node Option Checking
19996 @section Controlling Checking of @command{configure} Options
19997 @cindex Options, Package
19999 The @command{configure} script checks its command-line options against a
20000 list of known options, like @option{--help} or @option{--config-cache}.
20001 An unknown option ordinarily indicates a mistake by the user and
20002 @command{configure} halts with an error.  However, by default unknown
20003 @option{--with-@var{package}} and @option{--enable-@var{feature}}
20004 options elicit only a warning, to support configuring entire source
20005 trees.
20007 Source trees often contain multiple packages with a top-level
20008 @command{configure} script that uses the @code{AC_CONFIG_SUBDIRS} macro
20009 (@pxref{Subdirectories}).  Because the packages generally support
20010 different @option{--with-@var{package}} and
20011 @option{--enable-@var{feature}} options, the @acronym{GNU} Coding
20012 Standards say they must accept unrecognized options without halting.
20013 Even a warning message is undesirable here, so @code{AC_CONFIG_SUBDIRS}
20014 automatically disables the warnings.
20016 This default behavior may be modified in two ways.  First, the installer
20017 can invoke @code{configure --disable-option-checking} to disable
20018 these warnings, or invoke @code{configure --enable-option-checking=fatal}
20019 options to turn them into fatal errors, respectively.  Second, the
20020 maintainer can use @code{AC_DISABLE_OPTION_CHECKING}.
20022 @defmac AC_DISABLE_OPTION_CHECKING
20023 @acindex{DISABLE_OPTION_CHECKING}
20025 By default, disable warnings related to any unrecognized
20026 @option{--with-@var{package}} or @option{--enable-@var{feature}}
20027 options.  This is implied by @code{AC_CONFIG_SUBDIRS}.
20029 The installer can override this behavior by passing
20030 @option{--enable-option-checking} (enable warnings) or
20031 @option{--enable-option-checking=fatal} (enable errors) to
20032 @command{configure}.
20033 @end defmac
20036 @node Site Details
20037 @section Configuring Site Details
20038 @cindex Site details
20040 Some software packages require complex site-specific information.  Some
20041 examples are host names to use for certain services, company names, and
20042 email addresses to contact.  Since some configuration scripts generated
20043 by Metaconfig ask for such information interactively, people sometimes
20044 wonder how to get that information in Autoconf-generated configuration
20045 scripts, which aren't interactive.
20047 Such site configuration information should be put in a file that is
20048 edited @emph{only by users}, not by programs.  The location of the file
20049 can either be based on the @code{prefix} variable, or be a standard
20050 location such as the user's home directory.  It could even be specified
20051 by an environment variable.  The programs should examine that file at
20052 runtime, rather than at compile time.  Runtime configuration is more
20053 convenient for users and makes the configuration process simpler than
20054 getting the information while configuring.  @xref{Directory Variables, ,
20055 Variables for Installation Directories, standards, @acronym{GNU} Coding
20056 Standards}, for more information on where to put data files.
20058 @node Transforming Names
20059 @section Transforming Program Names When Installing
20060 @cindex Transforming program names
20061 @cindex Program names, transforming
20063 Autoconf supports changing the names of programs when installing them.
20064 In order to use these transformations, @file{configure.ac} must call the
20065 macro @code{AC_ARG_PROGRAM}.
20067 @defmac AC_ARG_PROGRAM
20068 @acindex{ARG_PROGRAM}
20069 @ovindex program_transform_name
20070 Place in output variable @code{program_transform_name} a sequence of
20071 @code{sed} commands for changing the names of installed programs.
20073 If any of the options described below are given to @command{configure},
20074 program names are transformed accordingly.  Otherwise, if
20075 @code{AC_CANONICAL_TARGET} has been called and a @option{--target} value
20076 is given, the target type followed by a dash is used as a prefix.
20077 Otherwise, no program name transformation is done.
20078 @end defmac
20080 @menu
20081 * Transformation Options::      @command{configure} options to transform names
20082 * Transformation Examples::     Sample uses of transforming names
20083 * Transformation Rules::        Makefile uses of transforming names
20084 @end menu
20086 @node Transformation Options
20087 @subsection Transformation Options
20089 You can specify name transformations by giving @command{configure} these
20090 command line options:
20092 @table @option
20093 @item --program-prefix=@var{prefix}
20094 prepend @var{prefix} to the names;
20096 @item --program-suffix=@var{suffix}
20097 append @var{suffix} to the names;
20099 @item --program-transform-name=@var{expression}
20100 perform @code{sed} substitution @var{expression} on the names.
20101 @end table
20103 @node Transformation Examples
20104 @subsection Transformation Examples
20106 These transformations are useful with programs that can be part of a
20107 cross-compilation development environment.  For example, a
20108 cross-assembler running on a Sun 4 configured with
20109 @option{--target=i960-vxworks} is normally installed as
20110 @file{i960-vxworks-as}, rather than @file{as}, which could be confused
20111 with a native Sun 4 assembler.
20113 You can force a program name to begin with @file{g}, if you don't want
20114 @acronym{GNU} programs installed on your system to shadow other programs with
20115 the same name.  For example, if you configure @acronym{GNU} @code{diff} with
20116 @option{--program-prefix=g}, then when you run @samp{make install} it is
20117 installed as @file{/usr/local/bin/gdiff}.
20119 As a more sophisticated example, you could use
20121 @example
20122 --program-transform-name='s/^/g/; s/^gg/g/; s/^gless/less/'
20123 @end example
20124 @noindent
20126 to prepend @samp{g} to most of the program names in a source tree,
20127 excepting those like @code{gdb} that already have one and those like
20128 @code{less} and @code{lesskey} that aren't @acronym{GNU} programs.  (That is
20129 assuming that you have a source tree containing those programs that is
20130 set up to use this feature.)
20132 One way to install multiple versions of some programs simultaneously is
20133 to append a version number to the name of one or both.  For example, if
20134 you want to keep Autoconf version 1 around for awhile, you can configure
20135 Autoconf version 2 using @option{--program-suffix=2} to install the
20136 programs as @file{/usr/local/bin/autoconf2},
20137 @file{/usr/local/bin/autoheader2}, etc.  Nevertheless, pay attention
20138 that only the binaries are renamed, therefore you'd have problems with
20139 the library files which might overlap.
20141 @node Transformation Rules
20142 @subsection Transformation Rules
20144 Here is how to use the variable @code{program_transform_name} in a
20145 @file{Makefile.in}:
20147 @example
20148 PROGRAMS = cp ls rm
20149 transform = @@program_transform_name@@
20150 install:
20151         for p in $(PROGRAMS); do \
20152           $(INSTALL_PROGRAM) $$p $(DESTDIR)$(bindir)/`echo $$p | \
20153                                               sed '$(transform)'`; \
20154         done
20156 uninstall:
20157         for p in $(PROGRAMS); do \
20158           rm -f $(DESTDIR)$(bindir)/`echo $$p | sed '$(transform)'`; \
20159         done
20160 @end example
20162 It is guaranteed that @code{program_transform_name} is never empty, and
20163 that there are no useless separators.  Therefore you may safely embed
20164 @code{program_transform_name} within a sed program using @samp{;}:
20166 @example
20167 transform = @@program_transform_name@@
20168 transform_exe = s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/
20169 @end example
20171 Whether to do the transformations on documentation files (Texinfo or
20172 @code{man}) is a tricky question; there seems to be no perfect answer,
20173 due to the several reasons for name transforming.  Documentation is not
20174 usually particular to a specific architecture, and Texinfo files do not
20175 conflict with system documentation.  But they might conflict with
20176 earlier versions of the same files, and @code{man} pages sometimes do
20177 conflict with system documentation.  As a compromise, it is probably
20178 best to do name transformations on @code{man} pages but not on Texinfo
20179 manuals.
20181 @node Site Defaults
20182 @section Setting Site Defaults
20183 @cindex Site defaults
20184 @cindex config.site
20186 Autoconf-generated @command{configure} scripts allow your site to provide
20187 default values for some configuration values.  You do this by creating
20188 site- and system-wide initialization files.
20190 @evindex CONFIG_SITE
20191 If the environment variable @code{CONFIG_SITE} is set, @command{configure}
20192 uses its value as the name of a shell script to read.  Otherwise, it
20193 reads the shell script @file{@var{prefix}/share/config.site} if it exists,
20194 then @file{@var{prefix}/etc/config.site} if it exists.  Thus,
20195 settings in machine-specific files override those in machine-independent
20196 ones in case of conflict.
20198 Site files can be arbitrary shell scripts, but only certain kinds of
20199 code are really appropriate to be in them.  Because @command{configure}
20200 reads any cache file after it has read any site files, a site file can
20201 define a default cache file to be shared between all Autoconf-generated
20202 @command{configure} scripts run on that system (@pxref{Cache Files}).  If
20203 you set a default cache file in a site file, it is a good idea to also
20204 set the output variable @code{CC} in that site file, because the cache
20205 file is only valid for a particular compiler, but many systems have
20206 several available.
20208 You can examine or override the value set by a command line option to
20209 @command{configure} in a site file; options set shell variables that have
20210 the same names as the options, with any dashes turned into underscores.
20211 The exceptions are that @option{--without-} and @option{--disable-} options
20212 are like giving the corresponding @option{--with-} or @option{--enable-}
20213 option and the value @samp{no}.  Thus, @option{--cache-file=localcache}
20214 sets the variable @code{cache_file} to the value @samp{localcache};
20215 @option{--enable-warnings=no} or @option{--disable-warnings} sets the variable
20216 @code{enable_warnings} to the value @samp{no}; @option{--prefix=/usr} sets the
20217 variable @code{prefix} to the value @samp{/usr}; etc.
20219 Site files are also good places to set default values for other output
20220 variables, such as @code{CFLAGS}, if you need to give them non-default
20221 values: anything you would normally do, repetitively, on the command
20222 line.  If you use non-default values for @var{prefix} or
20223 @var{exec_prefix} (wherever you locate the site file), you can set them
20224 in the site file if you specify it with the @code{CONFIG_SITE}
20225 environment variable.
20227 You can set some cache values in the site file itself.  Doing this is
20228 useful if you are cross-compiling, where it is impossible to check features
20229 that require running a test program.  You could ``prime the cache'' by
20230 setting those values correctly for that system in
20231 @file{@var{prefix}/etc/config.site}.  To find out the names of the cache
20232 variables you need to set, look for shell variables with @samp{_cv_} in
20233 their names in the affected @command{configure} scripts, or in the Autoconf
20234 M4 source code for those macros.
20236 The cache file is careful to not override any variables set in the site
20237 files.  Similarly, you should not override command-line options in the
20238 site files.  Your code should check that variables such as @code{prefix}
20239 and @code{cache_file} have their default values (as set near the top of
20240 @command{configure}) before changing them.
20242 Here is a sample file @file{/usr/share/local/@/gnu/share/@/config.site}.  The
20243 command @samp{configure --prefix=/usr/share/local/gnu} would read this
20244 file (if @code{CONFIG_SITE} is not set to a different file).
20246 @example
20247 # /usr/share/local/gnu/share/config.site for configure
20249 # Change some defaults.
20250 test "$prefix" = NONE && prefix=/usr/share/local/gnu
20251 test "$exec_prefix" = NONE && exec_prefix=/usr/local/gnu
20252 test "$sharedstatedir" = '$@{prefix@}/com' && sharedstatedir=/var
20253 test "$localstatedir" = '$@{prefix@}/var' && localstatedir=/var
20255 # Give Autoconf 2.x generated configure scripts a shared default
20256 # cache file for feature test results, architecture-specific.
20257 if test "$cache_file" = /dev/null; then
20258   cache_file="$prefix/var/config.cache"
20259   # A cache file is only valid for one C compiler.
20260   CC=gcc
20262 @end example
20264 @cindex Filesystem Hierarchy Standard
20265 @cindex FHS
20267 Another use of @file{config.site} is for priming the directory variables
20268 in a manner consistent with the Filesystem Hierarchy Standard
20269 (@acronym{FHS}).  Once the following file is installed at
20270 @file{/usr/share/config.site}, a user can execute simply
20271 @code{./configure --prefix=/usr} to get all the directories chosen in
20272 the locations recommended by @acronym{FHS}.
20274 @example
20275 # /usr/share/config.site for FHS defaults when installing below /usr,
20276 # and the respective settings were not changed on the command line.
20277 if test "$prefix" = /usr; then
20278   test "$sysconfdir" = '$@{prefix@}/etc' && sysconfdir=/etc
20279   test "$sharedstatedir" = '$@{prefix@}/com' && sharedstatedir=/var
20280   test "$localstatedir" = '$@{prefix@}/var' && localstatedir=/var
20282 @end example
20284 @cindex lib64
20285 @cindex 64-bit libraries
20286 Likewise, on platforms where 64-bit libraries are built by default, then
20287 installed in @file{/usr/local/@/lib64} instead of @file{/usr/local/@/lib},
20288 it is appropriate to install @file{/usr/local/@/share/config.site}:
20290 @example
20291 # /usr/local/share/config.site for platforms that prefer
20292 # the directory /usr/local/lib64 over /usr/local/lib.
20293 test "$libdir" = '$@{exec_prefix@}/lib' && libdir='$@{exec_prefix@}/lib64'
20294 @end example
20297 @c ============================================== Running configure Scripts.
20299 @node Running configure Scripts
20300 @chapter Running @command{configure} Scripts
20301 @cindex @command{configure}
20303 Below are instructions on how to configure a package that uses a
20304 @command{configure} script, suitable for inclusion as an @file{INSTALL}
20305 file in the package.  A plain-text version of @file{INSTALL} which you
20306 may use comes with Autoconf.
20308 @menu
20309 * Basic Installation::          Instructions for typical cases
20310 * Compilers and Options::       Selecting compilers and optimization
20311 * Multiple Architectures::      Compiling for multiple architectures at once
20312 * Installation Names::          Installing in different directories
20313 * Optional Features::           Selecting optional features
20314 * Particular Systems::          Particular systems
20315 * System Type::                 Specifying the system type
20316 * Sharing Defaults::            Setting site-wide defaults for @command{configure}
20317 * Defining Variables::          Specifying the compiler etc.
20318 * configure Invocation::        Changing how @command{configure} runs
20319 @end menu
20321 @set autoconf
20322 @include install.texi
20325 @c ============================================== config.status Invocation
20327 @node config.status Invocation
20328 @chapter config.status Invocation
20329 @cindex @command{config.status}
20331 The @command{configure} script creates a file named @file{config.status},
20332 which actually configures, @dfn{instantiates}, the template files.  It
20333 also records the configuration options that were specified when the
20334 package was last configured in case reconfiguring is needed.
20336 Synopsis:
20337 @example
20338 ./config.status @ovar{option}@dots{} @ovar{tag}@dots{}
20339 @end example
20341 It configures each @var{tag}; if none are specified, all the templates
20342 are instantiated.  A @var{tag} refers to a file or other tag associated
20343 with a configuration action, as specified by an @code{AC_CONFIG_@var{ITEMS}}
20344 macro (@pxref{Configuration Actions}).  The files must be specified
20345 without their dependencies, as in
20347 @example
20348 ./config.status foobar
20349 @end example
20351 @noindent
20354 @example
20355 ./config.status foobar:foo.in:bar.in
20356 @end example
20358 The supported options are:
20360 @table @option
20361 @item --help
20362 @itemx -h
20363 Print a summary of the command line options, the list of the template
20364 files, and exit.
20366 @item --version
20367 @itemx -V
20368 Print the version number of Autoconf and the configuration settings,
20369 and exit.
20371 @item --silent
20372 @itemx --quiet
20373 @itemx -q
20374 Do not print progress messages.
20376 @item --debug
20377 @itemx -d
20378 Don't remove the temporary files.
20380 @item --file=@var{file}[:@var{template}]
20381 Require that @var{file} be instantiated as if
20382 @samp{AC_CONFIG_FILES(@var{file}:@var{template})} was used.  Both
20383 @var{file} and @var{template} may be @samp{-} in which case the standard
20384 output and/or standard input, respectively, is used.  If a
20385 @var{template} file name is relative, it is first looked for in the build
20386 tree, and then in the source tree.  @xref{Configuration Actions}, for
20387 more details.
20389 This option and the following ones provide one way for separately
20390 distributed packages to share the values computed by @command{configure}.
20391 Doing so can be useful if some of the packages need a superset of the
20392 features that one of them, perhaps a common library, does.  These
20393 options allow a @file{config.status} file to create files other than the
20394 ones that its @file{configure.ac} specifies, so it can be used for a
20395 different package, or for extracting a subset of values.  For example,
20397 @example
20398 echo '@@CC@@' | ./config.status --file=-
20399 @end example
20401 @noindent
20402 provides the value of @code{@@CC@@} on standard output.
20404 @item --header=@var{file}[:@var{template}]
20405 Same as @option{--file} above, but with @samp{AC_CONFIG_HEADERS}.
20407 @item --recheck
20408 Ask @file{config.status} to update itself and exit (no instantiation).
20409 This option is useful if you change @command{configure}, so that the
20410 results of some tests might be different from the previous run.  The
20411 @option{--recheck} option reruns @command{configure} with the same arguments
20412 you used before, plus the @option{--no-create} option, which prevents
20413 @command{configure} from running @file{config.status} and creating
20414 @file{Makefile} and other files, and the @option{--no-recursion} option,
20415 which prevents @command{configure} from running other @command{configure}
20416 scripts in subdirectories.  (This is so other Make rules can
20417 run @file{config.status} when it changes; @pxref{Automatic Remaking},
20418 for an example).
20419 @end table
20421 @file{config.status} checks several optional environment variables that
20422 can alter its behavior:
20424 @anchor{CONFIG_SHELL}
20425 @defvar CONFIG_SHELL
20426 @evindex CONFIG_SHELL
20427 The shell with which to run @command{configure} for the @option{--recheck}
20428 option.  It must be Bourne-compatible.  The default is a shell that
20429 supports @code{LINENO} if available, and @file{/bin/sh} otherwise.
20430 Invoking @command{configure} by hand bypasses this setting, so you may
20431 need to use a command like @samp{CONFIG_SHELL=/bin/bash /bin/bash ./configure}
20432 to insure that the same shell is used everywhere.  The absolute name of the
20433 shell should be passed.
20434 @end defvar
20436 @defvar CONFIG_STATUS
20437 @evindex CONFIG_STATUS
20438 The file name to use for the shell script that records the
20439 configuration.  The default is @file{./config.status}.  This variable is
20440 useful when one package uses parts of another and the @command{configure}
20441 scripts shouldn't be merged because they are maintained separately.
20442 @end defvar
20444 You can use @file{./config.status} in your makefiles.  For example, in
20445 the dependencies given above (@pxref{Automatic Remaking}),
20446 @file{config.status} is run twice when @file{configure.ac} has changed.
20447 If that bothers you, you can make each run only regenerate the files for
20448 that rule:
20449 @example
20450 @group
20451 config.h: stamp-h
20452 stamp-h: config.h.in config.status
20453         ./config.status config.h
20454         echo > stamp-h
20456 Makefile: Makefile.in config.status
20457         ./config.status Makefile
20458 @end group
20459 @end example
20461 The calling convention of @file{config.status} has changed; see
20462 @ref{Obsolete config.status Use}, for details.
20465 @c =================================================== Obsolete Constructs
20467 @node Obsolete Constructs
20468 @chapter Obsolete Constructs
20469 @cindex Obsolete constructs
20471 Autoconf changes, and throughout the years some constructs have been
20472 obsoleted.  Most of the changes involve the macros, but in some cases
20473 the tools themselves, or even some concepts, are now considered
20474 obsolete.
20476 You may completely skip this chapter if you are new to Autoconf.  Its
20477 intention is mainly to help maintainers updating their packages by
20478 understanding how to move to more modern constructs.
20480 @menu
20481 * Obsolete config.status Use::  Obsolete convention for @command{config.status}
20482 * acconfig Header::             Additional entries in @file{config.h.in}
20483 * autoupdate Invocation::       Automatic update of @file{configure.ac}
20484 * Obsolete Macros::             Backward compatibility macros
20485 * Autoconf 1::                  Tips for upgrading your files
20486 * Autoconf 2.13::               Some fresher tips
20487 @end menu
20489 @node Obsolete config.status Use
20490 @section Obsolete @file{config.status} Invocation
20492 @file{config.status} now supports arguments to specify the files to
20493 instantiate; see @ref{config.status Invocation}, for more details.
20494 Before, environment variables had to be used.
20496 @defvar CONFIG_COMMANDS
20497 @evindex CONFIG_COMMANDS
20498 The tags of the commands to execute.  The default is the arguments given
20499 to @code{AC_OUTPUT} and @code{AC_CONFIG_COMMANDS} in
20500 @file{configure.ac}.
20501 @end defvar
20503 @defvar CONFIG_FILES
20504 @evindex CONFIG_FILES
20505 The files in which to perform @samp{@@@var{variable}@@} substitutions.
20506 The default is the arguments given to @code{AC_OUTPUT} and
20507 @code{AC_CONFIG_FILES} in @file{configure.ac}.
20508 @end defvar
20510 @defvar CONFIG_HEADERS
20511 @evindex CONFIG_HEADERS
20512 The files in which to substitute C @code{#define} statements.  The
20513 default is the arguments given to @code{AC_CONFIG_HEADERS}; if that
20514 macro was not called, @file{config.status} ignores this variable.
20515 @end defvar
20517 @defvar CONFIG_LINKS
20518 @evindex CONFIG_LINKS
20519 The symbolic links to establish.  The default is the arguments given to
20520 @code{AC_CONFIG_LINKS}; if that macro was not called,
20521 @file{config.status} ignores this variable.
20522 @end defvar
20524 In @ref{config.status Invocation}, using this old interface, the example
20525 would be:
20527 @example
20528 @group
20529 config.h: stamp-h
20530 stamp-h: config.h.in config.status
20531         CONFIG_COMMANDS= CONFIG_LINKS= CONFIG_FILES= \
20532           CONFIG_HEADERS=config.h ./config.status
20533         echo > stamp-h
20535 Makefile: Makefile.in config.status
20536         CONFIG_COMMANDS= CONFIG_LINKS= CONFIG_HEADERS= \
20537           CONFIG_FILES=Makefile ./config.status
20538 @end group
20539 @end example
20541 @noindent
20542 (If @file{configure.ac} does not call @code{AC_CONFIG_HEADERS}, there is
20543 no need to set @code{CONFIG_HEADERS} in the @command{make} rules.  Equally
20544 for @code{CONFIG_COMMANDS}, etc.)
20547 @node acconfig Header
20548 @section @file{acconfig.h}
20550 @cindex @file{acconfig.h}
20551 @cindex @file{config.h.top}
20552 @cindex @file{config.h.bot}
20554 In order to produce @file{config.h.in}, @command{autoheader} needs to
20555 build or to find templates for each symbol.  Modern releases of Autoconf
20556 use @code{AH_VERBATIM} and @code{AH_TEMPLATE} (@pxref{Autoheader
20557 Macros}), but in older releases a file, @file{acconfig.h}, contained the
20558 list of needed templates.  @command{autoheader} copied comments and
20559 @code{#define} and @code{#undef} statements from @file{acconfig.h} in
20560 the current directory, if present.  This file used to be mandatory if
20561 you @code{AC_DEFINE} any additional symbols.
20563 Modern releases of Autoconf also provide @code{AH_TOP} and
20564 @code{AH_BOTTOM} if you need to prepend/append some information to
20565 @file{config.h.in}.  Ancient versions of Autoconf had a similar feature:
20566 if @file{./acconfig.h} contains the string @samp{@@TOP@@},
20567 @command{autoheader} copies the lines before the line containing
20568 @samp{@@TOP@@} into the top of the file that it generates.  Similarly,
20569 if @file{./acconfig.h} contains the string @samp{@@BOTTOM@@},
20570 @command{autoheader} copies the lines after that line to the end of the
20571 file it generates.  Either or both of those strings may be omitted.  An
20572 even older alternate way to produce the same effect in ancient versions
20573 of Autoconf is to create the files @file{@var{file}.top} (typically
20574 @file{config.h.top}) and/or @file{@var{file}.bot} in the current
20575 directory.  If they exist, @command{autoheader} copies them to the
20576 beginning and end, respectively, of its output.
20578 In former versions of Autoconf, the files used in preparing a software
20579 package for distribution were:
20580 @example
20581 @group
20582 configure.ac --.   .------> autoconf* -----> configure
20583                +---+
20584 [aclocal.m4] --+   `---.
20585 [acsite.m4] ---'       |
20586                        +--> [autoheader*] -> [config.h.in]
20587 [acconfig.h] ----.     |
20588                  +-----'
20589 [config.h.top] --+
20590 [config.h.bot] --'
20591 @end group
20592 @end example
20594 Using only the @code{AH_} macros, @file{configure.ac} should be
20595 self-contained, and should not depend upon @file{acconfig.h} etc.
20598 @node autoupdate Invocation
20599 @section Using @command{autoupdate} to Modernize @file{configure.ac}
20600 @cindex @command{autoupdate}
20602 The @command{autoupdate} program updates a @file{configure.ac} file that
20603 calls Autoconf macros by their old names to use the current macro names.
20604 In version 2 of Autoconf, most of the macros were renamed to use a more
20605 uniform and descriptive naming scheme.  @xref{Macro Names}, for a
20606 description of the new scheme.  Although the old names still work
20607 (@pxref{Obsolete Macros}, for a list of the old macros and the corresponding
20608 new names), you can make your @file{configure.ac} files more readable
20609 and make it easier to use the current Autoconf documentation if you
20610 update them to use the new macro names.
20612 @evindex SIMPLE_BACKUP_SUFFIX
20613 If given no arguments, @command{autoupdate} updates @file{configure.ac},
20614 backing up the original version with the suffix @file{~} (or the value
20615 of the environment variable @code{SIMPLE_BACKUP_SUFFIX}, if that is
20616 set).  If you give @command{autoupdate} an argument, it reads that file
20617 instead of @file{configure.ac} and writes the updated file to the
20618 standard output.
20620 @noindent
20621 @command{autoupdate} accepts the following options:
20623 @table @option
20624 @item --help
20625 @itemx -h
20626 Print a summary of the command line options and exit.
20628 @item --version
20629 @itemx -V
20630 Print the version number of Autoconf and exit.
20632 @item --verbose
20633 @itemx -v
20634 Report processing steps.
20636 @item --debug
20637 @itemx -d
20638 Don't remove the temporary files.
20640 @item --force
20641 @itemx -f
20642 Force the update even if the file has not changed.  Disregard the cache.
20644 @item --include=@var{dir}
20645 @itemx -I @var{dir}
20646 Also look for input files in @var{dir}.  Multiple invocations accumulate.
20647 Directories are browsed from last to first.
20649 @item --prepend-include=@var{dir}
20650 @itemx -B @var{dir}
20651 Prepend directory @var{dir} to the search path.  This is used to include
20652 the language-specific files before any third-party macros.
20653 @end table
20655 @node Obsolete Macros
20656 @section Obsolete Macros
20658 Several macros are obsoleted in Autoconf, for various reasons (typically
20659 they failed to quote properly, couldn't be extended for more recent
20660 issues, etc.).  They are still supported, but deprecated: their use
20661 should be avoided.
20663 During the jump from Autoconf version 1 to version 2, most of the
20664 macros were renamed to use a more uniform and descriptive naming scheme,
20665 but their signature did not change.  @xref{Macro Names}, for a
20666 description of the new naming scheme.  Below, if there is just the mapping
20667 from old names to new names for these macros, the reader is invited to
20668 refer to the definition of the new macro for the signature and the
20669 description.
20671 @defmac AC_AIX
20672 @acindex{AIX}
20673 @cvindex _ALL_SOURCE
20674 This macro is a platform-specific subset of
20675 @code{AC_USE_SYSTEM_EXTENSIONS} (@pxref{AC_USE_SYSTEM_EXTENSIONS}).
20676 @end defmac
20678 @defmac AC_ALLOCA
20679 @acindex{ALLOCA}
20680 Replaced by @code{AC_FUNC_ALLOCA} (@pxref{AC_FUNC_ALLOCA}).
20681 @end defmac
20683 @defmac AC_ARG_ARRAY
20684 @acindex{ARG_ARRAY}
20685 Removed because of limited usefulness.
20686 @end defmac
20688 @defmac AC_C_CROSS
20689 @acindex{C_CROSS}
20690 This macro is obsolete; it does nothing.
20691 @end defmac
20693 @defmac AC_C_LONG_DOUBLE
20694 @acindex{C_LONG_DOUBLE}
20695 @cvindex HAVE_LONG_DOUBLE
20696 If the C compiler supports a working @code{long double} type with more
20697 range or precision than the @code{double} type, define
20698 @code{HAVE_LONG_DOUBLE}.
20700 You should use @code{AC_TYPE_LONG_DOUBLE} or
20701 @code{AC_TYPE_LONG_DOUBLE_WIDER} instead.  @xref{Particular Types}.
20702 @end defmac
20704 @defmac AC_CANONICAL_SYSTEM
20705 @acindex{CANONICAL_SYSTEM}
20706 Determine the system type and set output variables to the names of the
20707 canonical system types.  @xref{Canonicalizing}, for details about the
20708 variables this macro sets.
20710 The user is encouraged to use either @code{AC_CANONICAL_BUILD}, or
20711 @code{AC_CANONICAL_HOST}, or @code{AC_CANONICAL_TARGET}, depending on
20712 the needs.  Using @code{AC_CANONICAL_TARGET} is enough to run the two
20713 other macros (@pxref{Canonicalizing}).
20714 @end defmac
20716 @defmac AC_CHAR_UNSIGNED
20717 @acindex{CHAR_UNSIGNED}
20718 Replaced by @code{AC_C_CHAR_UNSIGNED} (@pxref{AC_C_CHAR_UNSIGNED}).
20719 @end defmac
20721 @defmac AC_CHECK_TYPE (@var{type}, @var{default})
20722 @acindex{CHECK_TYPE}
20723 Autoconf, up to 2.13, used to provide this version of
20724 @code{AC_CHECK_TYPE}, deprecated because of its flaws.  First, although
20725 it is a member of the @code{CHECK} clan, it does
20726 more than just checking.  Secondly, missing types are defined
20727 using @code{#define}, not @code{typedef}, and this can lead to
20728 problems in the case of pointer types.
20730 This use of @code{AC_CHECK_TYPE} is obsolete and discouraged; see
20731 @ref{Generic Types}, for the description of the current macro.
20733 If the type @var{type} is not defined, define it to be the C (or C++)
20734 builtin type @var{default}, e.g., @samp{short int} or @samp{unsigned int}.
20736 This macro is equivalent to:
20738 @example
20739 AC_CHECK_TYPE([@var{type}], [],
20740   [AC_DEFINE_UNQUOTED([@var{type}], [@var{default}],
20741      [Define to `@var{default}'
20742       if <sys/types.h> does not define.])])
20743 @end example
20745 In order to keep backward compatibility, the two versions of
20746 @code{AC_CHECK_TYPE} are implemented, selected using these heuristics:
20748 @enumerate
20749 @item
20750 If there are three or four arguments, the modern version is used.
20752 @item
20753 If the second argument appears to be a C or C++ type, then the
20754 obsolete version is used.  This happens if the argument is a C or C++
20755 @emph{builtin} type or a C identifier ending in @samp{_t}, optionally
20756 followed by one of @samp{[(* } and then by a string of zero or more
20757 characters taken from the set @samp{[]()* _a-zA-Z0-9}.
20759 @item
20760 If the second argument is spelled with the alphabet of valid C and C++
20761 types, the user is warned and the modern version is used.
20763 @item
20764 Otherwise, the modern version is used.
20765 @end enumerate
20767 @noindent
20768 You are encouraged either to use a valid builtin type, or to use the
20769 equivalent modern code (see above), or better yet, to use
20770 @code{AC_CHECK_TYPES} together with
20772 @example
20773 #ifndef HAVE_LOFF_T
20774 typedef loff_t off_t;
20775 #endif
20776 @end example
20777 @end defmac
20778 @c end of AC_CHECK_TYPE
20780 @defmac AC_CHECKING (@var{feature-description})
20781 @acindex{CHECKING}
20782 Same as
20784 @example
20785 AC_MSG_NOTICE([checking @var{feature-description}@dots{}]
20786 @end example
20788 @noindent
20789 @xref{AC_MSG_NOTICE}.
20790 @end defmac
20792 @defmac AC_COMPILE_CHECK (@var{echo-text}, @var{includes}, @
20793   @var{function-body}, @var{action-if-true}, @ovar{action-if-false})
20794 @acindex{COMPILE_CHECK}
20795 This is an obsolete version of @code{AC_TRY_COMPILE} itself replaced by
20796 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}), with the
20797 addition that it prints @samp{checking for @var{echo-text}} to the
20798 standard output first, if @var{echo-text} is non-empty.  Use
20799 @code{AC_MSG_CHECKING} and @code{AC_MSG_RESULT} instead to print
20800 messages (@pxref{Printing Messages}).
20801 @end defmac
20803 @defmac AC_CONST
20804 @acindex{CONST}
20805 Replaced by @code{AC_C_CONST} (@pxref{AC_C_CONST}).
20806 @end defmac
20808 @defmac AC_CROSS_CHECK
20809 @acindex{CROSS_CHECK}
20810 Same as @code{AC_C_CROSS}, which is obsolete too, and does nothing
20811 @code{:-)}.
20812 @end defmac
20814 @defmac AC_CYGWIN
20815 @acindex{CYGWIN}
20816 @evindex CYGWIN
20817 Check for the Cygwin environment in which case the shell variable
20818 @code{CYGWIN} is set to @samp{yes}.  Don't use this macro, the dignified
20819 means to check the nature of the host is using @code{AC_CANONICAL_HOST}
20820 (@pxref{Canonicalizing}).  As a matter of fact this macro is defined as:
20822 @example
20823 AC_REQUIRE([AC_CANONICAL_HOST])[]dnl
20824 case $host_os in
20825   *cygwin* ) CYGWIN=yes;;
20826          * ) CYGWIN=no;;
20827 esac
20828 @end example
20830 Beware that the variable @env{CYGWIN} has a special meaning when
20831 running Cygwin, and should not be changed.  That's yet another reason
20832 not to use this macro.
20833 @end defmac
20835 @defmac AC_DECL_SYS_SIGLIST
20836 @acindex{DECL_SYS_SIGLIST}
20837 @cvindex SYS_SIGLIST_DECLARED
20838 Same as:
20840 @example
20841 AC_CHECK_DECLS([sys_siglist], [], [],
20842 [#include <signal.h>
20843 /* NetBSD declares sys_siglist in unistd.h.  */
20844 #ifdef HAVE_UNISTD_H
20845 # include <unistd.h>
20846 #endif
20848 @end example
20850 @noindent
20851 @xref{AC_CHECK_DECLS}.
20852 @end defmac
20854 @defmac AC_DECL_YYTEXT
20855 @acindex{DECL_YYTEXT}
20856 Does nothing, now integrated in @code{AC_PROG_LEX} (@pxref{AC_PROG_LEX}).
20857 @end defmac
20859 @defmac AC_DIR_HEADER
20860 @acindex{DIR_HEADER}
20861 @cvindex DIRENT
20862 @cvindex SYSNDIR
20863 @cvindex SYSDIR
20864 @cvindex NDIR
20865 Like calling @code{AC_FUNC_CLOSEDIR_VOID}
20866 (@pxref{AC_FUNC_CLOSEDIR_VOID}) and @code{AC_HEADER_DIRENT}
20867 (@pxref{AC_HEADER_DIRENT}),
20868 but defines a different set of C preprocessor macros to indicate which
20869 header file is found:
20871 @multitable {@file{sys/ndir.h}} {Old Symbol} {@code{HAVE_SYS_NDIR_H}}
20872 @item Header            @tab Old Symbol     @tab New Symbol
20873 @item @file{dirent.h}   @tab @code{DIRENT}  @tab @code{HAVE_DIRENT_H}
20874 @item @file{sys/ndir.h} @tab @code{SYSNDIR} @tab @code{HAVE_SYS_NDIR_H}
20875 @item @file{sys/dir.h}  @tab @code{SYSDIR}  @tab @code{HAVE_SYS_DIR_H}
20876 @item @file{ndir.h}     @tab @code{NDIR}    @tab @code{HAVE_NDIR_H}
20877 @end multitable
20878 @end defmac
20880 @defmac AC_DYNIX_SEQ
20881 @acindex{DYNIX_SEQ}
20882 If on DYNIX/ptx, add @option{-lseq} to output variable
20883 @code{LIBS}.  This macro used to be defined as
20885 @example
20886 AC_CHECK_LIB([seq], [getmntent], [LIBS="-lseq $LIBS"])
20887 @end example
20889 @noindent
20890 now it is just @code{AC_FUNC_GETMNTENT} (@pxref{AC_FUNC_GETMNTENT}).
20891 @end defmac
20893 @defmac AC_EXEEXT
20894 @acindex{EXEEXT}
20895 @ovindex EXEEXT
20896 Defined the output variable @code{EXEEXT} based on the output of the
20897 compiler, which is now done automatically.  Typically set to empty
20898 string if Posix and @samp{.exe} if a @acronym{DOS} variant.
20899 @end defmac
20901 @defmac AC_EMXOS2
20902 @acindex{EMXOS2}
20903 Similar to @code{AC_CYGWIN} but checks for the EMX environment on OS/2
20904 and sets @code{EMXOS2}.  Don't use this macro, the dignified means to
20905 check the nature of the host is using @code{AC_CANONICAL_HOST}
20906 (@pxref{Canonicalizing}).
20907 @end defmac
20909 @defmac AC_ENABLE (@var{feature}, @var{action-if-given}, @
20910   @ovar{action-if-not-given})
20911 @acindex{ENABLE}
20912 This is an obsolete version of @code{AC_ARG_ENABLE} that does not
20913 support providing a help string (@pxref{AC_ARG_ENABLE}).
20914 @end defmac
20916 @defmac AC_ERROR
20917 @acindex{ERROR}
20918 Replaced by @code{AC_MSG_ERROR} (@pxref{AC_MSG_ERROR}).
20919 @end defmac
20921 @defmac AC_FIND_X
20922 @acindex{FIND_X}
20923 Replaced by @code{AC_PATH_X} (@pxref{AC_PATH_X}).
20924 @end defmac
20926 @defmac AC_FIND_XTRA
20927 @acindex{FIND_XTRA}
20928 Replaced by @code{AC_PATH_XTRA} (@pxref{AC_PATH_XTRA}).
20929 @end defmac
20931 @defmac AC_FOREACH
20932 @acindex{FOREACH}
20933 Replaced by @code{m4_foreach_w} (@pxref{m4_foreach_w}).
20934 @end defmac
20936 @defmac AC_FUNC_CHECK
20937 @acindex{FUNC_CHECK}
20938 Replaced by @code{AC_CHECK_FUNC} (@pxref{AC_CHECK_FUNC}).
20939 @end defmac
20941 @anchor{AC_FUNC_SETVBUF_REVERSED}
20942 @defmac AC_FUNC_SETVBUF_REVERSED
20943 @acindex{FUNC_SETVBUF_REVERSED}
20944 @cvindex SETVBUF_REVERSED
20945 @c @fuindex setvbuf
20946 @prindex @code{setvbuf}
20947 Do nothing.  Formerly, this macro checked whether @code{setvbuf} takes
20948 the buffering type as its second argument and the buffer pointer as the
20949 third, instead of the other way around, and defined
20950 @code{SETVBUF_REVERSED}.  However, the last systems to have the problem
20951 were those based on SVR2, which became obsolete in 1987, and the macro
20952 is no longer needed.
20953 @end defmac
20955 @defmac AC_FUNC_WAIT3
20956 @acindex{FUNC_WAIT3}
20957 @cvindex HAVE_WAIT3
20958 @c @fuindex wait3
20959 @prindex @code{wait3}
20960 If @code{wait3} is found and fills in the contents of its third argument
20961 (a @samp{struct rusage *}), which @acronym{HP-UX} does not do, define
20962 @code{HAVE_WAIT3}.
20964 These days portable programs should use @code{waitpid}, not
20965 @code{wait3}, as @code{wait3} has been removed from Posix.
20966 @end defmac
20968 @defmac AC_GCC_TRADITIONAL
20969 @acindex{GCC_TRADITIONAL}
20970 Replaced by @code{AC_PROG_GCC_TRADITIONAL} (@pxref{AC_PROG_GCC_TRADITIONAL}).
20971 @end defmac
20973 @defmac AC_GETGROUPS_T
20974 @acindex{GETGROUPS_T}
20975 Replaced by @code{AC_TYPE_GETGROUPS} (@pxref{AC_TYPE_GETGROUPS}).
20976 @end defmac
20978 @defmac AC_GETLOADAVG
20979 @acindex{GETLOADAVG}
20980 Replaced by @code{AC_FUNC_GETLOADAVG} (@pxref{AC_FUNC_GETLOADAVG}).
20981 @end defmac
20983 @defmac AC_GNU_SOURCE
20984 @acindex{GNU_SOURCE}
20985 @cvindex _GNU_SOURCE
20986 This macro is a platform-specific subset of
20987 @code{AC_USE_SYSTEM_EXTENSIONS} (@pxref{AC_USE_SYSTEM_EXTENSIONS}).
20988 @end defmac
20990 @defmac AC_HAVE_FUNCS
20991 @acindex{HAVE_FUNCS}
20992 Replaced by @code{AC_CHECK_FUNCS} (@pxref{AC_CHECK_FUNCS}).
20993 @end defmac
20995 @defmac AC_HAVE_HEADERS
20996 @acindex{HAVE_HEADERS}
20997 Replaced by @code{AC_CHECK_HEADERS} (@pxref{AC_CHECK_HEADERS}).
20998 @end defmac
21000 @defmac AC_HAVE_LIBRARY (@var{library}, @ovar{action-if-found}, @
21001   @ovar{action-if-not-found}, @ovar{other-libraries})
21002 @acindex{HAVE_LIBRARY}
21003 This macro is equivalent to calling @code{AC_CHECK_LIB} with a
21004 @var{function} argument of @code{main}.  In addition, @var{library} can
21005 be written as any of @samp{foo}, @option{-lfoo}, or @samp{libfoo.a}.  In
21006 all of those cases, the compiler is passed @option{-lfoo}.  However,
21007 @var{library} cannot be a shell variable; it must be a literal name.
21008 @xref{AC_CHECK_LIB}.
21009 @end defmac
21011 @defmac AC_HAVE_POUNDBANG
21012 @acindex{HAVE_POUNDBANG}
21013 Replaced by @code{AC_SYS_INTERPRETER} (@pxref{AC_SYS_INTERPRETER}).
21014 @end defmac
21016 @defmac AC_HEADER_CHECK
21017 @acindex{HEADER_CHECK}
21018 Replaced by @code{AC_CHECK_HEADER} (@pxref{AC_CHECK_HEADER}).
21019 @end defmac
21021 @defmac AC_HEADER_EGREP
21022 @acindex{HEADER_EGREP}
21023 Replaced by @code{AC_EGREP_HEADER} (@pxref{AC_EGREP_HEADER}).
21024 @end defmac
21026 @defmac AC_HELP_STRING
21027 @acindex{HELP_STRING}
21028 Replaced by @code{AS_HELP_STRING} (@pxref{AS_HELP_STRING}).
21029 @end defmac
21031 @defmac AC_INIT (@var{unique-file-in-source-dir})
21032 @acindex{INIT}
21033 Formerly @code{AC_INIT} used to have a single argument, and was
21034 equivalent to:
21036 @example
21037 AC_INIT
21038 AC_CONFIG_SRCDIR(@var{unique-file-in-source-dir})
21039 @end example
21040 See @ref{AC_INIT} and @ref{AC_CONFIG_SRCDIR}.
21041 @end defmac
21043 @defmac AC_INLINE
21044 @acindex{INLINE}
21045 Replaced by @code{AC_C_INLINE} (@pxref{AC_C_INLINE}).
21046 @end defmac
21048 @defmac AC_INT_16_BITS
21049 @acindex{INT_16_BITS}
21050 @cvindex INT_16_BITS
21051 If the C type @code{int} is 16 bits wide, define @code{INT_16_BITS}.
21052 Use @samp{AC_CHECK_SIZEOF(int)} instead (@pxref{AC_CHECK_SIZEOF}).
21053 @end defmac
21055 @defmac AC_IRIX_SUN
21056 @acindex{IRIX_SUN}
21057 If on @sc{irix} (Silicon Graphics Unix), add @option{-lsun} to output
21058 @code{LIBS}.  If you were using it to get @code{getmntent}, use
21059 @code{AC_FUNC_GETMNTENT} instead.  If you used it for the NIS versions
21060 of the password and group functions, use @samp{AC_CHECK_LIB(sun,
21061 getpwnam)}.  Up to Autoconf 2.13, it used to be
21063 @example
21064 AC_CHECK_LIB([sun], [getmntent], [LIBS="-lsun $LIBS"])
21065 @end example
21067 @noindent
21068 now it is defined as
21070 @example
21071 AC_FUNC_GETMNTENT
21072 AC_CHECK_LIB([sun], [getpwnam])
21073 @end example
21075 @noindent
21076 See @ref{AC_FUNC_GETMNTENT} and @ref{AC_CHECK_LIB}.
21077 @end defmac
21079 @defmac AC_ISC_POSIX
21080 @acindex{ISC_POSIX}
21081 @ovindex LIBS
21082 This macro adds @option{-lcposix} to output variable @code{LIBS} if
21083 necessary for Posix facilities.  Sun dropped support for the obsolete
21084 @sc{interactive} Systems Corporation Unix on 2006-07-23.  New programs
21085 need not use this macro.  It is implemented as
21086 @code{AC_SEARCH_LIBS([strerror], [cposix])} (@pxref{AC_SEARCH_LIBS}).
21087 @end defmac
21089 @defmac AC_LANG_C
21090 @acindex{LANG_C}
21091 Same as @samp{AC_LANG([C])} (@pxref{AC_LANG}).
21092 @end defmac
21094 @defmac AC_LANG_CPLUSPLUS
21095 @acindex{LANG_CPLUSPLUS}
21096 Same as @samp{AC_LANG([C++])} (@pxref{AC_LANG}).
21097 @end defmac
21099 @defmac AC_LANG_FORTRAN77
21100 @acindex{LANG_FORTRAN77}
21101 Same as @samp{AC_LANG([Fortran 77])} (@pxref{AC_LANG}).
21102 @end defmac
21104 @defmac AC_LANG_RESTORE
21105 @acindex{LANG_RESTORE}
21106 Select the @var{language} that is saved on the top of the stack, as set
21107 by @code{AC_LANG_SAVE}, remove it from the stack, and call
21108 @code{AC_LANG(@var{language})}.  @xref{Language Choice}, for the
21109 preferred way to change languages.
21110 @end defmac
21112 @defmac AC_LANG_SAVE
21113 @acindex{LANG_SAVE}
21114 Remember the current language (as set by @code{AC_LANG}) on a stack.
21115 The current language does not change.  @code{AC_LANG_PUSH} is preferred
21116 (@pxref{AC_LANG_PUSH}).
21117 @end defmac
21119 @defmac AC_LINK_FILES (@var{source}@dots{}, @var{dest}@dots{})
21120 @acindex{LINK_FILES}
21121 This is an obsolete version of @code{AC_CONFIG_LINKS}
21122 (@pxref{AC_CONFIG_LINKS}.  An updated version of:
21124 @example
21125 AC_LINK_FILES(config/$machine.h config/$obj_format.h,
21126               host.h            object.h)
21127 @end example
21129 @noindent
21132 @example
21133 AC_CONFIG_LINKS([host.h:config/$machine.h
21134                 object.h:config/$obj_format.h])
21135 @end example
21136 @end defmac
21138 @defmac AC_LN_S
21139 @acindex{LN_S}
21140 Replaced by @code{AC_PROG_LN_S} (@pxref{AC_PROG_LN_S}).
21141 @end defmac
21143 @defmac AC_LONG_64_BITS
21144 @acindex{LONG_64_BITS}
21145 @cvindex LONG_64_BITS
21146 Define @code{LONG_64_BITS} if the C type @code{long int} is 64 bits wide.
21147 Use the generic macro @samp{AC_CHECK_SIZEOF([long int])} instead
21148 (@pxref{AC_CHECK_SIZEOF}).
21149 @end defmac
21151 @defmac AC_LONG_DOUBLE
21152 @acindex{LONG_DOUBLE}
21153 If the C compiler supports a working @code{long double} type with more
21154 range or precision than the @code{double} type, define
21155 @code{HAVE_LONG_DOUBLE}.
21157 You should use @code{AC_TYPE_LONG_DOUBLE} or
21158 @code{AC_TYPE_LONG_DOUBLE_WIDER} instead.  @xref{Particular Types}.
21159 @end defmac
21161 @defmac AC_LONG_FILE_NAMES
21162 @acindex{LONG_FILE_NAMES}
21163 Replaced by
21164 @example
21165 AC_SYS_LONG_FILE_NAMES
21166 @end example
21167 @noindent
21168 @xref{AC_SYS_LONG_FILE_NAMES}.
21169 @end defmac
21171 @defmac AC_MAJOR_HEADER
21172 @acindex{MAJOR_HEADER}
21173 Replaced by @code{AC_HEADER_MAJOR} (@pxref{AC_HEADER_MAJOR}).
21174 @end defmac
21176 @defmac AC_MEMORY_H
21177 @acindex{MEMORY_H}
21178 @cvindex NEED_MEMORY_H
21179 Used to define @code{NEED_MEMORY_H} if the @code{mem} functions were
21180 defined in @file{memory.h}.  Today it is equivalent to
21181 @samp{AC_CHECK_HEADERS([memory.h])} (@pxref{AC_CHECK_HEADERS}).  Adjust
21182 your code to depend upon
21183 @code{HAVE_MEMORY_H}, not @code{NEED_MEMORY_H}; see @ref{Standard
21184 Symbols}.
21185 @end defmac
21187 @defmac AC_MINGW32
21188 @acindex{MINGW32}
21189 Similar to @code{AC_CYGWIN} but checks for the MinGW compiler
21190 environment and sets @code{MINGW32}.  Don't use this macro, the
21191 dignified means to check the nature of the host is using
21192 @code{AC_CANONICAL_HOST} (@pxref{Canonicalizing}).
21193 @end defmac
21195 @defmac AC_MINIX
21196 @acindex{MINIX}
21197 @cvindex _MINIX
21198 @cvindex _POSIX_SOURCE
21199 @cvindex _POSIX_1_SOURCE
21200 This macro is a platform-specific subset of
21201 @code{AC_USE_SYSTEM_EXTENSIONS} (@pxref{AC_USE_SYSTEM_EXTENSIONS}).
21202 @end defmac
21204 @defmac AC_MINUS_C_MINUS_O
21205 @acindex{MINUS_C_MINUS_O}
21206 Replaced by @code{AC_PROG_CC_C_O} (@pxref{AC_PROG_CC_C_O}).
21207 @end defmac
21209 @defmac AC_MMAP
21210 @acindex{MMAP}
21211 Replaced by @code{AC_FUNC_MMAP} (@pxref{AC_FUNC_MMAP}).
21212 @end defmac
21214 @defmac AC_MODE_T
21215 @acindex{MODE_T}
21216 Replaced by @code{AC_TYPE_MODE_T} (@pxref{AC_TYPE_MODE_T}).
21217 @end defmac
21219 @defmac AC_OBJEXT
21220 @acindex{OBJEXT}
21221 @ovindex OBJEXT
21222 Defined the output variable @code{OBJEXT} based on the output of the
21223 compiler, after .c files have been excluded.  Typically set to @samp{o}
21224 if Posix, @samp{obj} if a @acronym{DOS} variant.
21225 Now the compiler checking macros handle
21226 this automatically.
21227 @end defmac
21229 @defmac AC_OBSOLETE (@var{this-macro-name}, @ovar{suggestion})
21230 @acindex{OBSOLETE}
21231 Make M4 print a message to the standard error output warning that
21232 @var{this-macro-name} is obsolete, and giving the file and line number
21233 where it was called.  @var{this-macro-name} should be the name of the
21234 macro that is calling @code{AC_OBSOLETE}.  If @var{suggestion} is given,
21235 it is printed at the end of the warning message; for example, it can be
21236 a suggestion for what to use instead of @var{this-macro-name}.
21238 For instance
21240 @example
21241 AC_OBSOLETE([$0], [; use AC_CHECK_HEADERS(unistd.h) instead])dnl
21242 @end example
21244 @noindent
21245 You are encouraged to use @code{AU_DEFUN} instead, since it gives better
21246 services to the user (@pxref{AU_DEFUN}).
21247 @end defmac
21249 @defmac AC_OFF_T
21250 @acindex{OFF_T}
21251 Replaced by @code{AC_TYPE_OFF_T} (@pxref{AC_TYPE_OFF_T}).
21252 @end defmac
21254 @defmac AC_OUTPUT (@ovar{file}@dots{}, @ovar{extra-cmds}, @ovar{init-cmds})
21255 @acindex{OUTPUT}
21256 The use of @code{AC_OUTPUT} with arguments is deprecated.  This obsoleted
21257 interface is equivalent to:
21259 @example
21260 @group
21261 AC_CONFIG_FILES(@var{file}@dots{})
21262 AC_CONFIG_COMMANDS([default],
21263                    @var{extra-cmds}, @var{init-cmds})
21264 AC_OUTPUT
21265 @end group
21266 @end example
21268 @noindent
21269 See @ref{AC_CONFIG_FILES}, @ref{AC_CONFIG_COMMANDS}, and @ref{AC_OUTPUT}.
21270 @end defmac
21272 @defmac AC_OUTPUT_COMMANDS (@var{extra-cmds}, @ovar{init-cmds})
21273 @acindex{OUTPUT_COMMANDS}
21274 Specify additional shell commands to run at the end of
21275 @file{config.status}, and shell commands to initialize any variables
21276 from @command{configure}.  This macro may be called multiple times.  It is
21277 obsolete, replaced by @code{AC_CONFIG_COMMANDS} (@pxref{AC_CONFIG_COMMANDS}).
21279 Here is an unrealistic example:
21281 @example
21282 fubar=27
21283 AC_OUTPUT_COMMANDS([echo this is extra $fubar, and so on.],
21284                    [fubar=$fubar])
21285 AC_OUTPUT_COMMANDS([echo this is another, extra, bit],
21286                    [echo init bit])
21287 @end example
21289 Aside from the fact that @code{AC_CONFIG_COMMANDS} requires an
21290 additional key, an important difference is that
21291 @code{AC_OUTPUT_COMMANDS} is quoting its arguments twice, unlike
21292 @code{AC_CONFIG_COMMANDS}.  This means that @code{AC_CONFIG_COMMANDS}
21293 can safely be given macro calls as arguments:
21295 @example
21296 AC_CONFIG_COMMANDS(foo, [my_FOO()])
21297 @end example
21299 @noindent
21300 Conversely, where one level of quoting was enough for literal strings
21301 with @code{AC_OUTPUT_COMMANDS}, you need two with
21302 @code{AC_CONFIG_COMMANDS}.  The following lines are equivalent:
21304 @example
21305 @group
21306 AC_OUTPUT_COMMANDS([echo "Square brackets: []"])
21307 AC_CONFIG_COMMANDS([default], [[echo "Square brackets: []"]])
21308 @end group
21309 @end example
21310 @end defmac
21312 @defmac AC_PID_T
21313 @acindex{PID_T}
21314 Replaced by @code{AC_TYPE_PID_T} (@pxref{AC_TYPE_PID_T}).
21315 @end defmac
21317 @defmac AC_PREFIX
21318 @acindex{PREFIX}
21319 Replaced by @code{AC_PREFIX_PROGRAM} (@pxref{AC_PREFIX_PROGRAM}).
21320 @end defmac
21322 @defmac AC_PROGRAMS_CHECK
21323 @acindex{PROGRAMS_CHECK}
21324 Replaced by @code{AC_CHECK_PROGS} (@pxref{AC_CHECK_PROGS}).
21325 @end defmac
21327 @defmac AC_PROGRAMS_PATH
21328 @acindex{PROGRAMS_PATH}
21329 Replaced by @code{AC_PATH_PROGS} (@pxref{AC_PATH_PROGS}).
21330 @end defmac
21332 @defmac AC_PROGRAM_CHECK
21333 @acindex{PROGRAM_CHECK}
21334 Replaced by @code{AC_CHECK_PROG} (@pxref{AC_CHECK_PROG}).
21335 @end defmac
21337 @defmac AC_PROGRAM_EGREP
21338 @acindex{PROGRAM_EGREP}
21339 Replaced by @code{AC_EGREP_CPP} (@pxref{AC_EGREP_CPP}).
21340 @end defmac
21342 @defmac AC_PROGRAM_PATH
21343 @acindex{PROGRAM_PATH}
21344 Replaced by @code{AC_PATH_PROG} (@pxref{AC_PATH_PROG}).
21345 @end defmac
21347 @defmac AC_REMOTE_TAPE
21348 @acindex{REMOTE_TAPE}
21349 Removed because of limited usefulness.
21350 @end defmac
21352 @defmac AC_RESTARTABLE_SYSCALLS
21353 @acindex{RESTARTABLE_SYSCALLS}
21354 This macro was renamed @code{AC_SYS_RESTARTABLE_SYSCALLS}.  However,
21355 these days portable programs should use @code{sigaction} with
21356 @code{SA_RESTART} if they want restartable system calls.  They should
21357 not rely on @code{HAVE_RESTARTABLE_SYSCALLS}, since nowadays whether a
21358 system call is restartable is a dynamic issue, not a configuration-time
21359 issue.
21360 @end defmac
21362 @defmac AC_RETSIGTYPE
21363 @acindex{RETSIGTYPE}
21364 Replaced by @code{AC_TYPE_SIGNAL} (@pxref{AC_TYPE_SIGNAL}), which itself
21365 is obsolete when assuming C89 or better.
21366 @end defmac
21368 @defmac AC_RSH
21369 @acindex{RSH}
21370 Removed because of limited usefulness.
21371 @end defmac
21373 @defmac AC_SCO_INTL
21374 @acindex{SCO_INTL}
21375 @ovindex LIBS
21376 If on SCO Unix, add @option{-lintl} to output variable @code{LIBS}.  This
21377 macro used to do this:
21379 @example
21380 AC_CHECK_LIB([intl], [strftime], [LIBS="-lintl $LIBS"])
21381 @end example
21383 @noindent
21384 Now it just calls @code{AC_FUNC_STRFTIME} instead (@pxref{AC_FUNC_STRFTIME}).
21385 @end defmac
21387 @defmac AC_SETVBUF_REVERSED
21388 @acindex{SETVBUF_REVERSED}
21389 Replaced by
21390 @example
21391 AC_FUNC_SETVBUF_REVERSED
21392 @end example
21393 @noindent
21394 @xref{AC_FUNC_SETVBUF_REVERSED}.
21395 @end defmac
21397 @defmac AC_SET_MAKE
21398 @acindex{SET_MAKE}
21399 Replaced by @code{AC_PROG_MAKE_SET} (@pxref{AC_PROG_MAKE_SET}).
21400 @end defmac
21402 @defmac AC_SIZEOF_TYPE
21403 @acindex{SIZEOF_TYPE}
21404 Replaced by @code{AC_CHECK_SIZEOF} (@pxref{AC_CHECK_SIZEOF}).
21405 @end defmac
21407 @defmac AC_SIZE_T
21408 @acindex{SIZE_T}
21409 Replaced by @code{AC_TYPE_SIZE_T} (@pxref{AC_TYPE_SIZE_T}).
21410 @end defmac
21412 @defmac AC_STAT_MACROS_BROKEN
21413 @acindex{STAT_MACROS_BROKEN}
21414 Replaced by @code{AC_HEADER_STAT} (@pxref{AC_HEADER_STAT}).
21415 @end defmac
21417 @defmac AC_STDC_HEADERS
21418 @acindex{STDC_HEADERS}
21419 Replaced by @code{AC_HEADER_STDC} (@pxref{AC_HEADER_STDC}).
21420 @end defmac
21422 @defmac AC_STRCOLL
21423 @acindex{STRCOLL}
21424 Replaced by @code{AC_FUNC_STRCOLL} (@pxref{AC_FUNC_STRCOLL}).
21425 @end defmac
21427 @defmac AC_STRUCT_ST_BLKSIZE
21428 @acindex{STRUCT_ST_BLKSIZE}
21429 @cvindex HAVE_STRUCT_STAT_ST_BLKSIZE
21430 @cvindex HAVE_ST_BLKSIZE
21431 If @code{struct stat} contains an @code{st_blksize} member, define
21432 @code{HAVE_STRUCT_STAT_ST_BLKSIZE}.  The former name,
21433 @code{HAVE_ST_BLKSIZE} is to be avoided, as its support will cease in
21434 the future.  This macro is obsoleted, and should be replaced by
21436 @example
21437 AC_CHECK_MEMBERS([struct stat.st_blksize])
21438 @end example
21439 @noindent
21440 @xref{AC_CHECK_MEMBERS}.
21441 @end defmac
21443 @defmac AC_STRUCT_ST_RDEV
21444 @acindex{STRUCT_ST_RDEV}
21445 @cvindex HAVE_ST_RDEV
21446 @cvindex HAVE_STRUCT_STAT_ST_RDEV
21447 If @code{struct stat} contains an @code{st_rdev} member, define
21448 @code{HAVE_STRUCT_STAT_ST_RDEV}.  The former name for this macro,
21449 @code{HAVE_ST_RDEV}, is to be avoided as it will cease to be supported
21450 in the future.  Actually, even the new macro is obsolete and should be
21451 replaced by:
21452 @example
21453 AC_CHECK_MEMBERS([struct stat.st_rdev])
21454 @end example
21455 @noindent
21456 @xref{AC_CHECK_MEMBERS}.
21457 @end defmac
21459 @defmac AC_ST_BLKSIZE
21460 @acindex{ST_BLKSIZE}
21461 Replaced by @code{AC_CHECK_MEMBERS} (@pxref{AC_CHECK_MEMBERS}).
21462 @end defmac
21464 @defmac AC_ST_BLOCKS
21465 @acindex{ST_BLOCKS}
21466 Replaced by @code{AC_STRUCT_ST_BLOCKS} (@pxref{AC_STRUCT_ST_BLOCKS}).
21467 @end defmac
21469 @defmac AC_ST_RDEV
21470 @acindex{ST_RDEV}
21471 Replaced by @code{AC_CHECK_MEMBERS} (@pxref{AC_CHECK_MEMBERS}).
21472 @end defmac
21474 @defmac AC_SYS_RESTARTABLE_SYSCALLS
21475 @acindex{SYS_RESTARTABLE_SYSCALLS}
21476 @cvindex HAVE_RESTARTABLE_SYSCALLS
21477 If the system automatically restarts a system call that is interrupted
21478 by a signal, define @code{HAVE_RESTARTABLE_SYSCALLS}.  This macro does
21479 not check whether system calls are restarted in general---it checks whether a
21480 signal handler installed with @code{signal} (but not @code{sigaction})
21481 causes system calls to be restarted.  It does not check whether system calls
21482 can be restarted when interrupted by signals that have no handler.
21484 These days portable programs should use @code{sigaction} with
21485 @code{SA_RESTART} if they want restartable system calls.  They should
21486 not rely on @code{HAVE_RESTARTABLE_SYSCALLS}, since nowadays whether a
21487 system call is restartable is a dynamic issue, not a configuration-time
21488 issue.
21489 @end defmac
21491 @defmac AC_SYS_SIGLIST_DECLARED
21492 @acindex{SYS_SIGLIST_DECLARED}
21493 This macro was renamed @code{AC_DECL_SYS_SIGLIST}.  However, even that
21494 name is obsolete, as the same functionality is now acheived via
21495 @code{AC_CHECK_DECLS} (@pxref{AC_CHECK_DECLS}).
21496 @end defmac
21498 @defmac AC_TEST_CPP
21499 @acindex{TEST_CPP}
21500 This macro was renamed @code{AC_TRY_CPP}, which in turn was replaced by
21501 @code{AC_PREPROC_IFELSE} (@pxref{AC_PREPROC_IFELSE}).
21502 @end defmac
21504 @defmac AC_TEST_PROGRAM
21505 @acindex{TEST_PROGRAM}
21506 This macro was renamed @code{AC_TRY_RUN}, which in turn was replaced by
21507 @code{AC_RUN_IFELSE} (@pxref{AC_RUN_IFELSE}).
21508 @end defmac
21510 @defmac AC_TIMEZONE
21511 @acindex{TIMEZONE}
21512 Replaced by @code{AC_STRUCT_TIMEZONE} (@pxref{AC_STRUCT_TIMEZONE}).
21513 @end defmac
21515 @defmac AC_TIME_WITH_SYS_TIME
21516 @acindex{TIME_WITH_SYS_TIME}
21517 Replaced by @code{AC_HEADER_TIME} (@pxref{AC_HEADER_TIME}).
21518 @end defmac
21520 @defmac AC_TRY_COMPILE (@var{includes}, @var{function-body}, @
21521   @ovar{action-if-true}, @ovar{action-if-false})
21522 @acindex{TRY_COMPILE}
21523 Same as:
21525 @example
21526 AC_COMPILE_IFELSE(
21527   [AC_LANG_PROGRAM([[@var{includes}]],
21528      [[@var{function-body}]])],
21529   [@var{action-if-true}],
21530   [@var{action-if-false}])
21531 @end example
21533 @noindent
21534 @xref{Running the Compiler}.
21536 This macro double quotes both @var{includes} and @var{function-body}.
21538 For C and C++, @var{includes} is any @code{#include} statements needed
21539 by the code in @var{function-body} (@var{includes} is ignored if
21540 the currently selected language is Fortran or Fortran 77).  The compiler
21541 and compilation flags are determined by the current language
21542 (@pxref{Language Choice}).
21543 @end defmac
21545 @defmac AC_TRY_CPP (@var{input}, @ovar{action-if-true}, @ovar{action-if-false})
21546 @acindex{TRY_CPP}
21547 Same as:
21549 @example
21550 AC_PREPROC_IFELSE(
21551   [AC_LANG_SOURCE([[@var{input}]])],
21552   [@var{action-if-true}],
21553   [@var{action-if-false}])
21554 @end example
21556 @noindent
21557 @xref{Running the Preprocessor}.
21559 This macro double quotes the @var{input}.
21560 @end defmac
21562 @defmac AC_TRY_LINK (@var{includes}, @var{function-body}, @
21563   @ovar{action-if-true}, @ovar{action-if-false})
21564 @acindex{TRY_LINK}
21565 Same as:
21567 @example
21568 AC_LINK_IFELSE(
21569   [AC_LANG_PROGRAM([[@var{includes}]],
21570      [[@var{function-body}]])],
21571   [@var{action-if-true}],
21572   [@var{action-if-false}])
21573 @end example
21575 @noindent
21576 @xref{Running the Compiler}.
21578 This macro double quotes both @var{includes} and @var{function-body}.
21580 Depending on the current language (@pxref{Language Choice}), create a
21581 test program to see whether a function whose body consists of
21582 @var{function-body} can be compiled and linked.  If the file compiles
21583 and links successfully, run shell commands @var{action-if-found},
21584 otherwise run @var{action-if-not-found}.
21586 This macro double quotes both @var{includes} and @var{function-body}.
21588 For C and C++, @var{includes} is any @code{#include} statements needed
21589 by the code in @var{function-body} (@var{includes} is ignored if
21590 the currently selected language is Fortran or Fortran 77).  The compiler
21591 and compilation flags are determined by the current language
21592 (@pxref{Language Choice}), and in addition @code{LDFLAGS} and
21593 @code{LIBS} are used for linking.
21594 @end defmac
21596 @defmac AC_TRY_LINK_FUNC (@var{function}, @ovar{action-if-found}, @
21597   @ovar{action-if-not-found})
21598 @acindex{TRY_LINK_FUNC}
21599 This macro is equivalent to
21600 @example
21601 AC_LINK_IFELSE([AC_LANG_CALL([], [@var{function}])],
21602   [@var{action-if-found}], [@var{action-if-not-found}])
21603 @end example
21604 @noindent
21605 @xref{AC_LINK_IFELSE}.
21606 @end defmac
21608 @defmac AC_TRY_RUN (@var{program}, @ovar{action-if-true}, @
21609   @ovar{action-if-false}, @ovar{action-if-cross-compiling})
21610 @acindex{TRY_RUN}
21611 Same as:
21613 @example
21614 AC_RUN_IFELSE(
21615   [AC_LANG_SOURCE([[@var{program}]])],
21616   [@var{action-if-true}],
21617   [@var{action-if-false}],
21618   [@var{action-if-cross-compiling}])
21619 @end example
21621 @noindent
21622 @xref{Runtime}.
21623 @end defmac
21625 @anchor{AC_TYPE_SIGNAL}
21626 @defmac AC_TYPE_SIGNAL
21627 @acindex{TYPE_SIGNAL}
21628 @cvindex RETSIGTYPE
21629 @hdrindex{signal.h}
21630 If @file{signal.h} declares @code{signal} as returning a pointer to a
21631 function returning @code{void}, define @code{RETSIGTYPE} to be
21632 @code{void}; otherwise, define it to be @code{int}.  These days, it is
21633 portable to assume C89, and that signal handlers return @code{void},
21634 without needing to use this macro or @code{RETSIGTYPE}.
21636 When targetting older K&R C, it is possible to define signal handlers as
21637 returning type @code{RETSIGTYPE}, and omit a return statement:
21639 @example
21640 @group
21641 RETSIGTYPE
21642 hup_handler ()
21644 @dots{}
21646 @end group
21647 @end example
21648 @end defmac
21650 @defmac AC_UID_T
21651 @acindex{UID_T}
21652 Replaced by @code{AC_TYPE_UID_T} (@pxref{AC_TYPE_UID_T}).
21653 @end defmac
21655 @defmac AC_UNISTD_H
21656 @acindex{UNISTD_H}
21657 Same as @samp{AC_CHECK_HEADERS([unistd.h])} (@pxref{AC_CHECK_HEADERS}).
21658 @end defmac
21660 @defmac AC_USG
21661 @acindex{USG}
21662 @cvindex USG
21663 Define @code{USG} if the @acronym{BSD} string functions are defined in
21664 @file{strings.h}.  You should no longer depend upon @code{USG}, but on
21665 @code{HAVE_STRING_H}; see @ref{Standard Symbols}.
21666 @end defmac
21668 @defmac AC_UTIME_NULL
21669 @acindex{UTIME_NULL}
21670 Replaced by @code{AC_FUNC_UTIME_NULL} (@pxref{AC_FUNC_UTIME_NULL}).
21671 @end defmac
21673 @defmac AC_VALIDATE_CACHED_SYSTEM_TUPLE (@ovar{cmd})
21674 @acindex{VALIDATE_CACHED_SYSTEM_TUPLE}
21675 If the cache file is inconsistent with the current host, target and
21676 build system types, it used to execute @var{cmd} or print a default
21677 error message.  This is now handled by default.
21678 @end defmac
21680 @defmac AC_VERBOSE (@var{result-description})
21681 @acindex{VERBOSE}
21682 Replaced by @code{AC_MSG_RESULT} (@pxref{AC_MSG_RESULT}).
21683 @end defmac
21685 @defmac AC_VFORK
21686 @acindex{VFORK}
21687 Replaced by @code{AC_FUNC_FORK} (@pxref{AC_FUNC_FORK}).
21688 @end defmac
21690 @defmac AC_VPRINTF
21691 @acindex{VPRINTF}
21692 Replaced by @code{AC_FUNC_VPRINTF} (@pxref{AC_FUNC_VPRINTF}).
21693 @end defmac
21695 @defmac AC_WAIT3
21696 @acindex{WAIT3}
21697 This macro was renamed @code{AC_FUNC_WAIT3}.  However, these days
21698 portable programs should use @code{waitpid}, not @code{wait3}, as
21699 @code{wait3} has been removed from Posix.
21700 @end defmac
21702 @defmac AC_WARN
21703 @acindex{WARN}
21704 Replaced by @code{AC_MSG_WARN} (@pxref{AC_MSG_WARN}).
21705 @end defmac
21707 @defmac AC_WITH (@var{package}, @var{action-if-given}, @
21708   @ovar{action-if-not-given})
21709 @acindex{WITH}
21710 This is an obsolete version of @code{AC_ARG_WITH} that does not
21711 support providing a help string (@pxref{AC_ARG_WITH}).
21712 @end defmac
21714 @defmac AC_WORDS_BIGENDIAN
21715 @acindex{WORDS_BIGENDIAN}
21716 Replaced by @code{AC_C_BIGENDIAN} (@pxref{AC_C_BIGENDIAN}).
21717 @end defmac
21719 @defmac AC_XENIX_DIR
21720 @acindex{XENIX_DIR}
21721 @ovindex LIBS
21722 This macro used to add @option{-lx} to output variable @code{LIBS} if on
21723 Xenix.  Also, if @file{dirent.h} is being checked for, added
21724 @option{-ldir} to @code{LIBS}.  Now it is merely an alias of
21725 @code{AC_HEADER_DIRENT} instead, plus some code to detect whether
21726 running @sc{xenix} on which you should not depend:
21728 @example
21729 AC_MSG_CHECKING([for Xenix])
21730 AC_EGREP_CPP([yes],
21731 [#if defined M_XENIX && !defined M_UNIX
21732   yes
21733 #endif],
21734              [AC_MSG_RESULT([yes]); XENIX=yes],
21735              [AC_MSG_RESULT([no]); XENIX=])
21736 @end example
21737 @noindent
21738 Don't use this macro, the dignified means to check the nature of the
21739 host is using @code{AC_CANONICAL_HOST} (@pxref{Canonicalizing}).
21740 @end defmac
21742 @defmac AC_YYTEXT_POINTER
21743 @acindex{YYTEXT_POINTER}
21744 This macro was renamed @code{AC_DECL_YYTEXT}, which in turn was
21745 integrated into @code{AC_PROG_LEX} (@pxref{AC_PROG_LEX}).
21746 @end defmac
21748 @node Autoconf 1
21749 @section Upgrading From Version 1
21750 @cindex Upgrading autoconf
21751 @cindex Autoconf upgrading
21753 Autoconf version 2 is mostly backward compatible with version 1.
21754 However, it introduces better ways to do some things, and doesn't
21755 support some of the ugly things in version 1.  So, depending on how
21756 sophisticated your @file{configure.ac} files are, you might have to do
21757 some manual work in order to upgrade to version 2.  This chapter points
21758 out some problems to watch for when upgrading.  Also, perhaps your
21759 @command{configure} scripts could benefit from some of the new features in
21760 version 2; the changes are summarized in the file @file{NEWS} in the
21761 Autoconf distribution.
21763 @menu
21764 * Changed File Names::          Files you might rename
21765 * Changed Makefiles::           New things to put in @file{Makefile.in}
21766 * Changed Macros::              Macro calls you might replace
21767 * Changed Results::             Changes in how to check test results
21768 * Changed Macro Writing::       Better ways to write your own macros
21769 @end menu
21771 @node Changed File Names
21772 @subsection Changed File Names
21774 If you have an @file{aclocal.m4} installed with Autoconf (as opposed to
21775 in a particular package's source directory), you must rename it to
21776 @file{acsite.m4}.  @xref{autoconf Invocation}.
21778 If you distribute @file{install.sh} with your package, rename it to
21779 @file{install-sh} so @command{make} builtin rules don't inadvertently
21780 create a file called @file{install} from it.  @code{AC_PROG_INSTALL}
21781 looks for the script under both names, but it is best to use the new name.
21783 If you were using @file{config.h.top}, @file{config.h.bot}, or
21784 @file{acconfig.h}, you still can, but you have less clutter if you
21785 use the @code{AH_} macros.  @xref{Autoheader Macros}.
21787 @node Changed Makefiles
21788 @subsection Changed Makefiles
21790 Add @samp{@@CFLAGS@@}, @samp{@@CPPFLAGS@@}, and @samp{@@LDFLAGS@@} in
21791 your @file{Makefile.in} files, so they can take advantage of the values
21792 of those variables in the environment when @command{configure} is run.
21793 Doing this isn't necessary, but it's a convenience for users.
21795 Also add @samp{@@configure_input@@} in a comment to each input file for
21796 @code{AC_OUTPUT}, so that the output files contain a comment saying
21797 they were produced by @command{configure}.  Automatically selecting the
21798 right comment syntax for all the kinds of files that people call
21799 @code{AC_OUTPUT} on became too much work.
21801 Add @file{config.log} and @file{config.cache} to the list of files you
21802 remove in @code{distclean} targets.
21804 If you have the following in @file{Makefile.in}:
21806 @example
21807 prefix = /usr/local
21808 exec_prefix = $(prefix)
21809 @end example
21811 @noindent
21812 you must change it to:
21814 @example
21815 prefix = @@prefix@@
21816 exec_prefix = @@exec_prefix@@
21817 @end example
21819 @noindent
21820 The old behavior of replacing those variables without @samp{@@}
21821 characters around them has been removed.
21823 @node Changed Macros
21824 @subsection Changed Macros
21826 Many of the macros were renamed in Autoconf version 2.  You can still
21827 use the old names, but the new ones are clearer, and it's easier to find
21828 the documentation for them.  @xref{Obsolete Macros}, for a table showing the
21829 new names for the old macros.  Use the @command{autoupdate} program to
21830 convert your @file{configure.ac} to using the new macro names.
21831 @xref{autoupdate Invocation}.
21833 Some macros have been superseded by similar ones that do the job better,
21834 but are not call-compatible.  If you get warnings about calling obsolete
21835 macros while running @command{autoconf}, you may safely ignore them, but
21836 your @command{configure} script generally works better if you follow
21837 the advice that is printed about what to replace the obsolete macros with.  In
21838 particular, the mechanism for reporting the results of tests has
21839 changed.  If you were using @command{echo} or @code{AC_VERBOSE} (perhaps
21840 via @code{AC_COMPILE_CHECK}), your @command{configure} script's output
21841 looks better if you switch to @code{AC_MSG_CHECKING} and
21842 @code{AC_MSG_RESULT}.  @xref{Printing Messages}.  Those macros work best
21843 in conjunction with cache variables.  @xref{Caching Results}.
21847 @node Changed Results
21848 @subsection Changed Results
21850 If you were checking the results of previous tests by examining the
21851 shell variable @code{DEFS}, you need to switch to checking the values of
21852 the cache variables for those tests.  @code{DEFS} no longer exists while
21853 @command{configure} is running; it is only created when generating output
21854 files.  This difference from version 1 is because properly quoting the
21855 contents of that variable turned out to be too cumbersome and
21856 inefficient to do every time @code{AC_DEFINE} is called.  @xref{Cache
21857 Variable Names}.
21859 For example, here is a @file{configure.ac} fragment written for Autoconf
21860 version 1:
21862 @example
21863 AC_HAVE_FUNCS(syslog)
21864 case "$DEFS" in
21865 *-DHAVE_SYSLOG*) ;;
21866 *) # syslog is not in the default libraries.  See if it's in some other.
21867   saved_LIBS="$LIBS"
21868   for lib in bsd socket inet; do
21869     AC_CHECKING(for syslog in -l$lib)
21870     LIBS="-l$lib $saved_LIBS"
21871     AC_HAVE_FUNCS(syslog)
21872     case "$DEFS" in
21873     *-DHAVE_SYSLOG*) break ;;
21874     *) ;;
21875     esac
21876     LIBS="$saved_LIBS"
21877   done ;;
21878 esac
21879 @end example
21881 Here is a way to write it for version 2:
21883 @example
21884 AC_CHECK_FUNCS([syslog])
21885 if test "x$ac_cv_func_syslog" = xno; then
21886   # syslog is not in the default libraries.  See if it's in some other.
21887   for lib in bsd socket inet; do
21888     AC_CHECK_LIB([$lib], [syslog], [AC_DEFINE([HAVE_SYSLOG])
21889       LIBS="-l$lib $LIBS"; break])
21890   done
21892 @end example
21894 If you were working around bugs in @code{AC_DEFINE_UNQUOTED} by adding
21895 backslashes before quotes, you need to remove them.  It now works
21896 predictably, and does not treat quotes (except back quotes) specially.
21897 @xref{Setting Output Variables}.
21899 All of the Boolean shell variables set by Autoconf macros now use
21900 @samp{yes} for the true value.  Most of them use @samp{no} for false,
21901 though for backward compatibility some use the empty string instead.  If
21902 you were relying on a shell variable being set to something like 1 or
21903 @samp{t} for true, you need to change your tests.
21905 @node Changed Macro Writing
21906 @subsection Changed Macro Writing
21908 When defining your own macros, you should now use @code{AC_DEFUN}
21909 instead of @code{define}.  @code{AC_DEFUN} automatically calls
21910 @code{AC_PROVIDE} and ensures that macros called via @code{AC_REQUIRE}
21911 do not interrupt other macros, to prevent nested @samp{checking@dots{}}
21912 messages on the screen.  There's no actual harm in continuing to use the
21913 older way, but it's less convenient and attractive.  @xref{Macro
21914 Definitions}.
21916 You probably looked at the macros that came with Autoconf as a guide for
21917 how to do things.  It would be a good idea to take a look at the new
21918 versions of them, as the style is somewhat improved and they take
21919 advantage of some new features.
21921 If you were doing tricky things with undocumented Autoconf internals
21922 (macros, variables, diversions), check whether you need to change
21923 anything to account for changes that have been made.  Perhaps you can
21924 even use an officially supported technique in version 2 instead of
21925 kludging.  Or perhaps not.
21927 To speed up your locally written feature tests, add caching to them.
21928 See whether any of your tests are of general enough usefulness to
21929 encapsulate them into macros that you can share.
21932 @node Autoconf 2.13
21933 @section Upgrading From Version 2.13
21934 @cindex Upgrading autoconf
21935 @cindex Autoconf upgrading
21937 The introduction of the previous section (@pxref{Autoconf 1}) perfectly
21938 suits this section@enddots{}
21940 @quotation
21941 Autoconf version 2.50 is mostly backward compatible with version 2.13.
21942 However, it introduces better ways to do some things, and doesn't
21943 support some of the ugly things in version 2.13.  So, depending on how
21944 sophisticated your @file{configure.ac} files are, you might have to do
21945 some manual work in order to upgrade to version 2.50.  This chapter
21946 points out some problems to watch for when upgrading.  Also, perhaps
21947 your @command{configure} scripts could benefit from some of the new
21948 features in version 2.50; the changes are summarized in the file
21949 @file{NEWS} in the Autoconf distribution.
21950 @end quotation
21952 @menu
21953 * Changed Quotation::           Broken code which used to work
21954 * New Macros::                  Interaction with foreign macros
21955 * Hosts and Cross-Compilation::  Bugward compatibility kludges
21956 * AC_LIBOBJ vs LIBOBJS::        LIBOBJS is a forbidden token
21957 * AC_ACT_IFELSE vs AC_TRY_ACT::  A more generic scheme for testing sources
21958 @end menu
21960 @node Changed Quotation
21961 @subsection Changed Quotation
21963 The most important changes are invisible to you: the implementation of
21964 most macros have completely changed.  This allowed more factorization of
21965 the code, better error messages, a higher uniformity of the user's
21966 interface etc.  Unfortunately, as a side effect, some construct which
21967 used to (miraculously) work might break starting with Autoconf 2.50.
21968 The most common culprit is bad quotation.
21970 For instance, in the following example, the message is not properly
21971 quoted:
21973 @example
21974 AC_INIT
21975 AC_CHECK_HEADERS(foo.h, ,
21976   AC_MSG_ERROR(cannot find foo.h, bailing out))
21977 AC_OUTPUT
21978 @end example
21980 @noindent
21981 Autoconf 2.13 simply ignores it:
21983 @example
21984 $ @kbd{autoconf-2.13; ./configure --silent}
21985 creating cache ./config.cache
21986 configure: error: cannot find foo.h
21988 @end example
21990 @noindent
21991 while Autoconf 2.50 produces a broken @file{configure}:
21993 @example
21994 $ @kbd{autoconf-2.50; ./configure --silent}
21995 configure: error: cannot find foo.h
21996 ./configure: exit: bad non-numeric arg `bailing'
21997 ./configure: exit: bad non-numeric arg `bailing'
21999 @end example
22001 The message needs to be quoted, and the @code{AC_MSG_ERROR} invocation
22002 too!
22004 @example
22005 AC_INIT([Example], [1.0], [bug-example@@example.org])
22006 AC_CHECK_HEADERS([foo.h], [],
22007   [AC_MSG_ERROR([cannot find foo.h, bailing out])])
22008 AC_OUTPUT
22009 @end example
22011 Many many (and many more) Autoconf macros were lacking proper quotation,
22012 including no less than@dots{} @code{AC_DEFUN} itself!
22014 @example
22015 $ @kbd{cat configure.in}
22016 AC_DEFUN([AC_PROG_INSTALL],
22017 [# My own much better version
22019 AC_INIT
22020 AC_PROG_INSTALL
22021 AC_OUTPUT
22022 $ @kbd{autoconf-2.13}
22023 autoconf: Undefined macros:
22024 ***BUG in Autoconf--please report*** AC_FD_MSG
22025 ***BUG in Autoconf--please report*** AC_EPI
22026 configure.in:1:AC_DEFUN([AC_PROG_INSTALL],
22027 configure.in:5:AC_PROG_INSTALL
22028 $ @kbd{autoconf-2.50}
22030 @end example
22033 @node New Macros
22034 @subsection New Macros
22036 @cindex undefined macro
22037 @cindex @code{_m4_divert_diversion}
22039 While Autoconf was relatively dormant in the late 1990s, Automake
22040 provided Autoconf-like macros for a while.  Starting with Autoconf 2.50
22041 in 2001, Autoconf provided
22042 versions of these macros, integrated in the @code{AC_} namespace,
22043 instead of @code{AM_}.  But in order to ease the upgrading via
22044 @command{autoupdate}, bindings to such @code{AM_} macros are provided.
22046 Unfortunately older versions of Automake (e.g., Automake 1.4)
22047 did not quote the names of these macros.
22048 Therefore, when @command{m4} finds something like
22049 @samp{AC_DEFUN(AM_TYPE_PTRDIFF_T, @dots{})} in @file{aclocal.m4},
22050 @code{AM_TYPE_PTRDIFF_T} is
22051 expanded, replaced with its Autoconf definition.
22053 Fortunately Autoconf catches pre-@code{AC_INIT} expansions, and
22054 complains, in its own words:
22056 @example
22057 $ @kbd{cat configure.ac}
22058 AC_INIT([Example], [1.0], [bug-example@@example.org])
22059 AM_TYPE_PTRDIFF_T
22060 $ @kbd{aclocal-1.4}
22061 $ @kbd{autoconf}
22062 aclocal.m4:17: error: m4_defn: undefined macro: _m4_divert_diversion
22063 aclocal.m4:17: the top level
22064 autom4te: m4 failed with exit status: 1
22066 @end example
22068 Modern versions of Automake no longer define most of these
22069 macros, and properly quote the names of the remaining macros.
22070 If you must use an old Automake, do not depend upon macros from Automake
22071 as it is simply not its job
22072 to provide macros (but the one it requires itself):
22074 @example
22075 $ @kbd{cat configure.ac}
22076 AC_INIT([Example], [1.0], [bug-example@@example.org])
22077 AM_TYPE_PTRDIFF_T
22078 $ @kbd{rm aclocal.m4}
22079 $ @kbd{autoupdate}
22080 autoupdate: `configure.ac' is updated
22081 $ @kbd{cat configure.ac}
22082 AC_INIT([Example], [1.0], [bug-example@@example.org])
22083 AC_CHECK_TYPES([ptrdiff_t])
22084 $ @kbd{aclocal-1.4}
22085 $ @kbd{autoconf}
22087 @end example
22090 @node Hosts and Cross-Compilation
22091 @subsection Hosts and Cross-Compilation
22092 @cindex Cross compilation
22094 Based on the experience of compiler writers, and after long public
22095 debates, many aspects of the cross-compilation chain have changed:
22097 @itemize @minus
22098 @item
22099 the relationship between the build, host, and target architecture types,
22101 @item
22102 the command line interface for specifying them to @command{configure},
22104 @item
22105 the variables defined in @command{configure},
22107 @item
22108 the enabling of cross-compilation mode.
22109 @end itemize
22111 @sp 1
22113 The relationship between build, host, and target have been cleaned up:
22114 the chain of default is now simply: target defaults to host, host to
22115 build, and build to the result of @command{config.guess}.  Nevertheless,
22116 in order to ease the transition from 2.13 to 2.50, the following
22117 transition scheme is implemented.  @emph{Do not rely on it}, as it will
22118 be completely disabled in a couple of releases (we cannot keep it, as it
22119 proves to cause more problems than it cures).
22121 They all default to the result of running @command{config.guess}, unless
22122 you specify either @option{--build} or @option{--host}.  In this case,
22123 the default becomes the system type you specified.  If you specify both,
22124 and they're different, @command{configure} enters cross compilation
22125 mode, so it doesn't run any tests that require execution.
22127 Hint: if you mean to override the result of @command{config.guess},
22128 prefer @option{--build} over @option{--host}.  In the future,
22129 @option{--host} will not override the name of the build system type.
22130 Whenever you specify @option{--host}, be sure to specify @option{--build}
22131 too.
22133 @sp 1
22135 For backward compatibility, @command{configure} accepts a system
22136 type as an option by itself.  Such an option overrides the
22137 defaults for build, host, and target system types.  The following
22138 configure statement configures a cross toolchain that runs on
22139 Net@acronym{BSD}/alpha but generates code for @acronym{GNU} Hurd/sparc,
22140 which is also the build platform.
22142 @example
22143 ./configure --host=alpha-netbsd sparc-gnu
22144 @end example
22146 @sp 1
22148 In Autoconf 2.13 and before, the variables @code{build}, @code{host},
22149 and @code{target} had a different semantics before and after the
22150 invocation of @code{AC_CANONICAL_BUILD} etc.  Now, the argument of
22151 @option{--build} is strictly copied into @code{build_alias}, and is left
22152 empty otherwise.  After the @code{AC_CANONICAL_BUILD}, @code{build} is
22153 set to the canonicalized build type.  To ease the transition, before,
22154 its contents is the same as that of @code{build_alias}.  Do @emph{not}
22155 rely on this broken feature.
22157 For consistency with the backward compatibility scheme exposed above,
22158 when @option{--host} is specified but @option{--build} isn't, the build
22159 system is assumed to be the same as @option{--host}, and
22160 @samp{build_alias} is set to that value.  Eventually, this
22161 historically incorrect behavior will go away.
22163 @sp 1
22165 The former scheme to enable cross-compilation proved to cause more harm
22166 than good, in particular, it used to be triggered too easily, leaving
22167 regular end users puzzled in front of cryptic error messages.
22168 @command{configure} could even enter cross-compilation mode only
22169 because the compiler was not functional.  This is mainly because
22170 @command{configure} used to try to detect cross-compilation, instead of
22171 waiting for an explicit flag from the user.
22173 Now, @command{configure} enters cross-compilation mode if and only if
22174 @option{--host} is passed.
22176 That's the short documentation.  To ease the transition between 2.13 and
22177 its successors, a more complicated scheme is implemented.  @emph{Do not
22178 rely on the following}, as it will be removed in the near future.
22180 If you specify @option{--host}, but not @option{--build}, when
22181 @command{configure} performs the first compiler test it tries to run
22182 an executable produced by the compiler.  If the execution fails, it
22183 enters cross-compilation mode.  This is fragile.  Moreover, by the time
22184 the compiler test is performed, it may be too late to modify the
22185 build-system type: other tests may have already been performed.
22186 Therefore, whenever you specify @option{--host}, be sure to specify
22187 @option{--build} too.
22189 @example
22190 ./configure --build=i686-pc-linux-gnu --host=m68k-coff
22191 @end example
22193 @noindent
22194 enters cross-compilation mode.  The former interface, which
22195 consisted in setting the compiler to a cross-compiler without informing
22196 @command{configure} is obsolete.  For instance, @command{configure}
22197 fails if it can't run the code generated by the specified compiler if you
22198 configure as follows:
22200 @example
22201 ./configure CC=m68k-coff-gcc
22202 @end example
22205 @node AC_LIBOBJ vs LIBOBJS
22206 @subsection @code{AC_LIBOBJ} vs.@: @code{LIBOBJS}
22208 Up to Autoconf 2.13, the replacement of functions was triggered via the
22209 variable @code{LIBOBJS}.  Since Autoconf 2.50, the macro
22210 @code{AC_LIBOBJ} should be used instead (@pxref{Generic Functions}).
22211 Starting at Autoconf 2.53, the use of @code{LIBOBJS} is an error.
22213 This change is mandated by the unification of the @acronym{GNU} Build System
22214 components.  In particular, the various fragile techniques used to parse
22215 a @file{configure.ac} are all replaced with the use of traces.  As a
22216 consequence, any action must be traceable, which obsoletes critical
22217 variable assignments.  Fortunately, @code{LIBOBJS} was the only problem,
22218 and it can even be handled gracefully (read, ``without your having to
22219 change something'').
22221 There were two typical uses of @code{LIBOBJS}: asking for a replacement
22222 function, and adjusting @code{LIBOBJS} for Automake and/or Libtool.
22224 @sp 1
22226 As for function replacement, the fix is immediate: use
22227 @code{AC_LIBOBJ}.  For instance:
22229 @example
22230 LIBOBJS="$LIBOBJS fnmatch.o"
22231 LIBOBJS="$LIBOBJS malloc.$ac_objext"
22232 @end example
22234 @noindent
22235 should be replaced with:
22237 @example
22238 AC_LIBOBJ([fnmatch])
22239 AC_LIBOBJ([malloc])
22240 @end example
22242 @sp 1
22244 @ovindex LIBOBJDIR
22245 When used with Automake 1.10 or newer, a suitable value for
22246 @code{LIBOBJDIR} is set so that the @code{LIBOBJS} and @code{LTLIBOBJS}
22247 can be referenced from any @file{Makefile.am}.  Even without Automake,
22248 arranging for @code{LIBOBJDIR} to be set correctly enables
22249 referencing @code{LIBOBJS} and @code{LTLIBOBJS} in another directory.
22250 The @code{LIBOBJDIR} feature is experimental.
22253 @node AC_ACT_IFELSE vs AC_TRY_ACT
22254 @subsection @code{AC_@var{ACT}_IFELSE} vs.@: @code{AC_TRY_@var{ACT}}
22255 @c the anchor keeps the old node name, to try to avoid breaking links
22256 @anchor{AC_FOO_IFELSE vs AC_TRY_FOO}
22258 @acindex{@var{ACT}_IFELSE}
22259 @acindex{TRY_@var{ACT}}
22260 Since Autoconf 2.50, internal codes uses @code{AC_PREPROC_IFELSE},
22261 @code{AC_COMPILE_IFELSE}, @code{AC_LINK_IFELSE}, and
22262 @code{AC_RUN_IFELSE} on one hand and @code{AC_LANG_SOURCES},
22263 and @code{AC_LANG_PROGRAM} on the other hand instead of the deprecated
22264 @code{AC_TRY_CPP}, @code{AC_TRY_COMPILE}, @code{AC_TRY_LINK}, and
22265 @code{AC_TRY_RUN}.  The motivations where:
22266 @itemize @minus
22267 @item
22268 a more consistent interface: @code{AC_TRY_COMPILE} etc.@: were double
22269 quoting their arguments;
22271 @item
22272 the combinatoric explosion is solved by decomposing on the one hand the
22273 generation of sources, and on the other hand executing the program;
22275 @item
22276 this scheme helps supporting more languages than plain C and C++.
22277 @end itemize
22279 In addition to the change of syntax, the philosophy has changed too:
22280 while emphasis was put on speed at the expense of accuracy, today's
22281 Autoconf promotes accuracy of the testing framework at, ahem@dots{}, the
22282 expense of speed.
22285 As a perfect example of what is @emph{not} to be done, here is how to
22286 find out whether a header file contains a particular declaration, such
22287 as a typedef, a structure, a structure member, or a function.  Use
22288 @code{AC_EGREP_HEADER} instead of running @code{grep} directly on the
22289 header file; on some systems the symbol might be defined in another
22290 header file that the file you are checking includes.
22292 As a (bad) example, here is how you should not check for C preprocessor
22293 symbols, either defined by header files or predefined by the C
22294 preprocessor: using @code{AC_EGREP_CPP}:
22296 @example
22297 @group
22298 AC_EGREP_CPP(yes,
22299 [#ifdef _AIX
22300   yes
22301 #endif
22302 ], is_aix=yes, is_aix=no)
22303 @end group
22304 @end example
22306 The above example, properly written would (i) use
22307 @code{AC_LANG_PROGRAM}, and (ii) run the compiler:
22309 @example
22310 @group
22311 AC_COMPILE_IFELSE([AC_LANG_PROGRAM(
22312 [[#ifndef _AIX
22313  error: This isn't AIX!
22314 #endif
22315 ]])],
22316                    [is_aix=yes],
22317                    [is_aix=no])
22318 @end group
22319 @end example
22322 @c ============================= Generating Test Suites with Autotest
22324 @node Using Autotest
22325 @chapter Generating Test Suites with Autotest
22327 @cindex Autotest
22329 @display
22330 @strong{N.B.: This section describes a feature which is still
22331 stabilizing.  Although we believe that Autotest is useful as-is, this
22332 documentation describes an interface which might change in the future:
22333 do not depend upon Autotest without subscribing to the Autoconf mailing
22334 lists.}
22335 @end display
22337 It is paradoxical that portable projects depend on nonportable tools
22338 to run their test suite.  Autoconf by itself is the paragon of this
22339 problem: although it aims at perfectly portability, up to 2.13 its
22340 test suite was using Deja@acronym{GNU}, a rich and complex testing
22341 framework, but which is far from being standard on Posix systems.
22342 Worse yet, it was likely to be missing on the most fragile platforms,
22343 the very platforms that are most likely to torture Autoconf and
22344 exhibit deficiencies.
22346 To circumvent this problem, many package maintainers have developed their
22347 own testing framework, based on simple shell scripts whose sole outputs
22348 are exit status values describing whether the test succeeded.  Most of
22349 these tests share common patterns, and this can result in lots of
22350 duplicated code and tedious maintenance.
22352 Following exactly the same reasoning that yielded to the inception of
22353 Autoconf, Autotest provides a test suite generation framework, based on
22354 M4 macros building a portable shell script.  The suite itself is
22355 equipped with automatic logging and tracing facilities which greatly
22356 diminish the interaction with bug reporters, and simple timing reports.
22358 Autoconf itself has been using Autotest for years, and we do attest that
22359 it has considerably improved the strength of the test suite and the
22360 quality of bug reports.  Other projects are known to use some generation
22361 of Autotest, such as Bison, Free Recode, Free Wdiff, @acronym{GNU} Tar, each of
22362 them with different needs, and this usage has validated Autotest as a general
22363 testing framework.
22365 Nonetheless, compared to Deja@acronym{GNU}, Autotest is inadequate for
22366 interactive tool testing, which is probably its main limitation.
22368 @menu
22369 * Using an Autotest Test Suite::  Autotest and the user
22370 * Writing Testsuites::          Autotest macros
22371 * testsuite Invocation::        Running @command{testsuite} scripts
22372 * Making testsuite Scripts::    Using autom4te to create @command{testsuite}
22373 @end menu
22375 @node Using an Autotest Test Suite
22376 @section Using an Autotest Test Suite
22378 @menu
22379 * testsuite Scripts::           The concepts of Autotest
22380 * Autotest Logs::               Their contents
22381 @end menu
22383 @node testsuite Scripts
22384 @subsection @command{testsuite} Scripts
22386 @cindex @command{testsuite}
22388 Generating testing or validation suites using Autotest is rather easy.
22389 The whole validation suite is held in a file to be processed through
22390 @command{autom4te}, itself using @acronym{GNU} M4 under the scene, to
22391 produce a stand-alone Bourne shell script which then gets distributed.
22392 Neither @command{autom4te} nor @acronym{GNU} M4 are needed at
22393 the installer's end.
22395 @cindex test group
22396 Each test of the validation suite should be part of some test group.  A
22397 @dfn{test group} is a sequence of interwoven tests that ought to be
22398 executed together, usually because one test in the group creates data
22399 files than a later test in the same group needs to read.  Complex test
22400 groups make later debugging more tedious.  It is much better to
22401 keep only a few tests per test group.  Ideally there is only one test
22402 per test group.
22404 For all but the simplest packages, some file such as @file{testsuite.at}
22405 does not fully hold all test sources, as these are often easier to
22406 maintain in separate files.  Each of these separate files holds a single
22407 test group, or a sequence of test groups all addressing some common
22408 functionality in the package.  In such cases, @file{testsuite.at}
22409 merely initializes the validation suite, and sometimes does elementary
22410 health checking, before listing include statements for all other test
22411 files.  The special file @file{package.m4}, containing the
22412 identification of the package, is automatically included if found.
22414 A convenient alternative consists in moving all the global issues
22415 (local Autotest macros, elementary health checking, and @code{AT_INIT}
22416 invocation) into the file @code{local.at}, and making
22417 @file{testsuite.at} be a simple list of @code{m4_include} of sub test
22418 suites.  In such case, generating the whole test suite or pieces of it
22419 is only a matter of choosing the @command{autom4te} command line
22420 arguments.
22422 The validation scripts that Autotest produces are by convention called
22423 @command{testsuite}.  When run, @command{testsuite} executes each test
22424 group in turn, producing only one summary line per test to say if that
22425 particular test succeeded or failed.  At end of all tests, summarizing
22426 counters get printed.  One debugging directory is left for each test
22427 group which failed, if any: such directories are named
22428 @file{testsuite.dir/@var{nn}}, where @var{nn} is the sequence number of
22429 the test group, and they include:
22431 @itemize @bullet
22432 @item a debugging script named @file{run} which reruns the test in
22433 @dfn{debug mode} (@pxref{testsuite Invocation}).  The automatic generation
22434 of debugging scripts has the purpose of easing the chase for bugs.
22436 @item all the files created with @code{AT_DATA}
22438 @item a log of the run, named @file{testsuite.log}
22439 @end itemize
22441 In the ideal situation, none of the tests fail, and consequently no
22442 debugging directory is left behind for validation.
22444 It often happens in practice that individual tests in the validation
22445 suite need to get information coming out of the configuration process.
22446 Some of this information, common for all validation suites, is provided
22447 through the file @file{atconfig}, automatically created by
22448 @code{AC_CONFIG_TESTDIR}.  For configuration informations which your
22449 testing environment specifically needs, you might prepare an optional
22450 file named @file{atlocal.in}, instantiated by @code{AC_CONFIG_FILES}.
22451 The configuration process produces @file{atconfig} and @file{atlocal}
22452 out of these two input files, and these two produced files are
22453 automatically read by the @file{testsuite} script.
22455 Here is a diagram showing the relationship between files.
22457 @noindent
22458 Files used in preparing a software package for distribution:
22460 @example
22461                 [package.m4] -->.
22462                                  \
22463 subfile-1.at ->.  [local.at] ---->+
22464     ...         \                  \
22465 subfile-i.at ---->-- testsuite.at -->-- autom4te* -->testsuite
22466     ...         /
22467 subfile-n.at ->'
22468 @end example
22470 @noindent
22471 Files used in configuring a software package:
22473 @example
22474                                      .--> atconfig
22475                                     /
22476 [atlocal.in] -->  config.status* --<
22477                                     \
22478                                      `--> [atlocal]
22479 @end example
22481 @noindent
22482 Files created during the test suite execution:
22484 @example
22485 atconfig -->.                    .--> testsuite.log
22486              \                  /
22487               >-- testsuite* --<
22488              /                  \
22489 [atlocal] ->'                    `--> [testsuite.dir]
22490 @end example
22493 @node Autotest Logs
22494 @subsection Autotest Logs
22496 When run, the test suite creates a log file named after itself, e.g., a
22497 test suite named @command{testsuite} creates @file{testsuite.log}.  It
22498 contains a lot of information, usually more than maintainers actually
22499 need, but therefore most of the time it contains all that is needed:
22501 @table @asis
22502 @item command line arguments
22503 @c akim s/to consist in/to consist of/
22504 A bad but unfortunately widespread habit consists of
22505 setting environment variables before the command, such as in
22506 @samp{CC=my-home-grown-cc ./testsuite}.  The test suite does not
22507 know this change, hence (i) it cannot report it to you, and (ii)
22508 it cannot preserve the value of @code{CC} for subsequent runs.
22509 Autoconf faced exactly the same problem, and solved it by asking
22510 users to pass the variable definitions as command line arguments.
22511 Autotest requires this rule, too, but has no means to enforce it; the log
22512 then contains a trace of the variables that were changed by the user.
22514 @item @file{ChangeLog} excerpts
22515 The topmost lines of all the @file{ChangeLog} files found in the source
22516 hierarchy.  This is especially useful when bugs are reported against
22517 development versions of the package, since the version string does not
22518 provide sufficient information to know the exact state of the sources
22519 the user compiled.  Of course, this relies on the use of a
22520 @file{ChangeLog}.
22522 @item build machine
22523 Running a test suite in a cross-compile environment is not an easy task,
22524 since it would mean having the test suite run on a machine @var{build},
22525 while running programs on a machine @var{host}.  It is much simpler to
22526 run both the test suite and the programs on @var{host}, but then, from
22527 the point of view of the test suite, there remains a single environment,
22528 @var{host} = @var{build}.  The log contains relevant information on the
22529 state of the build machine, including some important environment
22530 variables.
22531 @c FIXME: How about having an M4sh macro to say `hey, log the value
22532 @c of `@dots{}'?  This would help both Autoconf and Autotest.
22534 @item tested programs
22535 The absolute file name and answers to @option{--version} of the tested
22536 programs (see @ref{Writing Testsuites}, @code{AT_TESTED}).
22538 @item configuration log
22539 The contents of @file{config.log}, as created by @command{configure},
22540 are appended.  It contains the configuration flags and a detailed report
22541 on the configuration itself.
22542 @end table
22545 @node Writing Testsuites
22546 @section Writing @file{testsuite.at}
22548 The @file{testsuite.at} is a Bourne shell script making use of special
22549 Autotest M4 macros.  It often contains a call to @code{AT_INIT} near
22550 its beginning followed by one call to @code{m4_include} per source file
22551 for tests.  Each such included file, or the remainder of
22552 @file{testsuite.at} if include files are not used, contain a sequence of
22553 test groups.  Each test group begins with a call to @code{AT_SETUP},
22554 then an arbitrary number of shell commands or calls to @code{AT_CHECK},
22555 and then completes with a call to @code{AT_CLEANUP}.  Multiple test
22556 groups can be categorized by a call to @code{AT_BANNER}.
22558 All of the public Autotest macros have all-uppercase names in the
22559 namespace @samp{^AT_} to prevent them from accidentally conflicting with
22560 other text; Autoconf also reserves the namespace @samp{^_AT_} for
22561 internal macros.  All shell variables used in the testsuite for internal
22562 purposes have mostly-lowercase names starting with @samp{at_}.  Autotest
22563 also uses here-document delimiters in the namespace @samp{^_AT[A-Z]}, and
22564 makes use of the file system namespace @samp{^at-}.
22566 Since Autoconf is built on top of M4sugar (@pxref{Programming in
22567 M4sugar}) and M4sh (@pxref{Programming in M4sh}), you must also be aware
22568 of those namespaces (@samp{^_?\(m4\|AS\)_}).  In general, you
22569 @emph{should not use} the namespace of a package that does not own the
22570 macro or shell code you are writing.
22572 @defmac AT_INIT (@ovar{name})
22573 @atindex{INIT}
22574 @c FIXME: Not clear, plus duplication of the information.
22575 Initialize Autotest.  Giving a @var{name} to the test suite is
22576 encouraged if your package includes several test suites.  Before this
22577 macro is called, @code{AT_PACKAGE_STRING} and
22578 @code{AT_PACKAGE_BUGREPORT} must be defined, which are used to display
22579 information about the testsuite to the user.  Typically, these macros
22580 are provided by a file @file{package.m4} built by @command{make}
22581 (@pxref{Making testsuite Scripts}), in order to inherit the package
22582 name, version, and bug reporting address from @file{configure.ac}.
22583 @end defmac
22585 @defmac AT_COPYRIGHT (@var{copyright-notice})
22586 @atindex{COPYRIGHT}
22587 @cindex Copyright Notice
22588 State that, in addition to the Free Software Foundation's copyright on
22589 the Autotest macros, parts of your test suite are covered by
22590 @var{copyright-notice}.
22592 The @var{copyright-notice} shows up in both the head of
22593 @command{testsuite} and in @samp{testsuite --version}.
22594 @end defmac
22596 @defmac AT_TESTED (@var{executables})
22597 @atindex{TESTED}
22598 Log the file name and answer to @option{--version} of each program in
22599 space-separated list @var{executables}.  Several invocations register
22600 new executables, in other words, don't fear registering one program
22601 several times.
22602 @end defmac
22604 Autotest test suites rely on @env{PATH} to find the tested program.
22605 This avoids the need to generate absolute names of the various tools, and
22606 makes it possible to test installed programs.  Therefore, knowing which
22607 programs are being exercised is crucial to understanding problems in
22608 the test suite itself, or its occasional misuses.  It is a good idea to
22609 also subscribe foreign programs you depend upon, to avoid incompatible
22610 diagnostics.
22612 @sp 1
22614 @defmac AT_BANNER (@var{test-category-name})
22615 @atindex{BANNER}
22616 This macro identifies the start of a category of related test groups.
22617 When the resulting @file{testsuite} is invoked with more than one test
22618 group to run, its output will include a banner containing
22619 @var{test-category-name} prior to any tests run from that category.  The
22620 banner should be no more than about 40 or 50 characters.  A blank banner
22621 will not print, effectively ending a category and letting subsequent
22622 test groups behave as though they are uncategorized when run in
22623 isolation.
22624 @end defmac
22626 @defmac AT_SETUP (@var{test-group-name})
22627 @atindex{SETUP}
22628 This macro starts a group of related tests, all to be executed in the
22629 same subshell.  It accepts a single argument, which holds a few words
22630 (no more than about 30 or 40 characters) quickly describing the purpose
22631 of the test group being started.  @var{test-group-name} must not expand
22632 to unbalanced quotes, although quadrigraphs can be used.
22633 @end defmac
22635 @defmac AT_KEYWORDS (@var{keywords})
22636 @atindex{KEYWORDS}
22637 Associate the space-separated list of @var{keywords} to the enclosing
22638 test group.  This makes it possible to run ``slices'' of the test suite.
22639 For instance, if some of your test groups exercise some @samp{foo}
22640 feature, then using @samp{AT_KEYWORDS(foo)} lets you run
22641 @samp{./testsuite -k foo} to run exclusively these test groups.  The
22642 @var{title} of the test group is automatically recorded to
22643 @code{AT_KEYWORDS}.
22645 Several invocations within a test group accumulate new keywords.  In
22646 other words, don't fear registering the same keyword several times in a
22647 test group.
22648 @end defmac
22650 @defmac AT_CAPTURE_FILE (@var{file})
22651 @atindex{CAPTURE_FILE}
22652 If the current test group fails, log the contents of @var{file}.
22653 Several identical calls within one test group have no additional effect.
22654 @end defmac
22656 @defmac AT_XFAIL_IF (@var{shell-condition})
22657 @atindex{XFAIL_IF}
22658 Determine whether the test is expected to fail because it is a known
22659 bug (for unsupported features, you should skip the test).
22660 @var{shell-condition} is a shell expression such as a @code{test}
22661 command; you can instantiate this macro many times from within the
22662 same test group, and one of the conditions is enough to turn
22663 the test into an expected failure.
22664 @end defmac
22666 @defmac AT_CLEANUP
22667 @atindex{CLEANUP}
22668 End the current test group.
22669 @end defmac
22671 @sp 1
22673 @defmac AT_DATA (@var{file}, @var{contents})
22674 @atindex{DATA}
22675 Initialize an input data @var{file} with given @var{contents}.  Of
22676 course, the @var{contents} have to be properly quoted between square
22677 brackets to protect against included commas or spurious M4
22678 expansion.  The contents must end with an end of line.  @var{file} must
22679 be a single shell word that expands into a single file name.
22680 @end defmac
22682 @defmac AT_CHECK (@var{commands}, @dvar{status, 0}, @ovar{stdout}, @
22683   @ovar{stderr}, @ovar{run-if-fail}, @ovar{run-if-pass})
22684 @defmacx AT_CHECK_UNQUOTED (@var{commands}, @dvar{status, 0}, @ovar{stdout}, @
22685   @ovar{stderr}, @ovar{run-if-fail}, @ovar{run-if-pass})
22686 @atindex{CHECK}
22687 @atindex{CHECK_UNQUOTED}
22688 Execute a test by performing given shell @var{commands}.  @var{commands}
22689 is output as-is, so shell expansions are honored.  These commands
22690 should normally exit with @var{status}, while producing expected
22691 @var{stdout} and @var{stderr} contents.  If @var{commands} exit with
22692 unexpected status 77, then the rest of the test group is skipped.  If
22693 @var{commands} exit with unexpected status 99, then the test group is
22694 immediately failed.  Otherwise, if this test
22695 fails, run shell commands @var{run-if-fail} or, if this test passes, run shell
22696 commands @var{run-if-pass}.
22698 This macro must be invoked in between @code{AT_SETUP} and @code{AT_CLEANUP}.
22700 If @var{status} is the literal @samp{ignore}, then the corresponding
22701 exit status is not checked, except for the special cases of 77 (skip)
22702 and 99 (hard failure).  The existence of hard failures allows one to
22703 mark a test as an expected failure with @code{AT_XFAIL_IF} because a
22704 feature has not yet been implemented, but to still distinguish between
22705 gracefully handling the missing feature and dumping core.  A hard
22706 failure also inhibits post-test actions in @var{run-if-fail}.
22708 If the value of the @var{stdout} or @var{stderr} parameter is one of the
22709 literals in the following table, then the test treats the output
22710 according to the rules of that literal.  Otherwise, the value of the
22711 parameter is treated as text that must exactly match the output given by
22712 @var{commands} on standard out and standard error (including an empty
22713 parameter for no output); any differences are captured in the testsuite
22714 log and the test is failed.  The difference between @code{AT_CHECK} and
22715 @code{AT_CHECK_UNQUOTED} is that only the latter performs shell variable
22716 expansion (@samp{$}), command substitution (@samp{`}), and backslash
22717 escaping (@samp{\}) on comparison text given in the @var{stdout} and
22718 @var{stderr} arguments; if the text includes a trailing newline, this
22719 would be the same as if it were specified via an unquoted
22720 here-document.  (However, there is no difference in the interpretation
22721 of @var{commands}).
22723 @table @samp
22724 @item ignore
22725 The content of the output is ignored, but still captured in the test
22726 group log (if the testsuite is run with option @option{-v}, the test
22727 group log is displayed as the test is run; if the test group later
22728 fails, the test group log is also copied into the overall testsuite
22729 log).  This action is valid for both @var{stdout} and @var{stderr}.
22731 @item ignore-nolog
22732 The content of the output is ignored, and nothing is captured in the log
22733 files.  If @var{commands} are likely to produce binary output (including
22734 long lines) or large amounts of output, then logging the output can make
22735 it harder to locate details related to subsequent tests within the
22736 group, and could potentially corrupt terminal display of a user running
22737 @command{testsuite -v}.
22739 @item stdout
22740 For the @var{stdout} parameter, capture the content of standard output
22741 to both the file @file{stdout} and the test group log.  Subsequent
22742 commands in the test group can then post-process the file.  This action
22743 is often used when it is desired to use @command{grep} to look for a
22744 substring in the output, or when the output must be post-processed to
22745 normalize error messages into a common form.
22747 @item stderr
22748 Like @samp{stdout}, except that it only works for the @var{stderr}
22749 parameter, and the standard error capture file will be named
22750 @file{stderr}.
22752 @item stdout-nolog
22753 @itemx stderr-nolog
22754 Like @samp{stdout} or @samp{stderr}, except that the captured output is
22755 not duplicated into the test group log.  This action is particularly
22756 useful for an intermediate check that produces large amounts of data,
22757 which will be followed by another check that filters down to the
22758 relevant data, as it makes it easier to locate details in the log.
22760 @item expout
22761 For the @var{stdout} parameter, compare standard output contents with
22762 the previously created file @file{expout}, and list any differences in
22763 the testsuite log.
22765 @item experr
22766 Like @samp{expout}, except that it only works for the @var{stderr}
22767 parameter, and the standard error contents are compared with
22768 @file{experr}.
22769 @end table
22770 @end defmac
22773 @node testsuite Invocation
22774 @section Running @command{testsuite} Scripts
22775 @cindex @command{testsuite}
22777 Autotest test suites support the following arguments:
22779 @table @option
22780 @item --help
22781 @itemx -h
22782 Display the list of options and exit successfully.
22784 @item --version
22785 @itemx -V
22786 Display the version of the test suite and exit successfully.
22788 @item --directory=@var{dir}
22789 @itemx -C @var{dir}
22790 Change the current directory to @var{dir} before creating any files.
22791 Useful for running the testsuite in a subdirectory from a top-level
22792 Makefile.
22794 @item --jobs@r{[}=@var{n}@r{]}
22795 @itemx -j@ovar{n}
22796 Run @var{n} tests in parallel, if possible.  If @var{n} is not given,
22797 run all given tests in parallel.  Note that there should be no space
22798 before the argument to @option{-j}, as @option{-j @var{number}} denotes
22799 the separate arguments @option{-j} and @option{@var{number}}, see below.
22801 In parallel mode, the standard input device of the testsuite script is
22802 not available to commands inside a test group.  Furthermore, banner
22803 lines are not printed, and the summary line for each test group is
22804 output after the test group completes.  Summary lines may appear
22805 unordered.  If verbose and trace output are enabled (see below), they
22806 may appear intermixed from concurrently running tests.
22808 Parallel mode requires the @command{mkfifo} command to work, and will be
22809 silently disabled otherwise.
22811 @item --clean
22812 @itemx -c
22813 Remove all the files the test suite might have created and exit.  Meant
22814 for @code{clean} Make targets.
22816 @item --list
22817 @itemx -l
22818 List all the tests (or only the selection), including their possible
22819 keywords.
22820 @end table
22822 @sp 1
22824 By default all tests are performed (or described with
22825 @option{--list}) in the default environment first silently, then
22826 verbosely, but the environment, set of tests, and verbosity level can be
22827 tuned:
22829 @table @samp
22830 @item @var{variable}=@var{value}
22831 Set the environment @var{variable} to @var{value}.  Use this rather
22832 than @samp{FOO=foo ./testsuite} as debugging scripts would then run in a
22833 different environment.
22835 @cindex @code{AUTOTEST_PATH}
22836 The variable @code{AUTOTEST_PATH} specifies the testing path to prepend
22837 to @env{PATH}.  Relative directory names (not starting with
22838 @samp{/}) are considered to be relative to the top level of the
22839 package being built.  All directories are made absolute, first
22840 starting from the top level @emph{build} tree, then from the
22841 @emph{source} tree.  For instance @samp{./testsuite
22842 AUTOTEST_PATH=tests:bin} for a @file{/src/foo-1.0} source package built
22843 in @file{/tmp/foo} results in @samp{/tmp/foo/tests:/tmp/foo/bin} and
22844 then @samp{/src/foo-1.0/tests:/src/foo-1.0/bin} being prepended to
22845 @env{PATH}.
22847 @item @var{number}
22848 @itemx @var{number}-@var{number}
22849 @itemx @var{number}-
22850 @itemx -@var{number}
22851 Add the corresponding test groups, with obvious semantics, to the
22852 selection.
22854 @item --keywords=@var{keywords}
22855 @itemx -k @var{keywords}
22856 Add to the selection the test groups with title or keywords (arguments
22857 to @code{AT_SETUP} or @code{AT_KEYWORDS}) that match @emph{all} keywords
22858 of the comma separated list @var{keywords}, case-insensitively.  Use
22859 @samp{!} immediately before the keyword to invert the selection for this
22860 keyword.  By default, the keywords match whole words; enclose them in
22861 @samp{.*} to also match parts of words.
22863 For example, running
22865 @example
22866 @kbd{./testsuite -k 'autoupdate,.*FUNC.*'}
22867 @end example
22869 @noindent
22870 selects all tests tagged @samp{autoupdate} @emph{and} with tags
22871 containing @samp{FUNC} (as in @samp{AC_CHECK_FUNC}, @samp{AC_FUNC_ALLOCA},
22872 etc.), while
22874 @example
22875 @kbd{./testsuite -k '!autoupdate' -k '.*FUNC.*'}
22876 @end example
22878 @noindent
22879 selects all tests not tagged @samp{autoupdate} @emph{or} with tags
22880 containing @samp{FUNC}.
22882 @item --errexit
22883 @itemx -e
22884 If any test fails, immediately abort testing.  It implies
22885 @option{--debug}: post test group clean up, and top-level logging
22886 are inhibited.  This option is meant for the full test
22887 suite, it is not really useful for generated debugging scripts.
22888 If the testsuite is run in parallel mode using @option{--jobs},
22889 then concurrently running tests will finish before exiting.
22891 @item --verbose
22892 @itemx -v
22893 Force more verbosity in the detailed output of what is being done.  This
22894 is the default for debugging scripts.
22896 @item --debug
22897 @itemx -d
22898 Do not remove the files after a test group was performed ---but they are
22899 still removed @emph{before}, therefore using this option is sane when
22900 running several test groups.  Create debugging scripts.  Do not
22901 overwrite the top-level
22902 log (in order to preserve supposedly existing full log file).  This is
22903 the default for debugging scripts, but it can also be useful to debug
22904 the testsuite itself.
22906 @item --trace
22907 @itemx -x
22908 Trigger shell tracing of the test groups.
22909 @end table
22912 @node Making testsuite Scripts
22913 @section Making @command{testsuite} Scripts
22915 For putting Autotest into movement, you need some configuration and
22916 makefile machinery.  We recommend, at least if your package uses deep or
22917 shallow hierarchies, that you use @file{tests/} as the name of the
22918 directory holding all your tests and their makefile.  Here is a
22919 check list of things to do.
22921 @itemize @minus
22923 @item
22924 @cindex @file{package.m4}
22925 @atindex{PACKAGE_STRING}
22926 @atindex{PACKAGE_BUGREPORT}
22927 @atindex{PACKAGE_NAME}
22928 @atindex{PACKAGE_TARNAME}
22929 @atindex{PACKAGE_VERSION}
22930 @atindex{PACKAGE_URL}
22931 Make sure to create the file @file{package.m4}, which defines the
22932 identity of the package.  It must define @code{AT_PACKAGE_STRING}, the
22933 full signature of the package, and @code{AT_PACKAGE_BUGREPORT}, the
22934 address to which bug reports should be sent.  For sake of completeness,
22935 we suggest that you also define @code{AT_PACKAGE_NAME},
22936 @code{AT_PACKAGE_TARNAME}, @code{AT_PACKAGE_VERSION}, and
22937 @code{AT_PACKAGE_URL}.
22938 @xref{Initializing configure}, for a description of these variables.
22939 Be sure to distribute @file{package.m4} and to put it into the source
22940 hierarchy: the test suite ought to be shipped!  See below for an example
22941 @file{Makefile} excerpt.
22943 @item
22944 Invoke @code{AC_CONFIG_TESTDIR}.
22946 @defmac AC_CONFIG_TESTDIR (@var{directory}, @dvar{test-path, directory})
22947 @acindex{CONFIG_TESTDIR}
22948 An Autotest test suite is to be configured in @var{directory}.  This
22949 macro requires the instantiation of @file{@var{directory}/atconfig} from
22950 @file{@var{directory}/atconfig.in}, and sets the default
22951 @code{AUTOTEST_PATH} to @var{test-path} (@pxref{testsuite Invocation}).
22952 @end defmac
22954 @item
22955 Still within @file{configure.ac}, as appropriate, ensure that some
22956 @code{AC_CONFIG_FILES} command includes substitution for
22957 @file{tests/atlocal}.
22959 @item
22960 The appropriate @file{Makefile} should be modified so the validation in
22961 your package is triggered by @samp{make check}.  An example is provided
22962 below.
22963 @end itemize
22965 With Automake, here is a minimal example for inclusion in
22966 @file{tests/Makefile.am}, in order to link @samp{make check} with a
22967 validation suite.
22969 @example
22970 # The `:;' works around a Bash 3.2 bug when the output is not writeable.
22971 $(srcdir)/package.m4: $(top_srcdir)/configure.ac
22972         :;@{ \
22973           echo '# Signature of the current package.' && \
22974           echo 'm4_define([AT_PACKAGE_NAME],' && \
22975           echo '  [@@PACKAGE_NAME@@])' && \
22976           echo 'm4_define([AT_PACKAGE_TARNAME],' && \
22977           echo '  [@@PACKAGE_TARNAME@@])' && \
22978           echo 'm4_define([AT_PACKAGE_VERSION],' && \
22979           echo '  [@@PACKAGE_VERSION@@])' && \
22980           echo 'm4_define([AT_PACKAGE_STRING],' && \
22981           echo '  [@@PACKAGE_STRING@@])' && \
22982           echo 'm4_define([AT_PACKAGE_BUGREPORT],' && \
22983           echo '  [@@PACKAGE_BUGREPORT@@])'; \
22984           echo 'm4_define([AT_PACKAGE_URL],' && \
22985           echo '  [@@PACKAGE_URL@@])'; \
22986         @} >'$(srcdir)/package.m4'
22988 EXTRA_DIST = testsuite.at $(srcdir)/package.m4 $(TESTSUITE) atlocal.in
22989 TESTSUITE = $(srcdir)/testsuite
22991 check-local: atconfig atlocal $(TESTSUITE)
22992         $(SHELL) '$(TESTSUITE)' $(TESTSUITEFLAGS)
22994 installcheck-local: atconfig atlocal $(TESTSUITE)
22995         $(SHELL) '$(TESTSUITE)' AUTOTEST_PATH='$(bindir)' \
22996           $(TESTSUITEFLAGS)
22998 clean-local:
22999         test ! -f '$(TESTSUITE)' || \
23000          $(SHELL) '$(TESTSUITE)' --clean
23002 AUTOM4TE = $(SHELL) $(srcdir)/build-aux/missing --run autom4te
23003 AUTOTEST = $(AUTOM4TE) --language=autotest
23004 $(TESTSUITE): $(srcdir)/testsuite.at $(srcdir)/package.m4
23005         $(AUTOTEST) -I '$(srcdir)' -o $@@.tmp $@@.at
23006         mv $@@.tmp $@@
23007 @end example
23009 Note that the built testsuite is distributed; this is necessary because
23010 users might not have Autoconf installed, and thus would not be able to
23011 rebuild it.  Likewise, the use of @file{missing} provides the user with
23012 a nicer error message if they modify a source file to the testsuite, and
23013 accidentally trigger the rebuild rules.
23015 You might want to list explicitly the dependencies, i.e., the list of
23016 the files @file{testsuite.at} includes.
23018 If you don't use Automake, you should include the above example in
23019 @file{tests/@/Makefile.in}, along with additional lines inspired from
23020 the following:
23022 @example
23023 subdir = tests
23025 atconfig: $(top_builddir)/config.status
23026         cd $(top_builddir) && \
23027            $(SHELL) ./config.status $(subdir)/$@@
23029 atlocal: $(srcdir)/atlocal.in $(top_builddir)/config.status
23030         cd $(top_builddir) && \
23031            $(SHELL) ./config.status $(subdir)/$@@
23032 @end example
23034 @noindent
23035 and manage to have @code{$(EXTRA_DIST)} distributed.  You will also want
23036 to distribute the file @file{build-aux/@/missing} from the Automake
23037 project; a copy of this file resides in the Autoconf source.
23039 With all this in place, and if you have not initialized @samp{TESTSUITEFLAGS}
23040 within your makefile, you can fine-tune test suite execution with this
23041 variable, for example:
23043 @example
23044 make check TESTSUITEFLAGS='-v -d -x 75 -k AC_PROG_CC CFLAGS=-g'
23045 @end example
23049 @c =============================== Frequent Autoconf Questions, with answers
23051 @node FAQ
23052 @chapter Frequent Autoconf Questions, with answers
23054 Several questions about Autoconf come up occasionally.  Here some of them
23055 are addressed.
23057 @menu
23058 * Distributing::                Distributing @command{configure} scripts
23059 * Why GNU M4::                  Why not use the standard M4?
23060 * Bootstrapping::               Autoconf and @acronym{GNU} M4 require each other?
23061 * Why Not Imake::               Why @acronym{GNU} uses @command{configure} instead of Imake
23062 * Defining Directories::        Passing @code{datadir} to program
23063 * Autom4te Cache::              What is it?  Can I remove it?
23064 * Present But Cannot Be Compiled::  Compiler and Preprocessor Disagree
23065 * Expanded Before Required::    Expanded Before Required
23066 @end menu
23068 @node Distributing
23069 @section Distributing @command{configure} Scripts
23070 @cindex License
23072 @display
23073 What are the restrictions on distributing @command{configure}
23074 scripts that Autoconf generates?  How does that affect my
23075 programs that use them?
23076 @end display
23078 There are no restrictions on how the configuration scripts that Autoconf
23079 produces may be distributed or used.  In Autoconf version 1, they were
23080 covered by the @acronym{GNU} General Public License.  We still encourage
23081 software authors to distribute their work under terms like those of the
23082 @acronym{GPL}, but doing so is not required to use Autoconf.
23084 Of the other files that might be used with @command{configure},
23085 @file{config.h.in} is under whatever copyright you use for your
23086 @file{configure.ac}.  @file{config.sub} and @file{config.guess} have an
23087 exception to the @acronym{GPL} when they are used with an Autoconf-generated
23088 @command{configure} script, which permits you to distribute them under the
23089 same terms as the rest of your package.  @file{install-sh} is from the X
23090 Consortium and is not copyrighted.
23092 @node Why GNU M4
23093 @section Why Require @acronym{GNU} M4?
23095 @display
23096 Why does Autoconf require @acronym{GNU} M4?
23097 @end display
23099 Many M4 implementations have hard-coded limitations on the size and
23100 number of macros that Autoconf exceeds.  They also lack several
23101 builtin macros that it would be difficult to get along without in a
23102 sophisticated application like Autoconf, including:
23104 @example
23105 m4_builtin
23106 m4_indir
23107 m4_bpatsubst
23108 __file__
23109 __line__
23110 @end example
23112 Autoconf requires version 1.4.5 or later of @acronym{GNU} M4.
23114 Since only software maintainers need to use Autoconf, and since @acronym{GNU}
23115 M4 is simple to configure and install, it seems reasonable to require
23116 @acronym{GNU} M4 to be installed also.  Many maintainers of @acronym{GNU} and
23117 other free software already have most of the @acronym{GNU} utilities
23118 installed, since they prefer them.
23120 @node Bootstrapping
23121 @section How Can I Bootstrap?
23122 @cindex Bootstrap
23124 @display
23125 If Autoconf requires @acronym{GNU} M4 and @acronym{GNU} M4 has an Autoconf
23126 @command{configure} script, how do I bootstrap?  It seems like a chicken
23127 and egg problem!
23128 @end display
23130 This is a misunderstanding.  Although @acronym{GNU} M4 does come with a
23131 @command{configure} script produced by Autoconf, Autoconf is not required
23132 in order to run the script and install @acronym{GNU} M4.  Autoconf is only
23133 required if you want to change the M4 @command{configure} script, which few
23134 people have to do (mainly its maintainer).
23136 @node Why Not Imake
23137 @section Why Not Imake?
23138 @cindex Imake
23140 @display
23141 Why not use Imake instead of @command{configure} scripts?
23142 @end display
23144 Several people have written addressing this question, so I include
23145 adaptations of their explanations here.
23147 The following answer is based on one written by Richard Pixley:
23149 @quotation
23150 Autoconf generated scripts frequently work on machines that it has
23151 never been set up to handle before.  That is, it does a good job of
23152 inferring a configuration for a new system.  Imake cannot do this.
23154 Imake uses a common database of host specific data.  For X11, this makes
23155 sense because the distribution is made as a collection of tools, by one
23156 central authority who has control over the database.
23158 @acronym{GNU} tools are not released this way.  Each @acronym{GNU} tool has a
23159 maintainer; these maintainers are scattered across the world.  Using a
23160 common database would be a maintenance nightmare.  Autoconf may appear
23161 to be this kind of database, but in fact it is not.  Instead of listing
23162 host dependencies, it lists program requirements.
23164 If you view the @acronym{GNU} suite as a collection of native tools, then the
23165 problems are similar.  But the @acronym{GNU} development tools can be
23166 configured as cross tools in almost any host+target permutation.  All of
23167 these configurations can be installed concurrently.  They can even be
23168 configured to share host independent files across hosts.  Imake doesn't
23169 address these issues.
23171 Imake templates are a form of standardization.  The @acronym{GNU} coding
23172 standards address the same issues without necessarily imposing the same
23173 restrictions.
23174 @end quotation
23177 Here is some further explanation, written by Per Bothner:
23179 @quotation
23180 One of the advantages of Imake is that it easy to generate large
23181 makefiles using the @samp{#include} and macro mechanisms of @command{cpp}.
23182 However, @code{cpp} is not programmable: it has limited conditional
23183 facilities, and no looping.  And @code{cpp} cannot inspect its
23184 environment.
23186 All of these problems are solved by using @code{sh} instead of
23187 @code{cpp}.  The shell is fully programmable, has macro substitution,
23188 can execute (or source) other shell scripts, and can inspect its
23189 environment.
23190 @end quotation
23193 Paul Eggert elaborates more:
23195 @quotation
23196 With Autoconf, installers need not assume that Imake itself is already
23197 installed and working well.  This may not seem like much of an advantage
23198 to people who are accustomed to Imake.  But on many hosts Imake is not
23199 installed or the default installation is not working well, and requiring
23200 Imake to install a package hinders the acceptance of that package on
23201 those hosts.  For example, the Imake template and configuration files
23202 might not be installed properly on a host, or the Imake build procedure
23203 might wrongly assume that all source files are in one big directory
23204 tree, or the Imake configuration might assume one compiler whereas the
23205 package or the installer needs to use another, or there might be a
23206 version mismatch between the Imake expected by the package and the Imake
23207 supported by the host.  These problems are much rarer with Autoconf,
23208 where each package comes with its own independent configuration
23209 processor.
23211 Also, Imake often suffers from unexpected interactions between
23212 @command{make} and the installer's C preprocessor.  The fundamental problem
23213 here is that the C preprocessor was designed to preprocess C programs,
23214 not makefiles.  This is much less of a problem with Autoconf,
23215 which uses the general-purpose preprocessor M4, and where the
23216 package's author (rather than the installer) does the preprocessing in a
23217 standard way.
23218 @end quotation
23221 Finally, Mark Eichin notes:
23223 @quotation
23224 Imake isn't all that extensible, either.  In order to add new features to
23225 Imake, you need to provide your own project template, and duplicate most
23226 of the features of the existing one.  This means that for a sophisticated
23227 project, using the vendor-provided Imake templates fails to provide any
23228 leverage---since they don't cover anything that your own project needs
23229 (unless it is an X11 program).
23231 On the other side, though:
23233 The one advantage that Imake has over @command{configure}:
23234 @file{Imakefile} files tend to be much shorter (likewise, less redundant)
23235 than @file{Makefile.in} files.  There is a fix to this, however---at least
23236 for the Kerberos V5 tree, we've modified things to call in common
23237 @file{post.in} and @file{pre.in} makefile fragments for the
23238 entire tree.  This means that a lot of common things don't have to be
23239 duplicated, even though they normally are in @command{configure} setups.
23240 @end quotation
23243 @node Defining Directories
23244 @section How Do I @code{#define} Installation Directories?
23246 @display
23247 My program needs library files, installed in @code{datadir} and
23248 similar.  If I use
23250 @example
23251 AC_DEFINE_UNQUOTED([DATADIR], [$datadir],
23252   [Define to the read-only architecture-independent
23253    data directory.])
23254 @end example
23256 @noindent
23257 I get
23259 @example
23260 #define DATADIR "$@{prefix@}/share"
23261 @end example
23262 @end display
23264 As already explained, this behavior is on purpose, mandated by the
23265 @acronym{GNU} Coding Standards, see @ref{Installation Directory
23266 Variables}.  There are several means to achieve a similar goal:
23268 @itemize @minus
23269 @item
23270 Do not use @code{AC_DEFINE} but use your makefile to pass the
23271 actual value of @code{datadir} via compilation flags.
23272 @xref{Installation Directory Variables}, for the details.
23274 @item
23275 This solution can be simplified when compiling a program: you may either
23276 extend the @code{CPPFLAGS}:
23278 @example
23279 CPPFLAGS = -DDATADIR='"$(datadir)"' @@CPPFLAGS@@
23280 @end example
23282 @noindent
23283 If you are using Automake, you should use @code{AM_CPPFLAGS} instead:
23285 @example
23286 AM_CPPFLAGS = -DDATADIR='"$(datadir)"'
23287 @end example
23289 @noindent
23290 Alternatively, create a dedicated header file:
23292 @example
23293 DISTCLEANFILES = myprog-paths.h
23294 myprog-paths.h: Makefile
23295         echo '#define DATADIR "$(datadir)"' >$@@
23296 @end example
23298 @item
23299 Use @code{AC_DEFINE} but have @command{configure} compute the literal
23300 value of @code{datadir} and others.  Many people have wrapped macros to
23301 automate this task; for an example, see the macro @code{AC_DEFINE_DIR} from
23302 the @uref{http://@/autoconf-archive@/.cryp.to/, Autoconf Macro
23303 Archive}.
23305 This solution does not conform to the @acronym{GNU} Coding Standards.
23307 @item
23308 Note that all the previous solutions hard wire the absolute name of
23309 these directories in the executables, which is not a good property.  You
23310 may try to compute the names relative to @code{prefix}, and try to
23311 find @code{prefix} at runtime, this way your package is relocatable.
23312 @end itemize
23315 @node Autom4te Cache
23316 @section What is @file{autom4te.cache}?
23318 @display
23319 What is this directory @file{autom4te.cache}?  Can I safely remove it?
23320 @end display
23322 In the @acronym{GNU} Build System, @file{configure.ac} plays a central
23323 role and is read by many tools: @command{autoconf} to create
23324 @file{configure}, @command{autoheader} to create @file{config.h.in},
23325 @command{automake} to create @file{Makefile.in}, @command{autoscan} to
23326 check the completeness of @file{configure.ac}, @command{autoreconf} to
23327 check the @acronym{GNU} Build System components that are used.  To
23328 ``read @file{configure.ac}'' actually means to compile it with M4,
23329 which can be a long process for complex @file{configure.ac}.
23331 This is why all these tools, instead of running directly M4, invoke
23332 @command{autom4te} (@pxref{autom4te Invocation}) which, while answering to
23333 a specific demand, stores additional information in
23334 @file{autom4te.cache} for future runs.  For instance, if you run
23335 @command{autoconf}, behind the scenes, @command{autom4te} also
23336 stores information for the other tools, so that when you invoke
23337 @command{autoheader} or @command{automake} etc., reprocessing
23338 @file{configure.ac} is not needed.  The speed up is frequently 30%,
23339 and is increasing with the size of @file{configure.ac}.
23341 But it is and remains being simply a cache: you can safely remove it.
23343 @sp 1
23345 @display
23346 Can I permanently get rid of it?
23347 @end display
23349 The creation of this cache can be disabled from
23350 @file{~/.autom4te.cfg}, see @ref{Customizing autom4te}, for more
23351 details.  You should be aware that disabling the cache slows down the
23352 Autoconf test suite by 40%.  The more @acronym{GNU} Build System
23353 components are used, the more the cache is useful; for instance
23354 running @samp{autoreconf -f} on the Core Utilities is twice slower without
23355 the cache @emph{although @option{--force} implies that the cache is
23356 not fully exploited}, and eight times slower than without
23357 @option{--force}.
23360 @node Present But Cannot Be Compiled
23361 @section Header Present But Cannot Be Compiled
23363 The most important guideline to bear in mind when checking for
23364 features is to mimic as much as possible the intended use.
23365 Unfortunately, old versions of @code{AC_CHECK_HEADER} and
23366 @code{AC_CHECK_HEADERS} failed to follow this idea, and called
23367 the preprocessor, instead of the compiler, to check for headers.  As a
23368 result, incompatibilities between headers went unnoticed during
23369 configuration, and maintainers finally had to deal with this issue
23370 elsewhere.
23372 The transition began with Autoconf 2.56.  As of Autoconf 2.64 both
23373 checks are performed, and @command{configure} complains loudly if the
23374 compiler and the preprocessor do not agree.  However, only the compiler
23375 result is considered.
23377 Consider the following example:
23379 @smallexample
23380 $ @kbd{cat number.h}
23381 typedef int number;
23382 $ @kbd{cat pi.h}
23383 const number pi = 3;
23384 $ @kbd{cat configure.ac}
23385 AC_INIT([Example], [1.0], [bug-example@@example.org])
23386 AC_CHECK_HEADERS([pi.h])
23387 $ @kbd{autoconf -Wall}
23388 $ @kbd{./configure}
23389 checking for gcc... gcc
23390 checking for C compiler default output file name... a.out
23391 checking whether the C compiler works... yes
23392 checking whether we are cross compiling... no
23393 checking for suffix of executables...
23394 checking for suffix of object files... o
23395 checking whether we are using the GNU C compiler... yes
23396 checking whether gcc accepts -g... yes
23397 checking for gcc option to accept ISO C89... none needed
23398 checking how to run the C preprocessor... gcc -E
23399 checking for grep that handles long lines and -e... grep
23400 checking for egrep... grep -E
23401 checking for ANSI C header files... yes
23402 checking for sys/types.h... yes
23403 checking for sys/stat.h... yes
23404 checking for stdlib.h... yes
23405 checking for string.h... yes
23406 checking for memory.h... yes
23407 checking for strings.h... yes
23408 checking for inttypes.h... yes
23409 checking for stdint.h... yes
23410 checking for unistd.h... yes
23411 checking pi.h usability... no
23412 checking pi.h presence... yes
23413 configure: WARNING: pi.h: present but cannot be compiled
23414 configure: WARNING: pi.h:     check for missing prerequisite headers?
23415 configure: WARNING: pi.h: see the Autoconf documentation
23416 configure: WARNING: pi.h:     section "Present But Cannot Be Compiled"
23417 configure: WARNING: pi.h: proceeding with the compiler's result
23418 configure: WARNING:     ## -------------------------------------- ##
23419 configure: WARNING:     ## Report this to bug-example@@example.org ##
23420 configure: WARNING:     ## -------------------------------------- ##
23421 checking for pi.h... yes
23422 @end smallexample
23424 @noindent
23425 The proper way the handle this case is using the fourth argument
23426 (@pxref{Generic Headers}):
23428 @example
23429 $ @kbd{cat configure.ac}
23430 AC_INIT([Example], [1.0], [bug-example@@example.org])
23431 AC_CHECK_HEADERS([number.h pi.h], [], [],
23432 [[#ifdef HAVE_NUMBER_H
23433 # include <number.h>
23434 #endif
23436 $ @kbd{autoconf -Wall}
23437 $ @kbd{./configure}
23438 checking for gcc... gcc
23439 checking for C compiler default output... a.out
23440 checking whether the C compiler works... yes
23441 checking whether we are cross compiling... no
23442 checking for suffix of executables...
23443 checking for suffix of object files... o
23444 checking whether we are using the GNU C compiler... yes
23445 checking whether gcc accepts -g... yes
23446 checking for gcc option to accept ANSI C... none needed
23447 checking for number.h... yes
23448 checking for pi.h... yes
23449 @end example
23451 See @ref{Particular Headers}, for a list of headers with their
23452 prerequisites.
23454 @node Expanded Before Required
23455 @section Expanded Before Required
23457 @cindex expanded before required
23458 Older versions of Autoconf silently built files with incorrect ordering
23459 between dependent macros if an outer macro first expanded, then later
23460 indirectly required, an inner macro.  Starting with Autoconf 2.64, this
23461 situation no longer generates out-of-order code, but results in
23462 duplicate output and a syntax warning:
23464 @example
23465 $ @kbd{cat configure.ac}
23466 @result{}AC_DEFUN([TESTA], [[echo in A
23467 @result{}if test -n "$SEEN_A" ; then echo duplicate ; fi
23468 @result{}SEEN_A=:]])
23469 @result{}AC_DEFUN([TESTB], [AC_REQUIRE([TESTA])[echo in B
23470 @result{}if test -z "$SEEN_A" ; then echo bug ; fi]])
23471 @result{}AC_DEFUN([TESTC], [AC_REQUIRE([TESTB])[echo in C]])
23472 @result{}AC_DEFUN([OUTER], [[echo in OUTER]
23473 @result{}TESTA
23474 @result{}TESTC])
23475 @result{}AC_INIT
23476 @result{}OUTER
23477 @result{}AC_OUTPUT
23478 $ @kbd{autoconf}
23479 @result{}configure.ac:11: warning: AC_REQUIRE:
23480 @result{} `TESTA' was expanded before it was required
23481 @result{}configure.ac:4: TESTB is expanded from...
23482 @result{}configure.ac:6: TESTC is expanded from...
23483 @result{}configure.ac:7: OUTER is expanded from...
23484 @result{}configure.ac:11: the top level
23485 @end example
23487 @noindent
23488 To avoid this warning, decide what purpose the macro in question serves.
23489 If it only needs to be expanded once (for example, if it provides
23490 initialization text used by later macros), then the simplest fix is to
23491 change the macro to be declared with @code{AC_DEFUN_ONCE}
23492 (@pxref{One-Shot Macros}), although this only works in Autoconf 2.64 and
23493 newer.  A more portable fix is to change all
23494 instances of direct calls to instead go through @code{AC_REQUIRE}
23495 (@pxref{Prerequisite Macros}).  If, instead, the macro is parameterized
23496 by arguments or by the current definition of other macros in the m4
23497 environment, then the macro should always be directly expanded instead
23498 of required.
23500 For another case study, consider this example trimmed down from an
23501 actual package.  Originally, the package contained shell code and
23502 multiple macro invocations at the top level of @file{configure.ac}:
23504 @example
23505 AC_DEFUN([FOO], [AC_COMPILE_IFELSE([@dots{}])])
23506 foobar=
23507 AC_PROG_CC
23509 @end example
23511 @noindent
23512 but that was getting complex, so the author wanted to offload some of
23513 the text into a new macro in another file included via
23514 @file{aclocal.m4}.  The na@"ive approach merely wraps the text in a new
23515 macro:
23517 @example
23518 AC_DEFUN([FOO], [AC_COMPILE_IFELSE([@dots{}])])
23519 AC_DEFUN([BAR], [
23520 foobar=
23521 AC_PROG_CC
23525 @end example
23527 @noindent
23528 With older versions of Autoconf, the setting of @samp{foobar=} occurs
23529 before the single compiler check, as the author intended.  But with
23530 Autoconf 2.64, this issues the ``expanded before it was required''
23531 warning for @code{AC_PROG_CC}, and outputs two copies of the compiler
23532 check, one before @samp{foobar=}, and one after.  To understand why this
23533 is happening, remember that the use of @code{AC_COMPILE_IFELSE} includes
23534 a call to @code{AC_REQUIRE([AC_PROG_CC])} under the hood.  According to
23535 the documented semantics of @code{AC_REQUIRE}, this means that
23536 @code{AC_PROG_CC} @emph{must} occur before the body of the outermost
23537 @code{AC_DEFUN}, which in this case is @code{BAR}, thus preceeding the
23538 use of @samp{foobar=}.  The older versions of Autoconf were broken with
23539 regards to the rules of @code{AC_REQUIRE}, which explains why the code
23540 changed from one over to two copies of @code{AC_PROG_CC} when upgrading
23541 autoconf.  In other words, the author was unknowingly relying on a bug
23542 exploit to get the desired results, and that exploit broke once the bug
23543 was fixed.
23545 So, what recourse does the author have, to restore their intended
23546 semantics of setting @samp{foobar=} prior to a single compiler check,
23547 regardless of whether Autoconf 2.63 or 2.64 is used?  One idea is to
23548 remember that only @code{AC_DEFUN} is impacted by @code{AC_REQUIRE};
23549 there is always the possibility of using the lower-level
23550 @code{m4_define}:
23552 @example
23553 AC_DEFUN([FOO], [AC_COMPILE_IFELSE([@dots{}])])
23554 m4_define([BAR], [
23555 foobar=
23556 AC_PROG_CC
23560 @end example
23562 @noindent
23563 This works great if everything is in the same file.  However, it does
23564 not help in the case where the author wants to have @command{aclocal}
23565 find the definition of @code{BAR} from its own file, since
23566 @command{aclocal} requires the use of @code{AC_DEFUN}.  In this case, a
23567 better fix is to recognize that if @code{BAR} also uses
23568 @code{AC_REQUIRE}, then there will no longer be direct expansion prior
23569 to a subsequent require.  Then, by creating yet another helper macro,
23570 the author can once again guarantee a single invocation of
23571 @code{AC_PROG_CC}, which will still occur after @code{foobar=}.  The
23572 author can also use @code{AC_BEFORE} to make sure no other macro
23573 appearing before @code{BAR} has triggered an unwanted expansion of
23574 @code{AC_PROG_CC}.
23576 @example
23577 AC_DEFUN([FOO], [AC_COMPILE_IFELSE([@dots{}])])
23578 AC_DEFUN([BEFORE_CC], [
23579 foobar=
23581 AC_DEFUN([BAR], [
23582 AC_BEFORE([$0], [AC_PROG_CC])dnl
23583 AC_REQUIRE([BEFORE_CC])dnl
23584 AC_REQUIRE([AC_PROG_CC])dnl
23588 @end example
23591 @c ===================================================== History of Autoconf.
23593 @node History
23594 @chapter History of Autoconf
23595 @cindex History of autoconf
23597 You may be wondering, Why was Autoconf originally written?  How did it
23598 get into its present form?  (Why does it look like gorilla spit?)  If
23599 you're not wondering, then this chapter contains no information useful
23600 to you, and you might as well skip it.  If you @emph{are} wondering,
23601 then let there be light@enddots{}
23603 @menu
23604 * Genesis::                     Prehistory and naming of @command{configure}
23605 * Exodus::                      The plagues of M4 and Perl
23606 * Leviticus::                   The priestly code of portability arrives
23607 * Numbers::                     Growth and contributors
23608 * Deuteronomy::                 Approaching the promises of easy configuration
23609 @end menu
23611 @node Genesis
23612 @section Genesis
23614 In June 1991 I was maintaining many of the @acronym{GNU} utilities for the
23615 Free Software Foundation.  As they were ported to more platforms and
23616 more programs were added, the number of @option{-D} options that users
23617 had to select in the makefile (around 20) became burdensome.
23618 Especially for me---I had to test each new release on a bunch of
23619 different systems.  So I wrote a little shell script to guess some of
23620 the correct settings for the fileutils package, and released it as part
23621 of fileutils 2.0.  That @command{configure} script worked well enough that
23622 the next month I adapted it (by hand) to create similar @command{configure}
23623 scripts for several other @acronym{GNU} utilities packages.  Brian Berliner
23624 also adapted one of my scripts for his @acronym{CVS} revision control system.
23626 Later that summer, I learned that Richard Stallman and Richard Pixley
23627 were developing similar scripts to use in the @acronym{GNU} compiler tools;
23628 so I adapted my @command{configure} scripts to support their evolving
23629 interface: using the file name @file{Makefile.in} as the templates;
23630 adding @samp{+srcdir}, the first option (of many); and creating
23631 @file{config.status} files.
23633 @node Exodus
23634 @section Exodus
23636 As I got feedback from users, I incorporated many improvements, using
23637 Emacs to search and replace, cut and paste, similar changes in each of
23638 the scripts.  As I adapted more @acronym{GNU} utilities packages to use
23639 @command{configure} scripts, updating them all by hand became impractical.
23640 Rich Murphey, the maintainer of the @acronym{GNU} graphics utilities, sent me
23641 mail saying that the @command{configure} scripts were great, and asking if
23642 I had a tool for generating them that I could send him.  No, I thought,
23643 but I should!  So I started to work out how to generate them.  And the
23644 journey from the slavery of hand-written @command{configure} scripts to the
23645 abundance and ease of Autoconf began.
23647 Cygnus @command{configure}, which was being developed at around that time,
23648 is table driven; it is meant to deal mainly with a discrete number of
23649 system types with a small number of mainly unguessable features (such as
23650 details of the object file format).  The automatic configuration system
23651 that Brian Fox had developed for Bash takes a similar approach.  For
23652 general use, it seems to me a hopeless cause to try to maintain an
23653 up-to-date database of which features each variant of each operating
23654 system has.  It's easier and more reliable to check for most features on
23655 the fly---especially on hybrid systems that people have hacked on
23656 locally or that have patches from vendors installed.
23658 I considered using an architecture similar to that of Cygnus
23659 @command{configure}, where there is a single @command{configure} script that
23660 reads pieces of @file{configure.in} when run.  But I didn't want to have
23661 to distribute all of the feature tests with every package, so I settled
23662 on having a different @command{configure} made from each
23663 @file{configure.in} by a preprocessor.  That approach also offered more
23664 control and flexibility.
23666 I looked briefly into using the Metaconfig package, by Larry Wall,
23667 Harlan Stenn, and Raphael Manfredi, but I decided not to for several
23668 reasons.  The @command{Configure} scripts it produces are interactive,
23669 which I find quite inconvenient; I didn't like the ways it checked for
23670 some features (such as library functions); I didn't know that it was
23671 still being maintained, and the @command{Configure} scripts I had
23672 seen didn't work on many modern systems (such as System V R4 and NeXT);
23673 it wasn't flexible in what it could do in response to a feature's
23674 presence or absence; I found it confusing to learn; and it was too big
23675 and complex for my needs (I didn't realize then how much Autoconf would
23676 eventually have to grow).
23678 I considered using Perl to generate my style of @command{configure}
23679 scripts, but decided that M4 was better suited to the job of simple
23680 textual substitutions: it gets in the way less, because output is
23681 implicit.  Plus, everyone already has it.  (Initially I didn't rely on
23682 the @acronym{GNU} extensions to M4.)  Also, some of my friends at the
23683 University of Maryland had recently been putting M4 front ends on
23684 several programs, including @code{tvtwm}, and I was interested in trying
23685 out a new language.
23687 @node Leviticus
23688 @section Leviticus
23690 Since my @command{configure} scripts determine the system's capabilities
23691 automatically, with no interactive user intervention, I decided to call
23692 the program that generates them Autoconfig.  But with a version number
23693 tacked on, that name would be too long for old Unix file systems,
23694 so I shortened it to Autoconf.
23696 In the fall of 1991 I called together a group of fellow questers after
23697 the Holy Grail of portability (er, that is, alpha testers) to give me
23698 feedback as I encapsulated pieces of my handwritten scripts in M4 macros
23699 and continued to add features and improve the techniques used in the
23700 checks.  Prominent among the testers were Fran@,{c}ois Pinard, who came up
23701 with the idea of making an Autoconf shell script to run M4
23702 and check for unresolved macro calls; Richard Pixley, who suggested
23703 running the compiler instead of searching the file system to find
23704 include files and symbols, for more accurate results; Karl Berry, who
23705 got Autoconf to configure @TeX{} and added the macro index to the
23706 documentation; and Ian Lance Taylor, who added support for creating a C
23707 header file as an alternative to putting @option{-D} options in a
23708 makefile, so he could use Autoconf for his @acronym{UUCP} package.
23709 The alpha testers cheerfully adjusted their files again and again as the
23710 names and calling conventions of the Autoconf macros changed from
23711 release to release.  They all contributed many specific checks, great
23712 ideas, and bug fixes.
23714 @node Numbers
23715 @section Numbers
23717 In July 1992, after months of alpha testing, I released Autoconf 1.0,
23718 and converted many @acronym{GNU} packages to use it.  I was surprised by how
23719 positive the reaction to it was.  More people started using it than I
23720 could keep track of, including people working on software that wasn't
23721 part of the @acronym{GNU} Project (such as TCL, FSP, and Kerberos V5).
23722 Autoconf continued to improve rapidly, as many people using the
23723 @command{configure} scripts reported problems they encountered.
23725 Autoconf turned out to be a good torture test for M4 implementations.
23726 Unix M4 started to dump core because of the length of the
23727 macros that Autoconf defined, and several bugs showed up in @acronym{GNU}
23728 M4 as well.  Eventually, we realized that we needed to use some
23729 features that only @acronym{GNU} M4 has.  4.3@acronym{BSD} M4, in
23730 particular, has an impoverished set of builtin macros; the System V
23731 version is better, but still doesn't provide everything we need.
23733 More development occurred as people put Autoconf under more stresses
23734 (and to uses I hadn't anticipated).  Karl Berry added checks for X11.
23735 david zuhn contributed C++ support.  Fran@,{c}ois Pinard made it diagnose
23736 invalid arguments.  Jim Blandy bravely coerced it into configuring
23737 @acronym{GNU} Emacs, laying the groundwork for several later improvements.
23738 Roland McGrath got it to configure the @acronym{GNU} C Library, wrote the
23739 @command{autoheader} script to automate the creation of C header file
23740 templates, and added a @option{--verbose} option to @command{configure}.
23741 Noah Friedman added the @option{--autoconf-dir} option and
23742 @code{AC_MACRODIR} environment variable.  (He also coined the term
23743 @dfn{autoconfiscate} to mean ``adapt a software package to use
23744 Autoconf''.)  Roland and Noah improved the quoting protection in
23745 @code{AC_DEFINE} and fixed many bugs, especially when I got sick of
23746 dealing with portability problems from February through June, 1993.
23748 @node Deuteronomy
23749 @section Deuteronomy
23751 A long wish list for major features had accumulated, and the effect of
23752 several years of patching by various people had left some residual
23753 cruft.  In April 1994, while working for Cygnus Support, I began a major
23754 revision of Autoconf.  I added most of the features of the Cygnus
23755 @command{configure} that Autoconf had lacked, largely by adapting the
23756 relevant parts of Cygnus @command{configure} with the help of david zuhn
23757 and Ken Raeburn.  These features include support for using
23758 @file{config.sub}, @file{config.guess}, @option{--host}, and
23759 @option{--target}; making links to files; and running @command{configure}
23760 scripts in subdirectories.  Adding these features enabled Ken to convert
23761 @acronym{GNU} @code{as}, and Rob Savoye to convert Deja@acronym{GNU}, to using
23762 Autoconf.
23764 I added more features in response to other peoples' requests.  Many
23765 people had asked for @command{configure} scripts to share the results of
23766 the checks between runs, because (particularly when configuring a large
23767 source tree, like Cygnus does) they were frustratingly slow.  Mike
23768 Haertel suggested adding site-specific initialization scripts.  People
23769 distributing software that had to unpack on MS-DOS asked for a way to
23770 override the @file{.in} extension on the file names, which produced file
23771 names like @file{config.h.in} containing two dots.  Jim Avera did an
23772 extensive examination of the problems with quoting in @code{AC_DEFINE}
23773 and @code{AC_SUBST}; his insights led to significant improvements.
23774 Richard Stallman asked that compiler output be sent to @file{config.log}
23775 instead of @file{/dev/null}, to help people debug the Emacs
23776 @command{configure} script.
23778 I made some other changes because of my dissatisfaction with the quality
23779 of the program.  I made the messages showing results of the checks less
23780 ambiguous, always printing a result.  I regularized the names of the
23781 macros and cleaned up coding style inconsistencies.  I added some
23782 auxiliary utilities that I had developed to help convert source code
23783 packages to use Autoconf.  With the help of Fran@,{c}ois Pinard, I made
23784 the macros not interrupt each others' messages.  (That feature revealed
23785 some performance bottlenecks in @acronym{GNU} M4, which he hastily
23786 corrected!)  I reorganized the documentation around problems people want
23787 to solve.  And I began a test suite, because experience had shown that
23788 Autoconf has a pronounced tendency to regress when we change it.
23790 Again, several alpha testers gave invaluable feedback, especially
23791 Fran@,{c}ois Pinard, Jim Meyering, Karl Berry, Rob Savoye, Ken Raeburn,
23792 and Mark Eichin.
23794 Finally, version 2.0 was ready.  And there was much rejoicing.  (And I
23795 have free time again.  I think.  Yeah, right.)
23798 @c ========================================================== Appendices
23801 @node GNU Free Documentation License
23802 @appendix GNU Free Documentation License
23804 @include fdl.texi
23806 @node Indices
23807 @appendix Indices
23809 @menu
23810 * Environment Variable Index::  Index of environment variables used
23811 * Output Variable Index::       Index of variables set in output files
23812 * Preprocessor Symbol Index::   Index of C preprocessor symbols defined
23813 * Autoconf Macro Index::        Index of Autoconf macros
23814 * M4 Macro Index::              Index of M4, M4sugar, and M4sh macros
23815 * Autotest Macro Index::        Index of Autotest macros
23816 * Program & Function Index::    Index of those with portability problems
23817 * Concept Index::               General index
23818 @end menu
23820 @node Environment Variable Index
23821 @appendixsec Environment Variable Index
23823 This is an alphabetical list of the environment variables that might
23824 influence Autoconf checks.
23826 @printindex ev
23828 @node Output Variable Index
23829 @appendixsec Output Variable Index
23831 This is an alphabetical list of the variables that Autoconf can
23832 substitute into files that it creates, typically one or more
23833 makefiles.  @xref{Setting Output Variables}, for more information
23834 on how this is done.
23836 @printindex ov
23838 @node Preprocessor Symbol Index
23839 @appendixsec Preprocessor Symbol Index
23841 This is an alphabetical list of the C preprocessor symbols that the
23842 Autoconf macros define.  To work with Autoconf, C source code needs to
23843 use these names in @code{#if} or @code{#ifdef} directives.
23845 @printindex cv
23847 @node Autoconf Macro Index
23848 @appendixsec Autoconf Macro Index
23850 This is an alphabetical list of the Autoconf macros.
23851 @ifset shortindexflag
23852 To make the list easier to use, the macros are listed without their
23853 preceding @samp{AC_}.
23854 @end ifset
23856 @printindex AC
23858 @node M4 Macro Index
23859 @appendixsec M4 Macro Index
23861 This is an alphabetical list of the M4, M4sugar, and M4sh macros.
23862 @ifset shortindexflag
23863 To make the list easier to use, the macros are listed without their
23864 preceding @samp{m4_} or @samp{AS_}.
23865 @end ifset
23867 @printindex MS
23869 @node Autotest Macro Index
23870 @appendixsec Autotest Macro Index
23872 This is an alphabetical list of the Autotest macros.
23873 @ifset shortindexflag
23874 To make the list easier to use, the macros are listed without their
23875 preceding @samp{AT_}.
23876 @end ifset
23878 @printindex AT
23880 @node Program & Function Index
23881 @appendixsec Program and Function Index
23883 This is an alphabetical list of the programs and functions whose
23884 portability is discussed in this document.
23886 @printindex pr
23888 @node Concept Index
23889 @appendixsec Concept Index
23891 This is an alphabetical list of the files, tools, and concepts
23892 introduced in this document.
23894 @printindex cp
23896 @bye
23898 @c  LocalWords:  texinfo setfilename autoconf texi settitle setchapternewpage
23899 @c  LocalWords:  setcontentsaftertitlepage finalout ARG ovar varname dvar acx
23900 @c  LocalWords:  makeinfo dvi defcodeindex ev ov CPP cv Autotest mv defindex fn
23901 @c  LocalWords:  shortindexflag iftex ifset acindex ACindex ifclear ahindex fu
23902 @c  LocalWords:  asindex MSindex atindex ATindex auindex hdrindex prindex FIXME
23903 @c  LocalWords:  msindex alloca fnindex Aaarg indices FSF's dircategory ifnames
23904 @c  LocalWords:  direntry autoscan autoreconf autoheader autoupdate config FDs
23905 @c  LocalWords:  testsuite titlepage Elliston Demaille vskip filll ifnottex hmm
23906 @c  LocalWords:  insertcopying Autoconf's detailmenu Automake Libtool Posix ois
23907 @c  LocalWords:  Systemology Checkpointing Changequote INTERCAL changequote dfn
23908 @c  LocalWords:  Quadrigraphs builtins Shellology acconfig Bugward LIBOBJ Imake
23909 @c  LocalWords:  LIBOBJS IFELSE cindex flushright Pinard Metaconfig uref Simons
23910 @c  LocalWords:  distclean uninstall noindent versioning Tromey dir
23911 @c  LocalWords:  SAMS samp aclocal acsite underquoted emph itemx prepend SUBST
23912 @c  LocalWords:  evindex automake Gettext autopoint gettext symlink libtoolize
23913 @c  LocalWords:  defmac INIT tarname ovindex cvindex BUGREPORT PREREQ asis PROG
23914 @c  LocalWords:  SRCDIR srcdir globbing afterwards cmds foos fooo foooo init cd
23915 @c  LocalWords:  builddir timestamp src Imakefile chmod defvar CFLAGS CPPFLAGS
23916 @c  LocalWords:  CXXFLAGS DEFS DHAVE defvarx FCFLAGS FFLAGS LDFLAGS bindir GCC
23917 @c  LocalWords:  datadir datarootdir docdir dvidir htmldir libdir ifnothtml kbd
23918 @c  LocalWords:  includedir infodir libexecdir localedir localstatedir mandir
23919 @c  LocalWords:  oldincludedir pdfdir PDF psdir PostScript sbindir sysconfdir
23920 @c  LocalWords:  sharedstatedir DDATADIR sed tmp pkgdatadir VPATH conf unistd
23921 @c  LocalWords:  undef endif builtin FUNCS ifndef STACKSEG getb GETB YMP fubar
23922 @c  LocalWords:  PRE dest SUBDIRS subdirs fi struct STDC stdlib stddef INTTYPES
23923 @c  LocalWords:  inttypes STDINT stdint AWK AIX Solaris NeXT env EGREP FGREP yy
23924 @c  LocalWords:  LEXLIB YYTEXT lfl nonportable Automake's LN RANLIB byacc INETD
23925 @c  LocalWords:  inetd prog PROGS progs ranlib lmp lXt lX nsl gethostbyname UX
23926 @c  LocalWords:  NextStep isinf isnan glibc IRIX sunmath lm lsunmath pre sizeof
23927 @c  LocalWords:  ld inline malloc putenv setenv FreeBSD realloc SunOS MinGW
23928 @c  LocalWords:  snprintf vsnprintf sprintf vsprintf sscanf gcc strerror ifdef
23929 @c  LocalWords:  strnlen sysconf PAGESIZE unsetenv va fallback memcpy dst FUNC
23930 @c  LocalWords:  PowerPC GNUC libPW pragma Olibcalls CHOWN chown CLOSEDIR VFORK
23931 @c  LocalWords:  closedir FNMATCH fnmatch vfork FSEEKO LARGEFILE fseeko SVR sc
23932 @c  LocalWords:  largefile GETGROUPS getgroups GETLOADAVG DGUX UMAX NLIST KMEM
23933 @c  LocalWords:  SETGID getloadavg nlist GETMNTENT irix
23934 @c  LocalWords:  getmntent UnixWare GETPGRP getpgid getpgrp Posix's pid LSTAT
23935 @c  LocalWords:  lstat rpl MEMCMP memcmp OpenStep MBRTOWC mbrtowc MKTIME mktime
23936 @c  LocalWords:  localtime MMAP mmap OBSTACK obstack obstacks ARGTYPES timeval
23937 @c  LocalWords:  SETPGRP setpgrp defmacx Hurd SETVBUF setvbuf STRCOLL strcoll
23938 @c  LocalWords:  STRTOD strtod DECL STRFTIME strftime SCO UTIME utime VPRINTF
23939 @c  LocalWords:  DOPRNT vprintf doprnt sp unfixable LIBSOURCE LIBSOURCES Eggert
23940 @c  LocalWords:  linux netinet ia Tru XFree DIRENT NDIR dirent ndir multitable
23941 @c  LocalWords:  NAMLEN strlen namlen MKDEV SYSMACROS makedev RESOLV resolv DNS
23942 @c  LocalWords:  inet structs NAMESER arpa NETDB netdb UTekV UTS GCC's kB
23943 @c  LocalWords:  STDBOOL BOOL stdbool conformant cplusplus bool Bool stdarg tm
23944 @c  LocalWords:  ctype strchr strrchr rindex bcopy memmove memchr WEXITSTATUS
23945 @c  LocalWords:  WIFEXITED TIOCGWINSZ GWINSZ termios preprocess preprocessable
23946 @c  LocalWords:  DECLS strdup calloc BLKSIZE blksize RDEV rdev TZNAME tzname pw
23947 @c  LocalWords:  passwd gecos pwd MBSTATE mbstate wchar RETSIGTYPE hup UID uid
23948 @c  LocalWords:  gid ptrdiff uintmax EXEEXT OBJEXT Ae conftest AXP str
23949 @c  LocalWords:  ALIGNOF WERROR Werror cpp HP's WorkShop egcs un fied stdc CXX
23950 @c  LocalWords:  varargs BIGENDIAN Endianness SPARC endianness grep'ed CONST FC
23951 @c  LocalWords:  const STRINGIZE stringizing PARAMS unprotoize protos KCC cxx
23952 @c  LocalWords:  xlC aCC CXXCPP FREEFORM xlf FLIBS FCLIBS ish SRCEXT XTRA LFS
23953 @c  LocalWords:  ISC lcposix MINIX Minix conditionalized inlines hw dD confdefs
23954 @c  LocalWords:  fputs stdout PREPROC ar UFS HFS QNX realtime fstype STATVFS se
23955 @c  LocalWords:  statvfs STATFS statfs func machfile hdr lelf raboof DEFUN GTK
23956 @c  LocalWords:  GTKMM Grmph ified ine defn baz EOF qar Ahhh changecom algol io
23957 @c  LocalWords:  changeword quadrigraphs quadrigraph dnl SGI atoi overquoting
23958 @c  LocalWords:  Aas Wcross sep args namespace undefine bpatsubst popdef dquote
23959 @c  LocalWords:  bregexp Overquote overquotation meisch maisch meische maische
23960 @c  LocalWords:  miscian DIRNAME dirname MKDIR CATFILE XMKMF TRAVOLTA celsius
23961 @c  LocalWords:  EMX emxos Emacsen Korn DYNIX subshell posix Ksh ksh Pdksh Zsh
23962 @c  LocalWords:  pdksh zsh Allbery Lipe Kubota UWS zorglub stderr eval esac lfn
23963 @c  LocalWords:  drivespec Posixy DJGPP doschk prettybird LPT pfew Zsh's yu yaa
23964 @c  LocalWords:  yM uM aM firebird IP subdir misparses ok Unpatched abc bc zA
23965 @c  LocalWords:  CDPATH DUALCASE LINENO prepass Subshells lineno NULLCMD cmp wc
23966 @c  LocalWords:  MAILPATH scanset arg NetBSD Almquist printf expr cp
23967 @c  LocalWords:  Oliva awk Aaaaarg cmd regex xfoo GNV OpenVMS VM
23968 @c  LocalWords:  sparc Proulx nbar nfoo maxdepth acdilrtu TWG mc
23969 @c  LocalWords:  mkdir exe uname OpenBSD Fileutils mktemp umask TMPDIR guid os
23970 @c  LocalWords:  fooXXXXXX Unicos utimes hpux hppa unescaped
23971 @c  LocalWords:  pmake DOS's gmake ifoo DESTDIR autoconfiscated pc coff mips gg
23972 @c  LocalWords:  dec ultrix cpu wildcards rpcc rdtsc powerpc readline
23973 @c  LocalWords:  withval vxworks gless localcache usr LOFF loff CYGWIN Cygwin
23974 @c  LocalWords:  cygwin SIGLIST siglist SYSNDIR SYSDIR ptx lseq rusage elif MSC
23975 @c  LocalWords:  lfoo POUNDBANG lsun NIS getpwnam SYSCALLS RSH INTL lintl aix
23976 @c  LocalWords:  intl lx ldir syslog bsd EPI toolchain netbsd objext de KNR nn
23977 @c  LocalWords:  fication LTLIBOBJS Wdiff TESTDIR atconfig atlocal akim XFAIL
23978 @c  LocalWords:  ChangeLog prepended errexit smallexample TESTSUITEFLAGS GPL er
23979 @c  LocalWords:  installcheck autotest indir Pixley Bothner Eichin Kerberos adl
23980 @c  LocalWords:  DISTCLEANFILES preprocessor's fileutils Stallman Murphey Stenn
23981 @c  LocalWords:  Manfredi Autoconfig TCL FSP david zuhn Blandy MACRODIR Raeburn
23982 @c  LocalWords:  autoconfiscate Savoye Haertel Avera Meyering fdl appendixsec
23983 @c  LocalWords:  printindex american LIBOBJDIR LibdirTest ERLCFLAGS OBJCFLAGS
23984 @c  LocalWords:  VER Gnulib online xyes strcpy TYPEOF typeof OBJC objcc objc ln
23985 @c  LocalWords:  GOBJC OTP ERLC erl valloc decr dumpdef errprint incr
23986 @c  LocalWords:  esyscmd len maketemp pushdef substr syscmd sysval translit txt
23987 @c  LocalWords:  sinclude foreach myvar tolower toupper uniq BASENAME STDIN
23988 @c  LocalWords:  Dynix descrips basename aname cname macroexpands xno xcheck
23989 @c  LocalWords:  LIBREADLINE lreadline lncurses libreadline
23991 @c Local Variables:
23992 @c fill-column: 72
23993 @c ispell-local-dictionary: "american"
23994 @c indent-tabs-mode: nil
23995 @c whitespace-check-buffer-indent: nil
23996 @c End: