docs: link to GNU Coding Standards in intro
[autoconf.git] / doc / autoconf.texi
blob99054c5960c641d6fa81b436331c6aae16727b92
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 a cache variable index.
56 @defcodeindex CA
57 @c Define an Autoconf macro index that @defmac doesn't write to.
58 @defcodeindex AC
59 @c Define an Autotest macro index that @defmac doesn't write to.
60 @defcodeindex AT
61 @c Define an M4sugar macro index that @defmac doesn't write to.
62 @defcodeindex MS
63 @c Define an index for *foreign* programs: `mv' etc.  Used for the
64 @c portability sections and so on.
65 @defindex pr
67 @c shortindexflag
68 @c --------------
69 @c Shall we factor AC_ out of the Autoconf macro index etc.?
70 @iftex
71 @set shortindexflag
72 @end iftex
74 @c @acindex{MACRO}
75 @c ---------------
76 @c Registering an AC_\MACRO\.
77 @ifset shortindexflag
78 @macro acindex{macro}
79 @ACindex \macro\
81 @end macro
82 @end ifset
83 @ifclear shortindexflag
84 @macro acindex{macro}
85 @ACindex AC_\macro\
86 @end macro
87 @end ifclear
89 @c @ahindex{MACRO}
90 @c ---------------
91 @c Registering an AH_\MACRO\.
92 @macro ahindex{macro}
93 @ACindex AH_\macro\
95 @end macro
97 @c @asindex{MACRO}
98 @c ---------------
99 @c Registering an AS_\MACRO\.
100 @ifset shortindexflag
101 @macro asindex{macro}
102 @MSindex \macro\
104 @end macro
105 @end ifset
106 @ifclear shortindexflag
107 @macro asindex{macro}
108 @MSindex AS_\macro\
109 @end macro
110 @end ifclear
112 @c @atindex{MACRO}
113 @c ---------------
114 @c Registering an AT_\MACRO\.
115 @ifset shortindexflag
116 @macro atindex{macro}
117 @ATindex \macro\
119 @end macro
120 @end ifset
121 @ifclear shortindexflag
122 @macro atindex{macro}
123 @ATindex AT_\macro\
124 @end macro
125 @end ifclear
127 @c @auindex{MACRO}
128 @c ---------------
129 @c Registering an AU_\MACRO\.
130 @macro auindex{macro}
131 @ACindex AU_\macro\
133 @end macro
135 @c @hdrindex{MACRO}
136 @c ----------------
137 @c Indexing a header.
138 @macro hdrindex{macro}
139 @prindex @file{\macro\}
141 @end macro
143 @c @msindex{MACRO}
144 @c ---------------
145 @c Registering an m4_\MACRO\.
146 @ifset shortindexflag
147 @macro msindex{macro}
148 @MSindex \macro\
150 @end macro
151 @end ifset
152 @ifclear shortindexflag
153 @macro msindex{macro}
154 @MSindex m4_\macro\
155 @end macro
156 @end ifclear
159 @c @caindex{VARIABLE}
160 @c ------------------
161 @c Registering an ac_cv_\VARIABLE\ cache variable.
162 @ifset shortindexflag
163 @macro caindex{macro}
164 @CAindex \macro\
165 @end macro
166 @end ifset
167 @ifclear shortindexflag
168 @macro caindex{macro}
169 @CAindex ac_cv_\macro\
170 @end macro
171 @end ifclear
173 @c Define an index for functions: `alloca' etc.  Used for the
174 @c portability sections and so on.  We can't use `fn' (aka `fnindex),
175 @c since `@defmac' goes into it => we'd get all the macros too.
177 @c   FIXME: Aaarg!  It seems there are too many indices for TeX :(
179 @c   ! No room for a new @write .
180 @c   l.112 @defcodeindex fu
182 @c   so don't define yet another one :(  Just put some tags before each
183 @c   @prindex which is actually a @funindex.
185 @c   @defcodeindex fu
188 @c   @c Put the programs and functions into their own index.
189 @c   @syncodeindex fu pr
191 @comment %**end of header
192 @comment ========================================================
194 @copying
196 This manual (@value{UPDATED}) is for GNU Autoconf
197 (version @value{VERSION}),
198 a package for creating scripts to configure source code packages using
199 templates and an M4 macro package.
201 Copyright @copyright{} 1992, 1993, 1994, 1995, 1996, 1998, 1999, 2000,
202 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 Free Software
203 Foundation, Inc.
205 @quotation
206 Permission is granted to copy, distribute and/or modify this document
207 under the terms of the GNU Free Documentation License,
208 Version 1.3 or any later version published by the Free Software
209 Foundation; with no Invariant Sections, with the Front-Cover texts
210 being ``A GNU Manual,'' and with the Back-Cover Texts as in
211 (a) below.  A copy of the license is included in the section entitled
212 ``GNU Free Documentation License.''
214 (a) The FSF's Back-Cover Text is: ``You have the freedom to copy and
215 modify this GNU manual.  Buying copies from the FSF
216 supports it in developing GNU and promoting software
217 freedom.''
218 @end quotation
219 @end copying
223 @dircategory Software development
224 @direntry
225 * Autoconf: (autoconf).         Create source code configuration scripts.
226 @end direntry
228 @dircategory Individual utilities
229 @direntry
230 * autoscan: (autoconf)autoscan Invocation.
231                                 Semi-automatic @file{configure.ac} writing
232 * ifnames: (autoconf)ifnames Invocation.        Listing conditionals in source.
233 * autoconf-invocation: (autoconf)autoconf Invocation.
234                                 How to create configuration scripts
235 * autoreconf: (autoconf)autoreconf Invocation.
236                                 Remaking multiple @command{configure} scripts
237 * autoheader: (autoconf)autoheader Invocation.
238                                 How to create configuration templates
239 * autom4te: (autoconf)autom4te Invocation.
240                                 The Autoconf executables backbone
241 * configure: (autoconf)configure Invocation.    Configuring a package.
242 * autoupdate: (autoconf)autoupdate Invocation.
243                                 Automatic update of @file{configure.ac}
244 * config.status: (autoconf)config.status Invocation. Recreating configurations.
245 * testsuite: (autoconf)testsuite Invocation.    Running an Autotest test suite.
246 @end direntry
248 @titlepage
249 @title Autoconf
250 @subtitle Creating Automatic Configuration Scripts
251 @subtitle for version @value{VERSION}, @value{UPDATED}
252 @author David MacKenzie
253 @author Ben Elliston
254 @author Akim Demaille
255 @page
256 @vskip 0pt plus 1filll
257 @insertcopying
258 @end titlepage
260 @contents
263 @ifnottex
264 @node Top
265 @top Autoconf
266 @insertcopying
267 @end ifnottex
269 @c The master menu, created with texinfo-master-menu, goes here.
271 @menu
272 * Introduction::                Autoconf's purpose, strengths, and weaknesses
273 * The GNU Build System::        A set of tools for portable software packages
274 * Making configure Scripts::    How to organize and produce Autoconf scripts
275 * Setup::                       Initialization and output
276 * Existing Tests::              Macros that check for particular features
277 * Writing Tests::               How to write new feature checks
278 * Results::                     What to do with results from feature checks
279 * Programming in M4::           Layers on top of which Autoconf is written
280 * Programming in M4sh::         Shell portability layer
281 * Writing Autoconf Macros::     Adding new macros to Autoconf
282 * Portable Shell::              Shell script portability pitfalls
283 * Portable Make::               Makefile portability pitfalls
284 * Portable C and C++::          C and C++ portability pitfalls
285 * Manual Configuration::        Selecting features that can't be guessed
286 * Site Configuration::          Local defaults for @command{configure}
287 * Running configure Scripts::   How to use the Autoconf output
288 * config.status Invocation::    Recreating a configuration
289 * Obsolete Constructs::         Kept for backward compatibility
290 * Using Autotest::              Creating portable test suites
291 * FAQ::                         Frequent Autoconf Questions, with answers
292 * History::                     History of Autoconf
293 * GNU Free Documentation License::  License for copying this manual
294 * Indices::                     Indices of symbols, concepts, etc.
296 @detailmenu
297  --- The Detailed Node Listing ---
299 The GNU Build System
301 * Automake::                    Escaping makefile hell
302 * Gnulib::                      The GNU portability library
303 * Libtool::                     Building libraries portably
304 * Pointers::                    More info on the GNU build system
306 Making @command{configure} Scripts
308 * Writing Autoconf Input::      What to put in an Autoconf input file
309 * autoscan Invocation::         Semi-automatic @file{configure.ac} writing
310 * ifnames Invocation::          Listing the conditionals in source code
311 * autoconf Invocation::         How to create configuration scripts
312 * autoreconf Invocation::       Remaking multiple @command{configure} scripts
314 Writing @file{configure.ac}
316 * Shell Script Compiler::       Autoconf as solution of a problem
317 * Autoconf Language::           Programming in Autoconf
318 * Autoconf Input Layout::       Standard organization of @file{configure.ac}
320 Initialization and Output Files
322 * Initializing configure::      Option processing etc.
323 * Versioning::                  Dealing with Autoconf versions
324 * Notices::                     Copyright, version numbers in @command{configure}
325 * Input::                       Where Autoconf should find files
326 * Output::                      Outputting results from the configuration
327 * Configuration Actions::       Preparing the output based on results
328 * Configuration Files::         Creating output files
329 * Makefile Substitutions::      Using output variables in makefiles
330 * Configuration Headers::       Creating a configuration header file
331 * Configuration Commands::      Running arbitrary instantiation commands
332 * Configuration Links::         Links depending on the configuration
333 * Subdirectories::              Configuring independent packages together
334 * Default Prefix::              Changing the default installation prefix
336 Substitutions in Makefiles
338 * Preset Output Variables::     Output variables that are always set
339 * Installation Directory Variables::  Other preset output variables
340 * Changed Directory Variables:: Warnings about @file{datarootdir}
341 * Build Directories::           Supporting multiple concurrent compiles
342 * Automatic Remaking::          Makefile rules for configuring
344 Configuration Header Files
346 * Header Templates::            Input for the configuration headers
347 * autoheader Invocation::       How to create configuration templates
348 * Autoheader Macros::           How to specify CPP templates
350 Existing Tests
352 * Common Behavior::             Macros' standard schemes
353 * Alternative Programs::        Selecting between alternative programs
354 * Files::                       Checking for the existence of files
355 * Libraries::                   Library archives that might be missing
356 * Library Functions::           C library functions that might be missing
357 * Header Files::                Header files that might be missing
358 * Declarations::                Declarations that may be missing
359 * Structures::                  Structures or members that might be missing
360 * Types::                       Types that might be missing
361 * Compilers and Preprocessors::  Checking for compiling programs
362 * System Services::             Operating system services
363 * Posix Variants::              Special kludges for specific Posix variants
364 * Erlang Libraries::            Checking for the existence of Erlang libraries
366 Common Behavior
368 * Standard Symbols::            Symbols defined by the macros
369 * Default Includes::            Includes used by the generic macros
371 Alternative Programs
373 * Particular Programs::         Special handling to find certain programs
374 * Generic Programs::            How to find other programs
376 Library Functions
378 * Function Portability::        Pitfalls with usual functions
379 * Particular Functions::        Special handling to find certain functions
380 * Generic Functions::           How to find other functions
382 Header Files
384 * Header Portability::          Collected knowledge on common headers
385 * Particular Headers::          Special handling to find certain headers
386 * Generic Headers::             How to find other headers
388 Declarations
390 * Particular Declarations::     Macros to check for certain declarations
391 * Generic Declarations::        How to find other declarations
393 Structures
395 * Particular Structures::       Macros to check for certain structure members
396 * Generic Structures::          How to find other structure members
398 Types
400 * Particular Types::            Special handling to find certain types
401 * Generic Types::               How to find other types
403 Compilers and Preprocessors
405 * Specific Compiler Characteristics::  Some portability issues
406 * Generic Compiler Characteristics::  Language independent tests and features
407 * C Compiler::                  Checking its characteristics
408 * C++ Compiler::                Likewise
409 * Objective C Compiler::        Likewise
410 * Objective C++ Compiler::      Likewise
411 * Erlang Compiler and Interpreter::  Likewise
412 * Fortran Compiler::            Likewise
414 Writing Tests
416 * Language Choice::             Selecting which language to use for testing
417 * Writing Test Programs::       Forging source files for compilers
418 * Running the Preprocessor::    Detecting preprocessor symbols
419 * Running the Compiler::        Detecting language or header features
420 * Running the Linker::          Detecting library features
421 * Runtime::                     Testing for runtime features
422 * Systemology::                 A zoology of operating systems
423 * Multiple Cases::              Tests for several possible values
425 Writing Test Programs
427 * Guidelines::                  General rules for writing test programs
428 * Test Functions::              Avoiding pitfalls in test programs
429 * Generating Sources::          Source program boilerplate
431 Results of Tests
433 * Defining Symbols::            Defining C preprocessor symbols
434 * Setting Output Variables::    Replacing variables in output files
435 * Special Chars in Variables::  Characters to beware of in variables
436 * Caching Results::             Speeding up subsequent @command{configure} runs
437 * Printing Messages::           Notifying @command{configure} users
439 Caching Results
441 * Cache Variable Names::        Shell variables used in caches
442 * Cache Files::                 Files @command{configure} uses for caching
443 * Cache Checkpointing::         Loading and saving the cache file
445 Programming in M4
447 * M4 Quotation::                Protecting macros from unwanted expansion
448 * Using autom4te::              The Autoconf executables backbone
449 * Programming in M4sugar::      Convenient pure M4 macros
450 * Debugging via autom4te::      Figuring out what M4 was doing
452 Programming in M4sh
454 * Common Shell Constructs::     Portability layer for common shell constructs
455 * Polymorphic Variables::       Support for indirect variable names
456 * Initialization Macros::       Macros to establish a sane shell environment
457 * File Descriptor Macros::      File descriptor macros for input and output
459 M4 Quotation
461 * Active Characters::           Characters that change the behavior of M4
462 * One Macro Call::              Quotation and one macro call
463 * Quoting and Parameters::      M4 vs. shell parameters
464 * Quotation and Nested Macros::  Macros calling macros
465 * Changequote is Evil::         Worse than INTERCAL: M4 + changequote
466 * Quadrigraphs::                Another way to escape special characters
467 * Balancing Parentheses::       Dealing with unbalanced parentheses
468 * Quotation Rule Of Thumb::     One parenthesis, one quote
470 Using @command{autom4te}
472 * autom4te Invocation::         A GNU M4 wrapper
473 * Customizing autom4te::        Customizing the Autoconf package
475 Programming in M4sugar
477 * Redefined M4 Macros::         M4 builtins changed in M4sugar
478 * Diagnostic Macros::           Diagnostic messages from M4sugar
479 * Diversion support::           Diversions in M4sugar
480 * Conditional constructs::      Conditions in M4
481 * Looping constructs::          Iteration in M4
482 * Evaluation Macros::           More quotation and evaluation control
483 * Text processing Macros::      String manipulation in M4
484 * Number processing Macros::    Arithmetic computation in M4
485 * Set manipulation Macros::     Set manipulation in M4
486 * Forbidden Patterns::          Catching unexpanded macros
488 Writing Autoconf Macros
490 * Macro Definitions::           Basic format of an Autoconf macro
491 * Macro Names::                 What to call your new macros
492 * Reporting Messages::          Notifying @command{autoconf} users
493 * Dependencies Between Macros::  What to do when macros depend on other macros
494 * Obsoleting Macros::           Warning about old ways of doing things
495 * Coding Style::                Writing Autoconf macros @`a la Autoconf
497 Dependencies Between Macros
499 * Prerequisite Macros::         Ensuring required information
500 * Suggested Ordering::          Warning about possible ordering problems
501 * One-Shot Macros::             Ensuring a macro is called only once
503 Portable Shell Programming
505 * Shellology::                  A zoology of shells
506 * Here-Documents::              Quirks and tricks
507 * File Descriptors::            FDs and redirections
508 * File System Conventions::     File names
509 * Shell Pattern Matching::      Pattern matching
510 * Shell Substitutions::         Variable and command expansions
511 * Assignments::                 Varying side effects of assignments
512 * Parentheses::                 Parentheses in shell scripts
513 * Slashes::                     Slashes in shell scripts
514 * Special Shell Variables::     Variables you should not change
515 * Shell Functions::             What to look out for if you use them
516 * Limitations of Builtins::     Portable use of not so portable /bin/sh
517 * Limitations of Usual Tools::  Portable use of portable tools
519 Portable Make Programming
521 * $< in Ordinary Make Rules::   $< in ordinary rules
522 * Failure in Make Rules::       Failing portably in rules
523 * Special Chars in Names::      Special Characters in Macro Names
524 * Backslash-Newline-Newline::   Empty last lines in macro definitions
525 * Backslash-Newline Comments::  Spanning comments across line boundaries
526 * Long Lines in Makefiles::     Line length limitations
527 * Macros and Submakes::         @code{make macro=value} and submakes
528 * The Make Macro MAKEFLAGS::    @code{$(MAKEFLAGS)} portability issues
529 * The Make Macro SHELL::        @code{$(SHELL)} portability issues
530 * Parallel Make::               Parallel @command{make} quirks
531 * Comments in Make Rules::      Other problems with Make comments
532 * Newlines in Make Rules::      Using literal newlines in rules
533 * obj/ and Make::               Don't name a subdirectory @file{obj}
534 * make -k Status::              Exit status of @samp{make -k}
535 * VPATH and Make::              @code{VPATH} woes
536 * Single Suffix Rules::         Single suffix rules and separated dependencies
537 * Timestamps and Make::         Subsecond timestamp resolution
539 @code{VPATH} and Make
541 * Variables listed in VPATH::   @code{VPATH} must be literal on ancient hosts
542 * VPATH and Double-colon::      Problems with @samp{::} on ancient hosts
543 * $< in Explicit Rules::        @code{$<} does not work in ordinary rules
544 * Automatic Rule Rewriting::    @code{VPATH} goes wild on Solaris
545 * Tru64 Directory Magic::       @command{mkdir} goes wild on Tru64
546 * Make Target Lookup::          More details about @code{VPATH} lookup
548 Portable C and C++ Programming
550 * Varieties of Unportability::  How to make your programs unportable
551 * Integer Overflow::            When integers get too large
552 * Preprocessor Arithmetic::     @code{#if} expression problems
553 * Null Pointers::               Properties of null pointers
554 * Buffer Overruns::             Subscript errors and the like
555 * Volatile Objects::            @code{volatile} and signals
556 * Floating Point Portability::  Portable floating-point arithmetic
557 * Exiting Portably::            Exiting and the exit status
559 Manual Configuration
561 * Specifying Target Triplets::  Specifying target triplets
562 * Canonicalizing::              Getting the canonical system type
563 * Using System Type::           What to do with the system type
565 Site Configuration
567 * Help Formatting::             Customizing @samp{configure --help}
568 * External Software::           Working with other optional software
569 * Package Options::             Selecting optional features
570 * Pretty Help Strings::         Formatting help string
571 * Option Checking::             Controlling checking of @command{configure} options
572 * Site Details::                Configuring site details
573 * Transforming Names::          Changing program names when installing
574 * Site Defaults::               Giving @command{configure} local defaults
576 Transforming Program Names When Installing
578 * Transformation Options::      @command{configure} options to transform names
579 * Transformation Examples::     Sample uses of transforming names
580 * Transformation Rules::        Makefile uses of transforming names
582 Running @command{configure} Scripts
584 * Basic Installation::          Instructions for typical cases
585 * Compilers and Options::       Selecting compilers and optimization
586 * Multiple Architectures::      Compiling for multiple architectures at once
587 * Installation Names::          Installing in different directories
588 * Optional Features::           Selecting optional features
589 * Particular Systems::          Particular systems
590 * System Type::                 Specifying the system type
591 * Sharing Defaults::            Setting site-wide defaults for @command{configure}
592 * Defining Variables::          Specifying the compiler etc.
593 * configure Invocation::        Changing how @command{configure} runs
595 Obsolete Constructs
597 * Obsolete config.status Use::  Obsolete convention for @command{config.status}
598 * acconfig Header::             Additional entries in @file{config.h.in}
599 * autoupdate Invocation::       Automatic update of @file{configure.ac}
600 * Obsolete Macros::             Backward compatibility macros
601 * Autoconf 1::                  Tips for upgrading your files
602 * Autoconf 2.13::               Some fresher tips
604 Upgrading From Version 1
606 * Changed File Names::          Files you might rename
607 * Changed Makefiles::           New things to put in @file{Makefile.in}
608 * Changed Macros::              Macro calls you might replace
609 * Changed Results::             Changes in how to check test results
610 * Changed Macro Writing::       Better ways to write your own macros
612 Upgrading From Version 2.13
614 * Changed Quotation::           Broken code which used to work
615 * New Macros::                  Interaction with foreign macros
616 * Hosts and Cross-Compilation::  Bugward compatibility kludges
617 * AC_LIBOBJ vs LIBOBJS::        LIBOBJS is a forbidden token
618 * AC_ACT_IFELSE vs AC_TRY_ACT::  A more generic scheme for testing sources
620 Generating Test Suites with Autotest
622 * Using an Autotest Test Suite::  Autotest and the user
623 * Writing Testsuites::          Autotest macros
624 * testsuite Invocation::        Running @command{testsuite} scripts
625 * Making testsuite Scripts::    Using autom4te to create @command{testsuite}
627 Using an Autotest Test Suite
629 * testsuite Scripts::           The concepts of Autotest
630 * Autotest Logs::               Their contents
632 Frequent Autoconf Questions, with answers
634 * Distributing::                Distributing @command{configure} scripts
635 * Why GNU M4::                  Why not use the standard M4?
636 * Bootstrapping::               Autoconf and GNU M4 require each other?
637 * Why Not Imake::               Why GNU uses @command{configure} instead of Imake
638 * Defining Directories::        Passing @code{datadir} to program
639 * Autom4te Cache::              What is it?  Can I remove it?
640 * Present But Cannot Be Compiled::  Compiler and Preprocessor Disagree
641 * Expanded Before Required::    Expanded Before Required
642 * Debugging::                   Debugging @command{configure} scripts
644 History of Autoconf
646 * Genesis::                     Prehistory and naming of @command{configure}
647 * Exodus::                      The plagues of M4 and Perl
648 * Leviticus::                   The priestly code of portability arrives
649 * Numbers::                     Growth and contributors
650 * Deuteronomy::                 Approaching the promises of easy configuration
652 Indices
654 * Environment Variable Index::  Index of environment variables used
655 * Output Variable Index::       Index of variables set in output files
656 * Preprocessor Symbol Index::   Index of C preprocessor symbols defined
657 * Cache Variable Index::        Index of documented cache variables
658 * Autoconf Macro Index::        Index of Autoconf macros
659 * M4 Macro Index::              Index of M4, M4sugar, and M4sh macros
660 * Autotest Macro Index::        Index of Autotest macros
661 * Program & Function Index::    Index of those with portability problems
662 * Concept Index::               General index
664 @end detailmenu
665 @end menu
667 @c ============================================================= Introduction.
669 @node Introduction
670 @chapter Introduction
671 @cindex Introduction
673 @flushright
674 A physicist, an engineer, and a computer scientist were discussing the
675 nature of God.  ``Surely a Physicist,'' said the physicist, ``because
676 early in the Creation, God made Light; and you know, Maxwell's
677 equations, the dual nature of electromagnetic waves, the relativistic
678 consequences@enddots{}'' ``An Engineer!,'' said the engineer, ``because
679 before making Light, God split the Chaos into Land and Water; it takes a
680 hell of an engineer to handle that big amount of mud, and orderly
681 separation of solids from liquids@enddots{}'' The computer scientist
682 shouted: ``And the Chaos, where do you think it was coming from, hmm?''
684 ---Anonymous
685 @end flushright
686 @c (via Franc,ois Pinard)
688 Autoconf is a tool for producing shell scripts that automatically
689 configure software source code packages to adapt to many kinds of
690 Posix-like systems.  The configuration scripts produced by Autoconf
691 are independent of Autoconf when they are run, so their users do not
692 need to have Autoconf.
694 The configuration scripts produced by Autoconf require no manual user
695 intervention when run; they do not normally even need an argument
696 specifying the system type.  Instead, they individually test for the
697 presence of each feature that the software package they are for might need.
698 (Before each check, they print a one-line message stating what they are
699 checking for, so the user doesn't get too bored while waiting for the
700 script to finish.)  As a result, they deal well with systems that are
701 hybrids or customized from the more common Posix variants.  There is
702 no need to maintain files that list the features supported by each
703 release of each variant of Posix.
705 For each software package that Autoconf is used with, it creates a
706 configuration script from a template file that lists the system features
707 that the package needs or can use.  After the shell code to recognize
708 and respond to a system feature has been written, Autoconf allows it to
709 be shared by many software packages that can use (or need) that feature.
710 If it later turns out that the shell code needs adjustment for some
711 reason, it needs to be changed in only one place; all of the
712 configuration scripts can be regenerated automatically to take advantage
713 of the updated code.
715 @c "Those who do not understand Unix are condemned to reinvent it, poorly."
716 @c --Henry Spencer, 1987 (see http://en.wikipedia.org/wiki/Unix_philosophy)
717 Those who do not understand Autoconf are condemned to reinvent it, poorly.
718 The primary goal of Autoconf is making the @emph{user's} life easier;
719 making the @emph{maintainer's} life easier is only a secondary goal.
720 Put another way, the primary goal is not to make the generation of
721 @file{configure} automatic for package maintainers (although patches
722 along that front are welcome, since package maintainers form the user
723 base of Autoconf); rather, the goal is to make @file{configure}
724 painless, portable, and predictable for the end user of each
725 @dfn{autoconfiscated} package.  And to this degree, Autoconf is highly
726 successful at its goal --- most complaints to the Autoconf list are
727 about difficulties in writing Autoconf input, and not in the behavior of
728 the resulting @file{configure}.  Even packages that don't use Autoconf
729 will generally provide a @file{configure} script, and the most common
730 complaint about these alternative home-grown scripts is that they fail
731 to meet one or more of the GNU Coding Standars (@pxref{Configuration, , ,
732 standards, The GNU Coding Standards}) that users
733 have come to expect from Autoconf-generated @file{configure} scripts.
735 The Metaconfig package is similar in purpose to Autoconf, but the
736 scripts it produces require manual user intervention, which is quite
737 inconvenient when configuring large source trees.  Unlike Metaconfig
738 scripts, Autoconf scripts can support cross-compiling, if some care is
739 taken in writing them.
741 Autoconf does not solve all problems related to making portable
742 software packages---for a more complete solution, it should be used in
743 concert with other GNU build tools like Automake and
744 Libtool.  These other tools take on jobs like the creation of a
745 portable, recursive makefile with all of the standard targets,
746 linking of shared libraries, and so on.  @xref{The GNU Build System},
747 for more information.
749 Autoconf imposes some restrictions on the names of macros used with
750 @code{#if} in C programs (@pxref{Preprocessor Symbol Index}).
752 Autoconf requires GNU M4 version 1.4.6 or later in order to
753 generate the scripts.  It uses features that some versions of M4,
754 including GNU M4 1.3, do not have.  Autoconf works better
755 with GNU M4 version 1.4.14 or later, though this is not
756 required.
758 @xref{Autoconf 1}, for information about upgrading from version 1.
759 @xref{History}, for the story of Autoconf's development.  @xref{FAQ},
760 for answers to some common questions about Autoconf.
762 See the @uref{http://@/www.gnu.org/@/software/@/autoconf/,
763 Autoconf web page} for up-to-date information, details on the mailing
764 lists, pointers to a list of known bugs, etc.
766 Mail suggestions to @email{autoconf@@gnu.org, the Autoconf mailing
767 list}.  Past suggestions are
768 @uref{http://@/lists.gnu.org/@/archive/@/html/@/autoconf/, archived}.
770 Mail bug reports to @email{bug-autoconf@@gnu.org, the
771 Autoconf Bugs mailing list}.  Past bug reports are
772 @uref{http://@/lists.gnu.org/@/archive/@/html/@/bug-autoconf/, archived}.
774 If possible, first check that your bug is
775 not already solved in current development versions, and that it has not
776 been reported yet.  Be sure to include all the needed information and a
777 short @file{configure.ac} that demonstrates the problem.
779 Autoconf's development tree is accessible via @command{git}; see the
780 @uref{http://@/savannah.gnu.org/@/projects/@/autoconf/, Autoconf
781 Summary} for details, or view
782 @uref{http://@/git.sv.gnu.org/@/gitweb/@/?p=autoconf.git, the actual
783 repository}.  Anonymous CVS access is also available, see
784 @file{README} for more details.  Patches relative to the
785 current @command{git} version can be sent for review to the
786 @email{autoconf-patches@@gnu.org, Autoconf Patches mailing list}, with
787 discussion on prior patches
788 @uref{http://@/lists.gnu.org/@/archive/@/html/@/autoconf-@/patches/,
789 archived}; and all commits are posted in the read-only
790 @email{autoconf-commit@@gnu.org, Autoconf Commit mailing list}, which is
791 also @uref{http://@/lists.gnu.org/@/archive/@/html/@/autoconf-commit/,
792 archived}.
794 Because of its mission, the Autoconf package itself
795 includes only a set of often-used
796 macros that have already demonstrated their usefulness.  Nevertheless,
797 if you wish to share your macros, or find existing ones, see the
798 @uref{http://@/www.gnu.org/@/software/@/autoconf-archive/, Autoconf Macro
799 Archive}, which is kindly run by @email{simons@@cryp.to,
800 Peter Simons}.
803 @c ================================================= The GNU Build System
805 @node The GNU Build System
806 @chapter The GNU Build System
807 @cindex GNU build system
809 Autoconf solves an important problem---reliable discovery of
810 system-specific build and runtime information---but this is only one
811 piece of the puzzle for the development of portable software.  To this
812 end, the GNU project has developed a suite of integrated
813 utilities to finish the job Autoconf started: the GNU build
814 system, whose most important components are Autoconf, Automake, and
815 Libtool.  In this chapter, we introduce you to those tools, point you
816 to sources of more information, and try to convince you to use the
817 entire GNU build system for your software.
819 @menu
820 * Automake::                    Escaping makefile hell
821 * Gnulib::                      The GNU portability library
822 * Libtool::                     Building libraries portably
823 * Pointers::                    More info on the GNU build system
824 @end menu
826 @node Automake
827 @section Automake
829 The ubiquity of @command{make} means that a makefile is almost the
830 only viable way to distribute automatic build rules for software, but
831 one quickly runs into its numerous limitations.  Its lack of
832 support for automatic dependency tracking, recursive builds in
833 subdirectories, reliable timestamps (e.g., for network file systems), and
834 so on, mean that developers must painfully (and often incorrectly)
835 reinvent the wheel for each project.  Portability is non-trivial, thanks
836 to the quirks of @command{make} on many systems.  On top of all this is the
837 manual labor required to implement the many standard targets that users
838 have come to expect (@code{make install}, @code{make distclean},
839 @code{make uninstall}, etc.).  Since you are, of course, using Autoconf,
840 you also have to insert repetitive code in your @file{Makefile.in} to
841 recognize @code{@@CC@@}, @code{@@CFLAGS@@}, and other substitutions
842 provided by @command{configure}.  Into this mess steps @dfn{Automake}.
843 @cindex Automake
845 Automake allows you to specify your build needs in a @file{Makefile.am}
846 file with a vastly simpler and more powerful syntax than that of a plain
847 makefile, and then generates a portable @file{Makefile.in} for
848 use with Autoconf.  For example, the @file{Makefile.am} to build and
849 install a simple ``Hello world'' program might look like:
851 @example
852 bin_PROGRAMS = hello
853 hello_SOURCES = hello.c
854 @end example
856 @noindent
857 The resulting @file{Makefile.in} (~400 lines) automatically supports all
858 the standard targets, the substitutions provided by Autoconf, automatic
859 dependency tracking, @code{VPATH} building, and so on.  @command{make}
860 builds the @code{hello} program, and @code{make install} installs it
861 in @file{/usr/local/bin} (or whatever prefix was given to
862 @command{configure}, if not @file{/usr/local}).
864 The benefits of Automake increase for larger packages (especially ones
865 with subdirectories), but even for small programs the added convenience
866 and portability can be substantial.  And that's not all@enddots{}
868 @node Gnulib
869 @section Gnulib
871 GNU software has a well-deserved reputation for running on
872 many different types of systems.  While our primary goal is to write
873 software for the GNU system, many users and developers have
874 been introduced to us through the systems that they were already using.
876 @cindex Gnulib
877 Gnulib is a central location for common GNU code, intended to
878 be shared among free software packages.  Its components are typically
879 shared at the source level, rather than being a library that gets built,
880 installed, and linked against.  The idea is to copy files from Gnulib
881 into your own source tree.  There is no distribution tarball; developers
882 should just grab source modules from the repository.  The source files
883 are available online, under various licenses, mostly GNU
884 GPL or GNU LGPL.
886 Gnulib modules typically contain C source code along with Autoconf
887 macros used to configure the source code.  For example, the Gnulib
888 @code{stdbool} module implements a @file{stdbool.h} header that nearly
889 conforms to C99, even on old-fashioned hosts that lack @file{stdbool.h}.
890 This module contains a source file for the replacement header, along
891 with an Autoconf macro that arranges to use the replacement header on
892 old-fashioned systems.
894 @node Libtool
895 @section Libtool
897 Often, one wants to build not only programs, but libraries, so that
898 other programs can benefit from the fruits of your labor.  Ideally, one
899 would like to produce @emph{shared} (dynamically linked) libraries,
900 which can be used by multiple programs without duplication on disk or in
901 memory and can be updated independently of the linked programs.
902 Producing shared libraries portably, however, is the stuff of
903 nightmares---each system has its own incompatible tools, compiler flags,
904 and magic incantations.  Fortunately, GNU provides a solution:
905 @dfn{Libtool}.
906 @cindex Libtool
908 Libtool handles all the requirements of building shared libraries for
909 you, and at this time seems to be the @emph{only} way to do so with any
910 portability.  It also handles many other headaches, such as: the
911 interaction of Make rules with the variable suffixes of
912 shared libraries, linking reliably with shared libraries before they are
913 installed by the superuser, and supplying a consistent versioning system
914 (so that different versions of a library can be installed or upgraded
915 without breaking binary compatibility).  Although Libtool, like
916 Autoconf, can be used without Automake, it is most simply utilized in
917 conjunction with Automake---there, Libtool is used automatically
918 whenever shared libraries are needed, and you need not know its syntax.
920 @node Pointers
921 @section Pointers
923 Developers who are used to the simplicity of @command{make} for small
924 projects on a single system might be daunted at the prospect of
925 learning to use Automake and Autoconf.  As your software is
926 distributed to more and more users, however, you otherwise
927 quickly find yourself putting lots of effort into reinventing the
928 services that the GNU build tools provide, and making the
929 same mistakes that they once made and overcame.  (Besides, since
930 you're already learning Autoconf, Automake is a piece of cake.)
932 There are a number of places that you can go to for more information on
933 the GNU build tools.
935 @itemize @minus
937 @item Web
939 The project home pages for
940 @uref{http://@/www@/.gnu@/.org/@/software/@/autoconf/, Autoconf},
941 @uref{http://@/www@/.gnu@/.org/@/software/@/automake/, Automake},
942 @uref{http://@/www@/.gnu@/.org/@/software/@/gnulib/, Gnulib}, and
943 @uref{http://@/www@/.gnu@/.org/@/software/@/libtool/, Libtool}.
945 @item Automake Manual
947 @xref{Top, , Automake, automake, GNU Automake}, for more
948 information on Automake.
950 @item Books
952 The book @cite{GNU Autoconf, Automake and
953 Libtool}@footnote{@cite{GNU Autoconf, Automake and Libtool},
954 by G. V. Vaughan, B. Elliston, T. Tromey, and I. L. Taylor.  SAMS (originally
955 New Riders), 2000, ISBN 1578701902.} describes the complete GNU
956 build environment.  You can also find
957 @uref{http://@/sources.redhat.com/@/autobook/, the entire book on-line}.
959 @end itemize
961 @c ================================================= Making configure Scripts.
963 @node Making configure Scripts
964 @chapter Making @command{configure} Scripts
965 @cindex @file{aclocal.m4}
966 @cindex @command{configure}
968 The configuration scripts that Autoconf produces are by convention
969 called @command{configure}.  When run, @command{configure} creates several
970 files, replacing configuration parameters in them with appropriate
971 values.  The files that @command{configure} creates are:
973 @itemize @minus
974 @item
975 one or more @file{Makefile} files, usually one in each subdirectory of the
976 package (@pxref{Makefile Substitutions});
978 @item
979 optionally, a C header file, the name of which is configurable,
980 containing @code{#define} directives (@pxref{Configuration Headers});
982 @item
983 a shell script called @file{config.status} that, when run, recreates
984 the files listed above (@pxref{config.status Invocation});
986 @item
987 an optional shell script normally called @file{config.cache}
988 (created when using @samp{configure --config-cache}) that
989 saves the results of running many of the tests (@pxref{Cache Files});
991 @item
992 a file called @file{config.log} containing any messages produced by
993 compilers, to help debugging if @command{configure} makes a mistake.
994 @end itemize
996 @cindex @file{configure.in}
997 @cindex @file{configure.ac}
998 To create a @command{configure} script with Autoconf, you need to write an
999 Autoconf input file @file{configure.ac} (or @file{configure.in}) and run
1000 @command{autoconf} on it.  If you write your own feature tests to
1001 supplement those that come with Autoconf, you might also write files
1002 called @file{aclocal.m4} and @file{acsite.m4}.  If you use a C header
1003 file to contain @code{#define} directives, you might also run
1004 @command{autoheader}, and you can distribute the generated file
1005 @file{config.h.in} with the package.
1007 Here is a diagram showing how the files that can be used in
1008 configuration are produced.  Programs that are executed are suffixed by
1009 @samp{*}.  Optional files are enclosed in square brackets (@samp{[]}).
1010 @command{autoconf} and @command{autoheader} also read the installed Autoconf
1011 macro files (by reading @file{autoconf.m4}).
1013 @noindent
1014 Files used in preparing a software package for distribution, when using
1015 just Autoconf:
1016 @example
1017 your source files --> [autoscan*] --> [configure.scan] --> configure.ac
1019 @group
1020 configure.ac --.
1021                |   .------> autoconf* -----> configure
1022 [aclocal.m4] --+---+
1023                |   `-----> [autoheader*] --> [config.h.in]
1024 [acsite.m4] ---'
1025 @end group
1027 Makefile.in
1028 @end example
1030 @noindent
1031 Additionally, if you use Automake, the following additional productions
1032 come into play:
1034 @example
1035 @group
1036 [acinclude.m4] --.
1037                  |
1038 [local macros] --+--> aclocal* --> aclocal.m4
1039                  |
1040 configure.ac ----'
1041 @end group
1043 @group
1044 configure.ac --.
1045                +--> automake* --> Makefile.in
1046 Makefile.am ---'
1047 @end group
1048 @end example
1050 @noindent
1051 Files used in configuring a software package:
1052 @example
1053 @group
1054                        .-------------> [config.cache]
1055 configure* ------------+-------------> config.log
1056                        |
1057 [config.h.in] -.       v            .-> [config.h] -.
1058                +--> config.status* -+               +--> make*
1059 Makefile.in ---'                    `-> Makefile ---'
1060 @end group
1061 @end example
1063 @menu
1064 * Writing Autoconf Input::      What to put in an Autoconf input file
1065 * autoscan Invocation::         Semi-automatic @file{configure.ac} writing
1066 * ifnames Invocation::          Listing the conditionals in source code
1067 * autoconf Invocation::         How to create configuration scripts
1068 * autoreconf Invocation::       Remaking multiple @command{configure} scripts
1069 @end menu
1071 @node Writing Autoconf Input
1072 @section Writing @file{configure.ac}
1074 To produce a @command{configure} script for a software package, create a
1075 file called @file{configure.ac} that contains invocations of the
1076 Autoconf macros that test the system features your package needs or can
1077 use.  Autoconf macros already exist to check for many features; see
1078 @ref{Existing Tests}, for their descriptions.  For most other features,
1079 you can use Autoconf template macros to produce custom checks; see
1080 @ref{Writing Tests}, for information about them.  For especially tricky
1081 or specialized features, @file{configure.ac} might need to contain some
1082 hand-crafted shell commands; see @ref{Portable Shell, , Portable Shell
1083 Programming}.  The @command{autoscan} program can give you a good start
1084 in writing @file{configure.ac} (@pxref{autoscan Invocation}, for more
1085 information).
1087 Previous versions of Autoconf promoted the name @file{configure.in},
1088 which is somewhat ambiguous (the tool needed to process this file is not
1089 described by its extension), and introduces a slight confusion with
1090 @file{config.h.in} and so on (for which @samp{.in} means ``to be
1091 processed by @command{configure}'').  Using @file{configure.ac} is now
1092 preferred.
1094 @menu
1095 * Shell Script Compiler::       Autoconf as solution of a problem
1096 * Autoconf Language::           Programming in Autoconf
1097 * Autoconf Input Layout::       Standard organization of @file{configure.ac}
1098 @end menu
1100 @node Shell Script Compiler
1101 @subsection A Shell Script Compiler
1103 Just as for any other computer language, in order to properly program
1104 @file{configure.ac} in Autoconf you must understand @emph{what} problem
1105 the language tries to address and @emph{how} it does so.
1107 The problem Autoconf addresses is that the world is a mess.  After all,
1108 you are using Autoconf in order to have your package compile easily on
1109 all sorts of different systems, some of them being extremely hostile.
1110 Autoconf itself bears the price for these differences: @command{configure}
1111 must run on all those systems, and thus @command{configure} must limit itself
1112 to their lowest common denominator of features.
1114 Naturally, you might then think of shell scripts; who needs
1115 @command{autoconf}?  A set of properly written shell functions is enough to
1116 make it easy to write @command{configure} scripts by hand.  Sigh!
1117 Unfortunately, even in 2008, where shells without any function support are
1118 far and few between, there are pitfalls to avoid when making use of them.
1119 Also, finding a Bourne shell that accepts shell functions is not trivial,
1120 even though there is almost always one on interesting porting targets.
1122 So, what is really needed is some kind of compiler, @command{autoconf},
1123 that takes an Autoconf program, @file{configure.ac}, and transforms it
1124 into a portable shell script, @command{configure}.
1126 How does @command{autoconf} perform this task?
1128 There are two obvious possibilities: creating a brand new language or
1129 extending an existing one.  The former option is attractive: all
1130 sorts of optimizations could easily be implemented in the compiler and
1131 many rigorous checks could be performed on the Autoconf program
1132 (e.g., rejecting any non-portable construct).  Alternatively, you can
1133 extend an existing language, such as the @code{sh} (Bourne shell)
1134 language.
1136 Autoconf does the latter: it is a layer on top of @code{sh}.  It was
1137 therefore most convenient to implement @command{autoconf} as a macro
1138 expander: a program that repeatedly performs @dfn{macro expansions} on
1139 text input, replacing macro calls with macro bodies and producing a pure
1140 @code{sh} script in the end.  Instead of implementing a dedicated
1141 Autoconf macro expander, it is natural to use an existing
1142 general-purpose macro language, such as M4, and implement the extensions
1143 as a set of M4 macros.
1146 @node Autoconf Language
1147 @subsection The Autoconf Language
1148 @cindex quotation
1150 The Autoconf language differs from many other computer
1151 languages because it treats actual code the same as plain text.  Whereas
1152 in C, for instance, data and instructions have different syntactic
1153 status, in Autoconf their status is rigorously the same.  Therefore, we
1154 need a means to distinguish literal strings from text to be expanded:
1155 quotation.
1157 When calling macros that take arguments, there must not be any white
1158 space between the macro name and the open parenthesis.
1160 @example
1161 AC_INIT ([oops], [1.0]) # incorrect
1162 AC_INIT([hello], [1.0]) # good
1163 @end example
1165 Arguments should
1166 be enclosed within the quote characters @samp{[} and @samp{]}, and be
1167 separated by commas.  Any leading blanks or newlines in arguments are ignored,
1168 unless they are quoted.  You should always quote an argument that
1169 might contain a macro name, comma, parenthesis, or a leading blank or
1170 newline.  This rule applies recursively for every macro
1171 call, including macros called from other macros.  For more details on
1172 quoting rules, see @ref{Programming in M4}.
1174 For instance:
1176 @example
1177 AC_CHECK_HEADER([stdio.h],
1178                 [AC_DEFINE([HAVE_STDIO_H], [1],
1179                    [Define to 1 if you have <stdio.h>.])],
1180                 [AC_MSG_ERROR([sorry, can't do anything for you])])
1181 @end example
1183 @noindent
1184 is quoted properly.  You may safely simplify its quotation to:
1186 @example
1187 AC_CHECK_HEADER([stdio.h],
1188                 [AC_DEFINE([HAVE_STDIO_H], 1,
1189                    [Define to 1 if you have <stdio.h>.])],
1190                 [AC_MSG_ERROR([sorry, can't do anything for you])])
1191 @end example
1193 @noindent
1194 because @samp{1} cannot contain a macro call.  Here, the argument of
1195 @code{AC_MSG_ERROR} must be quoted; otherwise, its comma would be
1196 interpreted as an argument separator.  Also, the second and third arguments
1197 of @samp{AC_CHECK_HEADER} must be quoted, since they contain
1198 macro calls.  The three arguments @samp{HAVE_STDIO_H}, @samp{stdio.h},
1199 and @samp{Define to 1 if you have <stdio.h>.} do not need quoting, but
1200 if you unwisely defined a macro with a name like @samp{Define} or
1201 @samp{stdio} then they would need quoting.  Cautious Autoconf users
1202 would keep the quotes, but many Autoconf users find such precautions
1203 annoying, and would rewrite the example as follows:
1205 @example
1206 AC_CHECK_HEADER(stdio.h,
1207                 [AC_DEFINE(HAVE_STDIO_H, 1,
1208                    [Define to 1 if you have <stdio.h>.])],
1209                 [AC_MSG_ERROR([sorry, can't do anything for you])])
1210 @end example
1212 @noindent
1213 This is safe, so long as you adopt good naming conventions and do not
1214 define macros with names like @samp{HAVE_STDIO_H}, @samp{stdio}, or
1215 @samp{h}.  Though it is also safe here to omit the quotes around
1216 @samp{Define to 1 if you have <stdio.h>.} this is not recommended, as
1217 message strings are more likely to inadvertently contain commas.
1219 The following example is wrong and dangerous, as it is underquoted:
1221 @example
1222 AC_CHECK_HEADER(stdio.h,
1223                 AC_DEFINE(HAVE_STDIO_H, 1,
1224                    Define to 1 if you have <stdio.h>.),
1225                 AC_MSG_ERROR([sorry, can't do anything for you]))
1226 @end example
1228 In other cases, you may have to use text that also resembles a macro
1229 call.  You must quote that text even when it is not passed as a macro
1230 argument.  For example, these two approaches in @file{configure.ac}
1231 (quoting just the potential problems, or quoting the entire line) will
1232 protect your script in case autoconf ever adds a macro @code{AC_DC}:
1234 @example
1235 echo "Hard rock was here!  --[AC_DC]"
1236 [echo "Hard rock was here!  --AC_DC"]
1237 @end example
1239 @noindent
1240 which results in this text in @file{configure}:
1242 @example
1243 echo "Hard rock was here!  --AC_DC"
1244 echo "Hard rock was here!  --AC_DC"
1245 @end example
1247 @noindent
1248 When you use the same text in a macro argument, you must therefore have
1249 an extra quotation level (since one is stripped away by the macro
1250 substitution).  In general, then, it is a good idea to @emph{use double
1251 quoting for all literal string arguments}, either around just the
1252 problematic portions, or over the entire argument:
1254 @example
1255 AC_MSG_WARN([[AC_DC] stinks  --Iron Maiden])
1256 AC_MSG_WARN([[AC_DC stinks  --Iron Maiden]])
1257 @end example
1259 However, the above example triggers a warning about a possibly
1260 unexpanded macro when running @command{autoconf}, because it collides
1261 with the namespace of macros reserved for the Autoconf language.  To be
1262 really safe, you can use additional escaping (either a quadrigraph, or
1263 creative shell constructs) to silence that particular warning:
1265 @example
1266 echo "Hard rock was here!  --AC""_DC"
1267 AC_MSG_WARN([[AC@@&t@@_DC stinks  --Iron Maiden]])
1268 @end example
1270 You are now able to understand one of the constructs of Autoconf that
1271 has been continually misunderstood@enddots{}  The rule of thumb is that
1272 @emph{whenever you expect macro expansion, expect quote expansion};
1273 i.e., expect one level of quotes to be lost.  For instance:
1275 @example
1276 AC_COMPILE_IFELSE([char b[10];], [], [AC_MSG_ERROR([you lose])])
1277 @end example
1279 @noindent
1280 is incorrect: here, the first argument of @code{AC_COMPILE_IFELSE} is
1281 @samp{char b[10];} and is expanded once, which results in
1282 @samp{char b10;}.  (There was an idiom common in Autoconf's past to
1283 address this issue via the M4 @code{changequote} primitive, but do not
1284 use it!)  Let's take a closer look: the author meant the first argument
1285 to be understood as a literal, and therefore it must be quoted twice:
1287 @example
1288 AC_COMPILE_IFELSE([[char b[10];]], [], [AC_MSG_ERROR([you lose])])
1289 @end example
1291 @noindent
1292 Voil@`a, you actually produce @samp{char b[10];} this time!
1294 On the other hand, descriptions (e.g., the last parameter of
1295 @code{AC_DEFINE} or @code{AS_HELP_STRING}) are not literals---they
1296 are subject to line breaking, for example---and should not be double quoted.
1297 Even if these descriptions are short and are not actually broken, double
1298 quoting them yields weird results.
1300 Some macros take optional arguments, which this documentation represents
1301 as @ovar{arg} (not to be confused with the quote characters).  You may
1302 just leave them empty, or use @samp{[]} to make the emptiness of the
1303 argument explicit, or you may simply omit the trailing commas.  The
1304 three lines below are equivalent:
1306 @example
1307 AC_CHECK_HEADERS([stdio.h], [], [], [])
1308 AC_CHECK_HEADERS([stdio.h],,,)
1309 AC_CHECK_HEADERS([stdio.h])
1310 @end example
1312 It is best to put each macro call on its own line in
1313 @file{configure.ac}.  Most of the macros don't add extra newlines; they
1314 rely on the newline after the macro call to terminate the commands.
1315 This approach makes the generated @command{configure} script a little
1316 easier to read by not inserting lots of blank lines.  It is generally
1317 safe to set shell variables on the same line as a macro call, because
1318 the shell allows assignments without intervening newlines.
1320 You can include comments in @file{configure.ac} files by starting them
1321 with the @samp{#}.  For example, it is helpful to begin
1322 @file{configure.ac} files with a line like this:
1324 @example
1325 # Process this file with autoconf to produce a configure script.
1326 @end example
1328 @node Autoconf Input Layout
1329 @subsection Standard @file{configure.ac} Layout
1331 The order in which @file{configure.ac} calls the Autoconf macros is not
1332 important, with a few exceptions.  Every @file{configure.ac} must
1333 contain a call to @code{AC_INIT} before the checks, and a call to
1334 @code{AC_OUTPUT} at the end (@pxref{Output}).  Additionally, some macros
1335 rely on other macros having been called first, because they check
1336 previously set values of some variables to decide what to do.  These
1337 macros are noted in the individual descriptions (@pxref{Existing
1338 Tests}), and they also warn you when @command{configure} is created if they
1339 are called out of order.
1341 To encourage consistency, here is a suggested order for calling the
1342 Autoconf macros.  Generally speaking, the things near the end of this
1343 list are those that could depend on things earlier in it.  For example,
1344 library functions could be affected by types and libraries.
1346 @display
1347 @group
1348 Autoconf requirements
1349 @code{AC_INIT(@var{package}, @var{version}, @var{bug-report-address})}
1350 information on the package
1351 checks for programs
1352 checks for libraries
1353 checks for header files
1354 checks for types
1355 checks for structures
1356 checks for compiler characteristics
1357 checks for library functions
1358 checks for system services
1359 @code{AC_CONFIG_FILES(@r{[}@var{file@dots{}}@r{]})}
1360 @code{AC_OUTPUT}
1361 @end group
1362 @end display
1365 @node autoscan Invocation
1366 @section Using @command{autoscan} to Create @file{configure.ac}
1367 @cindex @command{autoscan}
1369 The @command{autoscan} program can help you create and/or maintain a
1370 @file{configure.ac} file for a software package.  @command{autoscan}
1371 examines source files in the directory tree rooted at a directory given
1372 as a command line argument, or the current directory if none is given.
1373 It searches the source files for common portability problems and creates
1374 a file @file{configure.scan} which is a preliminary @file{configure.ac}
1375 for that package, and checks a possibly existing @file{configure.ac} for
1376 completeness.
1378 When using @command{autoscan} to create a @file{configure.ac}, you
1379 should manually examine @file{configure.scan} before renaming it to
1380 @file{configure.ac}; it probably needs some adjustments.
1381 Occasionally, @command{autoscan} outputs a macro in the wrong order
1382 relative to another macro, so that @command{autoconf} produces a warning;
1383 you need to move such macros manually.  Also, if you want the package to
1384 use a configuration header file, you must add a call to
1385 @code{AC_CONFIG_HEADERS} (@pxref{Configuration Headers}).  You might
1386 also have to change or add some @code{#if} directives to your program in
1387 order to make it work with Autoconf (@pxref{ifnames Invocation}, for
1388 information about a program that can help with that job).
1390 When using @command{autoscan} to maintain a @file{configure.ac}, simply
1391 consider adding its suggestions.  The file @file{autoscan.log}
1392 contains detailed information on why a macro is requested.
1394 @command{autoscan} uses several data files (installed along with Autoconf)
1395 to determine which macros to output when it finds particular symbols in
1396 a package's source files.  These data files all have the same format:
1397 each line consists of a symbol, one or more blanks, and the Autoconf macro to
1398 output if that symbol is encountered.  Lines starting with @samp{#} are
1399 comments.
1401 @command{autoscan} accepts the following options:
1403 @table @option
1404 @item --help
1405 @itemx -h
1406 Print a summary of the command line options and exit.
1408 @item --version
1409 @itemx -V
1410 Print the version number of Autoconf and exit.
1412 @item --verbose
1413 @itemx -v
1414 Print the names of the files it examines and the potentially interesting
1415 symbols it finds in them.  This output can be voluminous.
1417 @item --debug
1418 @itemx -d
1419 Don't remove temporary files.
1421 @item --include=@var{dir}
1422 @itemx -I @var{dir}
1423 Append @var{dir} to the include path.  Multiple invocations accumulate.
1425 @item --prepend-include=@var{dir}
1426 @itemx -B @var{dir}
1427 Prepend @var{dir} to the include path.  Multiple invocations accumulate.
1428 @end table
1430 @node ifnames Invocation
1431 @section Using @command{ifnames} to List Conditionals
1432 @cindex @command{ifnames}
1434 @command{ifnames} can help you write @file{configure.ac} for a software
1435 package.  It prints the identifiers that the package already uses in C
1436 preprocessor conditionals.  If a package has already been set up to have
1437 some portability, @command{ifnames} can thus help you figure out what its
1438 @command{configure} needs to check for.  It may help fill in some gaps in a
1439 @file{configure.ac} generated by @command{autoscan} (@pxref{autoscan
1440 Invocation}).
1442 @command{ifnames} scans all of the C source files named on the command line
1443 (or the standard input, if none are given) and writes to the standard
1444 output a sorted list of all the identifiers that appear in those files
1445 in @code{#if}, @code{#elif}, @code{#ifdef}, or @code{#ifndef}
1446 directives.  It prints each identifier on a line, followed by a
1447 space-separated list of the files in which that identifier occurs.
1449 @noindent
1450 @command{ifnames} accepts the following options:
1452 @table @option
1453 @item --help
1454 @itemx -h
1455 Print a summary of the command line options and exit.
1457 @item --version
1458 @itemx -V
1459 Print the version number of Autoconf and exit.
1460 @end table
1462 @node autoconf Invocation
1463 @section Using @command{autoconf} to Create @command{configure}
1464 @cindex @command{autoconf}
1466 To create @command{configure} from @file{configure.ac}, run the
1467 @command{autoconf} program with no arguments.  @command{autoconf} processes
1468 @file{configure.ac} with the M4 macro processor, using the
1469 Autoconf macros.  If you give @command{autoconf} an argument, it reads that
1470 file instead of @file{configure.ac} and writes the configuration script
1471 to the standard output instead of to @command{configure}.  If you give
1472 @command{autoconf} the argument @option{-}, it reads from the standard
1473 input instead of @file{configure.ac} and writes the configuration script
1474 to the standard output.
1476 The Autoconf macros are defined in several files.  Some of the files are
1477 distributed with Autoconf; @command{autoconf} reads them first.  Then it
1478 looks for the optional file @file{acsite.m4} in the directory that
1479 contains the distributed Autoconf macro files, and for the optional file
1480 @file{aclocal.m4} in the current directory.  Those files can contain
1481 your site's or the package's own Autoconf macro definitions
1482 (@pxref{Writing Autoconf Macros}, for more information).  If a macro is
1483 defined in more than one of the files that @command{autoconf} reads, the
1484 last definition it reads overrides the earlier ones.
1486 @command{autoconf} accepts the following options:
1488 @table @option
1489 @item --help
1490 @itemx -h
1491 Print a summary of the command line options and exit.
1493 @item --version
1494 @itemx -V
1495 Print the version number of Autoconf and exit.
1497 @item --verbose
1498 @itemx -v
1499 Report processing steps.
1501 @item --debug
1502 @itemx -d
1503 Don't remove the temporary files.
1505 @item --force
1506 @itemx -f
1507 Remake @file{configure} even if newer than its input files.
1509 @item --include=@var{dir}
1510 @itemx -I @var{dir}
1511 Append @var{dir} to the include path.  Multiple invocations accumulate.
1513 @item --prepend-include=@var{dir}
1514 @itemx -B @var{dir}
1515 Prepend @var{dir} to the include path.  Multiple invocations accumulate.
1517 @item --output=@var{file}
1518 @itemx -o @var{file}
1519 Save output (script or trace) to @var{file}.  The file @option{-} stands
1520 for the standard output.
1522 @item --warnings=@var{category}
1523 @itemx -W @var{category}
1524 @evindex WARNINGS
1525 Report the warnings related to @var{category} (which can actually be a
1526 comma separated list).  @xref{Reporting Messages}, macro
1527 @code{AC_DIAGNOSE}, for a comprehensive list of categories.  Special
1528 values include:
1530 @table @samp
1531 @item all
1532 report all the warnings
1534 @item none
1535 report none
1537 @item error
1538 treats warnings as errors
1540 @item no-@var{category}
1541 disable warnings falling into @var{category}
1542 @end table
1544 Warnings about @samp{syntax} are enabled by default, and the environment
1545 variable @env{WARNINGS}, a comma separated list of categories, is
1546 honored as well.  Passing @option{-W @var{category}} actually behaves as if
1547 you had passed @option{--warnings syntax,$WARNINGS,@var{category}}.  To
1548 disable the defaults and @env{WARNINGS}, and then
1549 enable warnings about obsolete constructs, use @option{-W
1550 none,obsolete}.
1552 @cindex Back trace
1553 @cindex Macro invocation stack
1554 Because @command{autoconf} uses @command{autom4te} behind the scenes, it
1555 displays a back trace for errors, but not for warnings; if you want
1556 them, just pass @option{-W error}.  @xref{autom4te Invocation}, for some
1557 examples.
1559 @item --trace=@var{macro}[:@var{format}]
1560 @itemx -t @var{macro}[:@var{format}]
1561 Do not create the @command{configure} script, but list the calls to
1562 @var{macro} according to the @var{format}.  Multiple @option{--trace}
1563 arguments can be used to list several macros.  Multiple @option{--trace}
1564 arguments for a single macro are not cumulative; instead, you should
1565 just make @var{format} as long as needed.
1567 The @var{format} is a regular string, with newlines if desired, and
1568 several special escape codes.  It defaults to @samp{$f:$l:$n:$%}; see
1569 @ref{autom4te Invocation}, for details on the @var{format}.
1571 @item --initialization
1572 @itemx -i
1573 By default, @option{--trace} does not trace the initialization of the
1574 Autoconf macros (typically the @code{AC_DEFUN} definitions).  This
1575 results in a noticeable speedup, but can be disabled by this option.
1576 @end table
1579 It is often necessary to check the content of a @file{configure.ac}
1580 file, but parsing it yourself is extremely fragile and error-prone.  It
1581 is suggested that you rely upon @option{--trace} to scan
1582 @file{configure.ac}.  For instance, to find the list of variables that
1583 are substituted, use:
1585 @example
1586 @group
1587 $ @kbd{autoconf -t AC_SUBST}
1588 configure.ac:2:AC_SUBST:ECHO_C
1589 configure.ac:2:AC_SUBST:ECHO_N
1590 configure.ac:2:AC_SUBST:ECHO_T
1591 @i{More traces deleted}
1592 @end group
1593 @end example
1595 @noindent
1596 The example below highlights the difference between @samp{$@@},
1597 @samp{$*}, and @samp{$%}.
1599 @example
1600 @group
1601 $ @kbd{cat configure.ac}
1602 AC_DEFINE(This, is, [an
1603 [example]])
1604 $ @kbd{autoconf -t 'AC_DEFINE:@@: $@@}
1605 *: $*
1606 %: $%'
1607 @@: [This],[is],[an
1608 [example]]
1609 *: This,is,an
1610 [example]
1611 %: This:is:an [example]
1612 @end group
1613 @end example
1615 @noindent
1616 The @var{format} gives you a lot of freedom:
1618 @example
1619 @group
1620 $ @kbd{autoconf -t 'AC_SUBST:$$ac_subst@{"$1"@} = "$f:$l";'}
1621 $ac_subst@{"ECHO_C"@} = "configure.ac:2";
1622 $ac_subst@{"ECHO_N"@} = "configure.ac:2";
1623 $ac_subst@{"ECHO_T"@} = "configure.ac:2";
1624 @i{More traces deleted}
1625 @end group
1626 @end example
1628 @noindent
1629 A long @var{separator} can be used to improve the readability of complex
1630 structures, and to ease their parsing (for instance when no single
1631 character is suitable as a separator):
1633 @example
1634 @group
1635 $ @kbd{autoconf -t 'AM_MISSING_PROG:$@{|:::::|@}*'}
1636 ACLOCAL|:::::|aclocal|:::::|$missing_dir
1637 AUTOCONF|:::::|autoconf|:::::|$missing_dir
1638 AUTOMAKE|:::::|automake|:::::|$missing_dir
1639 @i{More traces deleted}
1640 @end group
1641 @end example
1643 @node autoreconf Invocation
1644 @section Using @command{autoreconf} to Update @command{configure} Scripts
1645 @cindex @command{autoreconf}
1647 Installing the various components of the GNU Build System can be
1648 tedious: running @command{autopoint} for Gettext, @command{automake} for
1649 @file{Makefile.in} etc.@: in each directory.  It may be needed either
1650 because some tools such as @command{automake} have been updated on your
1651 system, or because some of the sources such as @file{configure.ac} have
1652 been updated, or finally, simply in order to install the GNU Build
1653 System in a fresh tree.
1655 @command{autoreconf} runs @command{autoconf}, @command{autoheader},
1656 @command{aclocal}, @command{automake}, @command{libtoolize}, and
1657 @command{autopoint} (when appropriate) repeatedly to update the
1658 GNU Build System in the specified directories and their
1659 subdirectories (@pxref{Subdirectories}).  By default, it only remakes
1660 those files that are older than their sources.  The environment variables
1661 @env{AUTOM4TE}, @env{AUTOCONF}, @env{AUTOHEADER}, @env{AUTOMAKE},
1662 @env{ACLOCAL}, @env{AUTOPOINT}, @env{LIBTOOLIZE}, @env{M4}, and @env{MAKE}
1663 may be used to override the invocation of the respective tools.
1665 If you install a new version of some tool, you can make
1666 @command{autoreconf} remake @emph{all} of the files by giving it the
1667 @option{--force} option.
1669 @xref{Automatic Remaking}, for Make rules to automatically
1670 rebuild @command{configure} scripts when their source files change.  That
1671 method handles the timestamps of configuration header templates
1672 properly, but does not pass @option{--autoconf-dir=@var{dir}} or
1673 @option{--localdir=@var{dir}}.
1675 @cindex Gettext
1676 @cindex @command{autopoint}
1677 Gettext supplies the @command{autopoint} command to add translation
1678 infrastructure to a source package.  If you use @command{autopoint},
1679 your @file{configure.ac} should invoke both @code{AM_GNU_GETTEXT} and
1680 @code{AM_GNU_GETTEXT_VERSION(@var{gettext-version})}.  @xref{autopoint
1681 Invocation, , Invoking the @code{autopoint} Program, gettext,
1682 GNU @code{gettext} utilities}, for further details.
1684 @noindent
1685 @command{autoreconf} accepts the following options:
1687 @table @option
1688 @item --help
1689 @itemx -h
1690 Print a summary of the command line options and exit.
1692 @item --version
1693 @itemx -V
1694 Print the version number of Autoconf and exit.
1696 @item --verbose
1697 @itemx -V
1698 Print the name of each directory @command{autoreconf} examines and the
1699 commands it runs.  If given two or more times, pass @option{--verbose}
1700 to subordinate tools that support it.
1702 @item --debug
1703 @itemx -d
1704 Don't remove the temporary files.
1706 @item --force
1707 @itemx -f
1708 Remake even @file{configure} scripts and configuration headers that are
1709 newer than their input files (@file{configure.ac} and, if present,
1710 @file{aclocal.m4}).
1712 @item --install
1713 @itemx -i
1714 Install the missing auxiliary files in the package.  By default, files
1715 are copied; this can be changed with @option{--symlink}.
1717 If deemed appropriate, this option triggers calls to
1718 @samp{automake --add-missing},
1719 @samp{libtoolize}, @samp{autopoint}, etc.
1721 @item --no-recursive
1722 Do not rebuild files in subdirectories to configure (see @ref{Subdirectories},
1723 macro @code{AC_CONFIG_SUBDIRS}).
1725 @item --symlink
1726 @itemx -s
1727 When used with @option{--install}, install symbolic links to the missing
1728 auxiliary files instead of copying them.
1730 @item --make
1731 @itemx -m
1732 When the directories were configured, update the configuration by
1733 running @samp{./config.status --recheck && ./config.status}, and then
1734 run @samp{make}.
1736 @item --include=@var{dir}
1737 @itemx -I @var{dir}
1738 Append @var{dir} to the include path.  Multiple invocations accumulate.
1739 Passed on to @command{aclocal}, @command{autoconf} and
1740 @command{autoheader} internally.
1742 @item --prepend-include=@var{dir}
1743 @itemx -B @var{dir}
1744 Prepend @var{dir} to the include path.  Multiple invocations accumulate.
1745 Passed on to @command{autoconf} and @command{autoheader} internally.
1747 @item --warnings=@var{category}
1748 @itemx -W @var{category}
1749 @evindex WARNINGS
1750 Report the warnings related to @var{category} (which can actually be a
1751 comma separated list).
1753 @table @samp
1754 @item cross
1755 related to cross compilation issues.
1757 @item obsolete
1758 report the uses of obsolete constructs.
1760 @item portability
1761 portability issues
1763 @item syntax
1764 dubious syntactic constructs.
1766 @item all
1767 report all the warnings
1769 @item none
1770 report none
1772 @item error
1773 treats warnings as errors
1775 @item no-@var{category}
1776 disable warnings falling into @var{category}
1777 @end table
1779 Warnings about @samp{syntax} are enabled by default, and the environment
1780 variable @env{WARNINGS}, a comma separated list of categories, is
1781 honored as well.  Passing @option{-W @var{category}} actually behaves as if
1782 you had passed @option{--warnings syntax,$WARNINGS,@var{category}}.  To
1783 disable the defaults and @env{WARNINGS}, and then
1784 enable warnings about obsolete constructs, use @option{-W
1785 none,obsolete}.
1786 @end table
1788 If you want @command{autoreconf} to pass flags that are not listed here
1789 on to @command{aclocal}, set @code{ACLOCAL_AMFLAGS} in your @file{Makefile.am}.
1790 Due to a limitation in the Autoconf implementation these flags currently
1791 must be set on a single line in @file{Makefile.am}, without any
1792 backslash-newlines.
1794 @c ========================================= Initialization and Output Files.
1796 @node Setup
1797 @chapter Initialization and Output Files
1799 Autoconf-generated @command{configure} scripts need some information about
1800 how to initialize, such as how to find the package's source files and
1801 about the output files to produce.  The following sections describe the
1802 initialization and the creation of output files.
1804 @menu
1805 * Initializing configure::      Option processing etc.
1806 * Versioning::                  Dealing with Autoconf versions
1807 * Notices::                     Copyright, version numbers in @command{configure}
1808 * Input::                       Where Autoconf should find files
1809 * Output::                      Outputting results from the configuration
1810 * Configuration Actions::       Preparing the output based on results
1811 * Configuration Files::         Creating output files
1812 * Makefile Substitutions::      Using output variables in makefiles
1813 * Configuration Headers::       Creating a configuration header file
1814 * Configuration Commands::      Running arbitrary instantiation commands
1815 * Configuration Links::         Links depending on the configuration
1816 * Subdirectories::              Configuring independent packages together
1817 * Default Prefix::              Changing the default installation prefix
1818 @end menu
1820 @node Initializing configure
1821 @section Initializing @command{configure}
1823 Every @command{configure} script must call @code{AC_INIT} before doing
1824 anything else that produces output.  Calls to silent macros, such as
1825 @code{AC_DEFUN}, may also occur prior to @code{AC_INIT}, although these
1826 are generally used via @file{aclocal.m4}, since that is implicitly
1827 included before the start of @file{configure.ac}.  The only other
1828 required macro is @code{AC_OUTPUT} (@pxref{Output}).
1830 @anchor{AC_INIT}
1831 @defmac AC_INIT (@var{package}, @var{version}, @ovar{bug-report}, @
1832   @ovar{tarname}, @ovar{url})
1833 @acindex{INIT}
1834 Process any command-line arguments and perform various initializations
1835 and verifications.
1837 Set the name of the @var{package} and its @var{version}.  These are
1838 typically used in @option{--version} support, including that of
1839 @command{configure}.  The optional argument @var{bug-report} should be
1840 the email to which users should send bug reports.  The package
1841 @var{tarname} differs from @var{package}: the latter designates the full
1842 package name (e.g., @samp{GNU Autoconf}), while the former is meant for
1843 distribution tar ball names (e.g., @samp{autoconf}).  It defaults to
1844 @var{package} with @samp{GNU } stripped, lower-cased, and all characters
1845 other than alphanumerics and underscores are changed to @samp{-}.  If
1846 provided, @var{url} should be the home page for the package.
1848 The arguments of @code{AC_INIT} must be static, i.e., there should not
1849 be any shell computation, quotes, or newlines, but they can be computed
1850 by M4.  This is because the package information strings are expanded at
1851 M4 time into several contexts, and must give the same text at shell time
1852 whether used in single-quoted strings, double-quoted strings, quoted
1853 here-documents, or unquoted here-documents.  It is permissible to use
1854 @code{m4_esyscmd} or @code{m4_esyscmd_s} for computing a version string
1855 that changes with every commit to a version control system (in fact,
1856 Autoconf does just that, for all builds of the development tree made
1857 between releases).
1859 The following M4 macros (e.g., @code{AC_PACKAGE_NAME}), output variables
1860 (e.g., @code{PACKAGE_NAME}), and preprocessor symbols (e.g.,
1861 @code{PACKAGE_NAME}), are defined by @code{AC_INIT}:
1863 @table @asis
1864 @item @code{AC_PACKAGE_NAME}, @code{PACKAGE_NAME}
1865 @acindex{PACKAGE_NAME}
1866 @ovindex PACKAGE_NAME
1867 @cvindex PACKAGE_NAME
1868 Exactly @var{package}.
1870 @item @code{AC_PACKAGE_TARNAME}, @code{PACKAGE_TARNAME}
1871 @acindex{PACKAGE_TARNAME}
1872 @ovindex PACKAGE_TARNAME
1873 @cvindex PACKAGE_TARNAME
1874 Exactly @var{tarname}, possibly generated from @var{package}.
1876 @item @code{AC_PACKAGE_VERSION}, @code{PACKAGE_VERSION}
1877 @acindex{PACKAGE_VERSION}
1878 @ovindex PACKAGE_VERSION
1879 @cvindex PACKAGE_VERSION
1880 Exactly @var{version}.
1882 @item @code{AC_PACKAGE_STRING}, @code{PACKAGE_STRING}
1883 @acindex{PACKAGE_STRING}
1884 @ovindex PACKAGE_STRING
1885 @cvindex PACKAGE_STRING
1886 Exactly @samp{@var{package} @var{version}}.
1888 @item @code{AC_PACKAGE_BUGREPORT}, @code{PACKAGE_BUGREPORT}
1889 @acindex{PACKAGE_BUGREPORT}
1890 @ovindex PACKAGE_BUGREPORT
1891 @cvindex PACKAGE_BUGREPORT
1892 Exactly @var{bug-report}, if one was provided.  Typically an email
1893 address, or URL to a bug management web page.
1895 @item @code{AC_PACKAGE_URL}, @code{PACKAGE_URL}
1896 @acindex{PACKAGE_URL}
1897 @ovindex PACKAGE_URL
1898 @cvindex PACKAGE_URL
1899 Exactly @var{url}, if one was provided.  If @var{url} was empty, but
1900 @var{package} begins with @samp{GNU }, then this defaults to
1901 @samp{http://@/www.gnu.org/@/software/@/@var{tarname}/}, otherwise, no URL is
1902 assumed.
1903 @end table
1904 @end defmac
1906 If your @command{configure} script does its own option processing, it
1907 should inspect @samp{$@@} or @samp{$*} immediately after calling
1908 @code{AC_INIT}, because other Autoconf macros liberally use the
1909 @command{set} command to process strings, and this has the side effect
1910 of updating @samp{$@@} and @samp{$*}.  However, we suggest that you use
1911 standard macros like @code{AC_ARG_ENABLE} instead of attempting to
1912 implement your own option processing.  @xref{Site Configuration}.
1914 @node Versioning
1915 @section Dealing with Autoconf versions
1916 @cindex Autoconf version
1917 @cindex version, Autoconf
1919 The following optional macros can be used to help choose the minimum
1920 version of Autoconf that can successfully compile a given
1921 @file{configure.ac}.
1923 @defmac AC_PREREQ (@var{version})
1924 @acindex{PREREQ}
1925 @cindex Version
1926 Ensure that a recent enough version of Autoconf is being used.  If the
1927 version of Autoconf being used to create @command{configure} is
1928 earlier than @var{version}, print an error message to the standard
1929 error output and exit with failure (exit status is 63).  For example:
1931 @example
1932 AC_PREREQ([@value{VERSION}])
1933 @end example
1935 This macro may be used before @code{AC_INIT}.
1936 @end defmac
1938 @defmac AC_AUTOCONF_VERSION
1939 @acindex{AUTOCONF_VERSION}
1940 This macro was introduced in Autoconf 2.62.  It identifies the version
1941 of Autoconf that is currently parsing the input file, in a format
1942 suitable for @code{m4_version_compare} (@pxref{m4_version_compare}); in
1943 other words, for this release of Autoconf, its value is
1944 @samp{@value{VERSION}}.  One potential use of this macro is for writing
1945 conditional fallbacks based on when a feature was added to Autoconf,
1946 rather than using @code{AC_PREREQ} to require the newer version of
1947 Autoconf.  However, remember that the Autoconf philosophy favors feature
1948 checks over version checks.
1950 You should not expand this macro directly; use
1951 @samp{m4_defn([AC_AUTOCONF_VERSION])} instead.  This is because some
1952 users might
1953 have a beta version of Autoconf installed, with arbitrary letters
1954 included in its version string.  This means it is possible for the
1955 version string to contain the name of a defined macro, such that
1956 expanding @code{AC_AUTOCONF_VERSION} would trigger the expansion of that
1957 macro during rescanning, and change the version string to be different
1958 than what you intended to check.
1959 @end defmac
1961 @node Notices
1962 @section Notices in @command{configure}
1963 @cindex Notices in @command{configure}
1965 The following macros manage version numbers for @command{configure}
1966 scripts.  Using them is optional.
1968 @defmac AC_COPYRIGHT (@var{copyright-notice})
1969 @acindex{COPYRIGHT}
1970 @cindex Copyright Notice
1971 State that, in addition to the Free Software Foundation's copyright on
1972 the Autoconf macros, parts of your @command{configure} are covered by the
1973 @var{copyright-notice}.
1975 The @var{copyright-notice} shows up in both the head of
1976 @command{configure} and in @samp{configure --version}.
1977 @end defmac
1980 @defmac AC_REVISION (@var{revision-info})
1981 @acindex{REVISION}
1982 @cindex Revision
1983 Copy revision stamp @var{revision-info} into the @command{configure}
1984 script, with any dollar signs or double-quotes removed.  This macro lets
1985 you put a revision stamp from @file{configure.ac} into @command{configure}
1986 without RCS or CVS changing it when you check in
1987 @command{configure}.  That way, you can determine easily which revision of
1988 @file{configure.ac} a particular @command{configure} corresponds to.
1990 For example, this line in @file{configure.ac}:
1992 @c The @w prevents RCS from changing the example in the manual.
1993 @example
1994 AC_REVISION([@w{$}Revision: 1.30 $])
1995 @end example
1997 @noindent
1998 produces this in @command{configure}:
2000 @example
2001 #!/bin/sh
2002 # From configure.ac Revision: 1.30
2003 @end example
2004 @end defmac
2007 @node Input
2008 @section Finding @command{configure} Input
2010 @anchor{AC_CONFIG_SRCDIR}
2011 @defmac AC_CONFIG_SRCDIR (@var{unique-file-in-source-dir})
2012 @acindex{CONFIG_SRCDIR}
2013 @var{unique-file-in-source-dir} is some file that is in the package's
2014 source directory; @command{configure} checks for this file's existence to
2015 make sure that the directory that it is told contains the source code in
2016 fact does.  Occasionally people accidentally specify the wrong directory
2017 with @option{--srcdir}; this is a safety check.  @xref{configure
2018 Invocation}, for more information.
2019 @end defmac
2022 @c FIXME: Remove definitively once --install explained.
2024 @c Small packages may store all their macros in @code{aclocal.m4}.  As the
2025 @c set of macros grows, or for maintenance reasons, a maintainer may prefer
2026 @c to split the macros in several files.  In this case, Autoconf must be
2027 @c told which files to load, and in which order.
2029 @c @defmac AC_INCLUDE (@var{file}@dots{})
2030 @c @acindex{INCLUDE}
2031 @c @c FIXME: There is no longer shell globbing.
2032 @c Read the macro definitions that appear in the listed files.  A list of
2033 @c space-separated file names or shell globbing patterns is expected.  The
2034 @c files are read in the order they're listed.
2036 @c Because the order of definition of macros is important (only the last
2037 @c definition of a macro is used), beware that it is @code{AC_INIT} that
2038 @c loads @file{acsite.m4} and @file{aclocal.m4}.  Note that
2039 @c @code{AC_INCLUDE}ing a file before @code{AC_INIT} or within
2040 @c @file{aclocal.m4} is different from doing so after @code{AC_INIT}: in
2041 @c the latter case, non-macro lines from included files may end up in the
2042 @c @file{configure} script, whereas in the former case, they'd be discarded
2043 @c just like any text that appear before @code{AC_INIT}.
2044 @c @end defmac
2046 Packages that do manual configuration or use the @command{install} program
2047 might need to tell @command{configure} where to find some other shell
2048 scripts by calling @code{AC_CONFIG_AUX_DIR}, though the default places
2049 it looks are correct for most cases.
2051 @defmac AC_CONFIG_AUX_DIR (@var{dir})
2052 @acindex{CONFIG_AUX_DIR}
2053 Use the auxiliary build tools (e.g., @file{install-sh},
2054 @file{config.sub}, @file{config.guess}, Cygnus @command{configure},
2055 Automake and Libtool scripts, etc.)@: that are in directory @var{dir}.
2056 These are auxiliary files used in configuration.  @var{dir} can be
2057 either absolute or relative to @file{@var{srcdir}}.  The default is
2058 @file{@var{srcdir}} or @file{@var{srcdir}/..} or
2059 @file{@var{srcdir}/../..}, whichever is the first that contains
2060 @file{install-sh}.  The other files are not checked for, so that using
2061 @code{AC_PROG_INSTALL} does not automatically require distributing the
2062 other auxiliary files.  It checks for @file{install.sh} also, but that
2063 name is obsolete because some @command{make} have a rule that creates
2064 @file{install} from it if there is no makefile.
2066 The auxiliary directory is commonly named @file{build-aux}.
2067 If you need portability to DOS variants, do not name the
2068 auxiliary directory @file{aux}.  @xref{File System Conventions}.
2069 @end defmac
2071 @defmac AC_REQUIRE_AUX_FILE (@var{file})
2072 @acindex{REQUIRE_AUX_FILE}
2073 Declares that @var{file} is expected in the directory defined above.  In
2074 Autoconf proper, this macro does nothing: its sole purpose is to be
2075 traced by third-party tools to produce a list of expected auxiliary
2076 files.  For instance it is called by macros like @code{AC_PROG_INSTALL}
2077 (@pxref{Particular Programs}) or @code{AC_CANONICAL_BUILD}
2078 (@pxref{Canonicalizing}) to register the auxiliary files they need.
2079 @end defmac
2081 Similarly, packages that use @command{aclocal} should declare where
2082 local macros can be found using @code{AC_CONFIG_MACRO_DIR}.
2084 @defmac AC_CONFIG_MACRO_DIR (@var{dir})
2085 @acindex{CONFIG_MACRO_DIR}
2086 Specify @var{dir} as the location of additional local Autoconf macros.
2087 This macro is intended for use by future versions of commands like
2088 @command{autoreconf} that trace macro calls.  It should be called
2089 directly from @file{configure.ac} so that tools that install macros for
2090 @command{aclocal} can find the macros' declarations.
2092 Note that if you use @command{aclocal} from Automake to generate
2093 @file{aclocal.m4}, you must also set @code{ACLOCAL_AMFLAGS = -I
2094 @var{dir}} in your top-level @file{Makefile.am}.  Due to a limitation in
2095 the Autoconf implementation of @command{autoreconf}, these include
2096 directives currently must be set on a single line in @file{Makefile.am},
2097 without any backslash-newlines.
2098 @end defmac
2101 @node Output
2102 @section Outputting Files
2103 @cindex Outputting files
2105 Every Autoconf script, e.g., @file{configure.ac}, should finish by
2106 calling @code{AC_OUTPUT}.  That is the macro that generates and runs
2107 @file{config.status}, which in turn creates the makefiles and any
2108 other files resulting from configuration.  This is the only required
2109 macro besides @code{AC_INIT} (@pxref{Input}).
2111 @anchor{AC_OUTPUT}
2112 @defmac AC_OUTPUT
2113 @acindex{OUTPUT}
2114 @cindex Instantiation
2115 Generate @file{config.status} and launch it.  Call this macro once, at
2116 the end of @file{configure.ac}.
2118 @file{config.status} performs all the configuration actions: all the
2119 output files (see @ref{Configuration Files}, macro
2120 @code{AC_CONFIG_FILES}), header files (see @ref{Configuration Headers},
2121 macro @code{AC_CONFIG_HEADERS}), commands (see @ref{Configuration
2122 Commands}, macro @code{AC_CONFIG_COMMANDS}), links (see
2123 @ref{Configuration Links}, macro @code{AC_CONFIG_LINKS}), subdirectories
2124 to configure (see @ref{Subdirectories}, macro @code{AC_CONFIG_SUBDIRS})
2125 are honored.
2127 The location of your @code{AC_OUTPUT} invocation is the exact point
2128 where configuration actions are taken: any code afterwards is
2129 executed by @command{configure} once @command{config.status} was run.  If
2130 you want to bind actions to @command{config.status} itself
2131 (independently of whether @command{configure} is being run), see
2132 @ref{Configuration Commands, , Running Arbitrary Configuration
2133 Commands}.
2134 @end defmac
2136 Historically, the usage of @code{AC_OUTPUT} was somewhat different.
2137 @xref{Obsolete Macros}, for a description of the arguments that
2138 @code{AC_OUTPUT} used to support.
2141 If you run @command{make} in subdirectories, you should run it using the
2142 @command{make} variable @code{MAKE}.  Most versions of @command{make} set
2143 @code{MAKE} to the name of the @command{make} program plus any options it
2144 was given.  (But many do not include in it the values of any variables
2145 set on the command line, so those are not passed on automatically.)
2146 Some old versions of @command{make} do not set this variable.  The
2147 following macro allows you to use it even with those versions.
2149 @anchor{AC_PROG_MAKE_SET}
2150 @defmac AC_PROG_MAKE_SET
2151 @acindex{PROG_MAKE_SET}
2152 @ovindex SET_MAKE
2153 If the Make command, @code{$MAKE} if set or else @samp{make}, predefines
2154 @code{$(MAKE)}, define output variable @code{SET_MAKE} to be empty.
2155 Otherwise, define @code{SET_MAKE} to a macro definition that sets
2156 @code{$(MAKE)}, such as @samp{MAKE=make}.  Calls @code{AC_SUBST} for
2157 @code{SET_MAKE}.
2158 @end defmac
2160 If you use this macro, place a line like this in each @file{Makefile.in}
2161 that runs @command{MAKE} on other directories:
2163 @example
2164 @@SET_MAKE@@
2165 @end example
2169 @node Configuration Actions
2170 @section Performing Configuration Actions
2171 @cindex Configuration actions
2173 @file{configure} is designed so that it appears to do everything itself,
2174 but there is actually a hidden slave: @file{config.status}.
2175 @file{configure} is in charge of examining your system, but it is
2176 @file{config.status} that actually takes the proper actions based on the
2177 results of @file{configure}.  The most typical task of
2178 @file{config.status} is to @emph{instantiate} files.
2180 @acindex{CONFIG_@var{ITEMS}}
2181 This section describes the common behavior of the four standard
2182 instantiating macros: @code{AC_CONFIG_FILES}, @code{AC_CONFIG_HEADERS},
2183 @code{AC_CONFIG_COMMANDS} and @code{AC_CONFIG_LINKS}.  They all
2184 have this prototype:
2186 @c FIXME: Can't use @ovar here, Texinfo 4.0 goes lunatic and emits something
2187 @c awful.
2188 @example
2189 AC_CONFIG_@var{ITEMS}(@var{tag}@dots{}, @r{[}@var{commands}@r{]}, @r{[}@var{init-cmds}@r{]})
2190 @end example
2192 @noindent
2193 where the arguments are:
2195 @table @var
2196 @item tag@dots{}
2197 A blank-or-newline-separated list of tags, which are typically the names of
2198 the files to instantiate.
2200 You are encouraged to use literals as @var{tags}.  In particular, you
2201 should avoid
2203 @example
2204 @dots{} && my_foos="$my_foos fooo"
2205 @dots{} && my_foos="$my_foos foooo"
2206 AC_CONFIG_@var{ITEMS}([$my_foos])
2207 @end example
2209 @noindent
2210 and use this instead:
2212 @example
2213 @dots{} && AC_CONFIG_@var{ITEMS}([fooo])
2214 @dots{} && AC_CONFIG_@var{ITEMS}([foooo])
2215 @end example
2217 The macros @code{AC_CONFIG_FILES} and @code{AC_CONFIG_HEADERS} use
2218 special @var{tag} values: they may have the form @samp{@var{output}} or
2219 @samp{@var{output}:@var{inputs}}.  The file @var{output} is instantiated
2220 from its templates, @var{inputs} (defaulting to @samp{@var{output}.in}).
2222 @samp{AC_CONFIG_FILES([Makefile:boiler/top.mk:boiler/bot.mk)]},
2223 for example, asks for
2224 the creation of the file @file{Makefile} that contains the expansion of the
2225 output variables in the concatenation of @file{boiler/top.mk} and
2226 @file{boiler/bot.mk}.
2228 The special value @samp{-} might be used to denote the standard output
2229 when used in @var{output}, or the standard input when used in the
2230 @var{inputs}.  You most probably don't need to use this in
2231 @file{configure.ac}, but it is convenient when using the command line
2232 interface of @file{./config.status}, see @ref{config.status Invocation},
2233 for more details.
2235 The @var{inputs} may be absolute or relative file names.  In the latter
2236 case they are first looked for in the build tree, and then in the source
2237 tree.  Input files should be text files, and a line length below 2000
2238 bytes should be safe.
2240 @item commands
2241 Shell commands output literally into @file{config.status}, and
2242 associated with a tag that the user can use to tell @file{config.status}
2243 which commands to run.  The commands are run each time a @var{tag}
2244 request is given to @file{config.status}, typically each time the file
2245 @file{@var{tag}} is created.
2247 The variables set during the execution of @command{configure} are
2248 @emph{not} available here: you first need to set them via the
2249 @var{init-cmds}.  Nonetheless the following variables are precomputed:
2251 @table @code
2252 @item srcdir
2253 The name of the top source directory, assuming that the working
2254 directory is the top build directory.  This
2255 is what the @command{configure} option @option{--srcdir} sets.
2257 @item ac_top_srcdir
2258 The name of the top source directory, assuming that the working
2259 directory is the current build directory.
2261 @item ac_top_build_prefix
2262 The name of the top build directory, assuming that the working
2263 directory is the current build directory.
2264 It can be empty, or else ends with a slash, so that you may concatenate
2267 @item ac_srcdir
2268 The name of the corresponding source directory, assuming that the
2269 working directory is the current build directory.
2271 @item tmp
2272 The name of a temporary directory within the build tree, which you
2273 can use if you need to create additional temporary files.  The
2274 directory is cleaned up when @command{config.status} is done or
2275 interrupted.  Please use package-specific file name prefixes to
2276 avoid clashing with files that @command{config.status} may use
2277 internally.
2278 @end table
2280 @noindent
2281 The @dfn{current} directory refers to the directory (or
2282 pseudo-directory) containing the input part of @var{tags}.  For
2283 instance, running
2285 @example
2286 AC_CONFIG_COMMANDS([deep/dir/out:in/in.in], [@dots{}], [@dots{}])
2287 @end example
2289 @noindent
2290  with @option{--srcdir=../package} produces the following values:
2292 @example
2293 # Argument of --srcdir
2294 srcdir='../package'
2295 # Reversing deep/dir
2296 ac_top_build_prefix='../../'
2297 # Concatenation of $ac_top_build_prefix and srcdir
2298 ac_top_srcdir='../../../package'
2299 # Concatenation of $ac_top_srcdir and deep/dir
2300 ac_srcdir='../../../package/deep/dir'
2301 @end example
2303 @noindent
2304 independently of @samp{in/in.in}.
2306 @item init-cmds
2307 Shell commands output @emph{unquoted} near the beginning of
2308 @file{config.status}, and executed each time @file{config.status} runs
2309 (regardless of the tag).  Because they are unquoted, for example,
2310 @samp{$var} is output as the value of @code{var}.  @var{init-cmds}
2311 is typically used by @file{configure} to give @file{config.status} some
2312 variables it needs to run the @var{commands}.
2314 You should be extremely cautious in your variable names: all the
2315 @var{init-cmds} share the same name space and may overwrite each other
2316 in unpredictable ways.  Sorry@enddots{}
2317 @end table
2319 All these macros can be called multiple times, with different
2320 @var{tag} values, of course!
2323 @node Configuration Files
2324 @section Creating Configuration Files
2325 @cindex Creating configuration files
2326 @cindex Configuration file creation
2328 Be sure to read the previous section, @ref{Configuration Actions}.
2330 @anchor{AC_CONFIG_FILES}
2331 @defmac AC_CONFIG_FILES (@var{file}@dots{}, @ovar{cmds}, @ovar{init-cmds})
2332 @acindex{CONFIG_FILES}
2333 Make @code{AC_OUTPUT} create each @file{@var{file}} by copying an input
2334 file (by default @file{@var{file}.in}), substituting the output variable
2335 values.
2336 @c Before we used to have this feature, which was later rejected
2337 @c because it complicates the writing of makefiles:
2338 @c If the file would be unchanged, it is left untouched, to preserve
2339 @c timestamp.
2340 This macro is one of the instantiating macros; see @ref{Configuration
2341 Actions}.  @xref{Makefile Substitutions}, for more information on using
2342 output variables.  @xref{Setting Output Variables}, for more information
2343 on creating them.  This macro creates the directory that the file is in
2344 if it doesn't exist.  Usually, makefiles are created this way,
2345 but other files, such as @file{.gdbinit}, can be specified as well.
2347 Typical calls to @code{AC_CONFIG_FILES} look like this:
2349 @example
2350 AC_CONFIG_FILES([Makefile src/Makefile man/Makefile X/Imakefile])
2351 AC_CONFIG_FILES([autoconf], [chmod +x autoconf])
2352 @end example
2354 You can override an input file name by appending to @var{file} a
2355 colon-separated list of input files.  Examples:
2357 @example
2358 AC_CONFIG_FILES([Makefile:boiler/top.mk:boiler/bot.mk]
2359                 [lib/Makefile:boiler/lib.mk])
2360 @end example
2362 @noindent
2363 Doing this allows you to keep your file names acceptable to
2364 DOS variants, or
2365 to prepend and/or append boilerplate to the file.
2366 @end defmac
2370 @node Makefile Substitutions
2371 @section Substitutions in Makefiles
2372 @cindex Substitutions in makefiles
2373 @cindex Makefile substitutions
2375 Each subdirectory in a distribution that contains something to be
2376 compiled or installed should come with a file @file{Makefile.in}, from
2377 which @command{configure} creates a file @file{Makefile} in that directory.
2378 To create @file{Makefile}, @command{configure} performs a simple variable
2379 substitution, replacing occurrences of @samp{@@@var{variable}@@} in
2380 @file{Makefile.in} with the value that @command{configure} has determined
2381 for that variable.  Variables that are substituted into output files in
2382 this way are called @dfn{output variables}.  They are ordinary shell
2383 variables that are set in @command{configure}.  To make @command{configure}
2384 substitute a particular variable into the output files, the macro
2385 @code{AC_SUBST} must be called with that variable name as an argument.
2386 Any occurrences of @samp{@@@var{variable}@@} for other variables are
2387 left unchanged.  @xref{Setting Output Variables}, for more information
2388 on creating output variables with @code{AC_SUBST}.
2390 A software package that uses a @command{configure} script should be
2391 distributed with a file @file{Makefile.in}, but no makefile; that
2392 way, the user has to properly configure the package for the local system
2393 before compiling it.
2395 @xref{Makefile Conventions, , Makefile Conventions, standards, The
2396 GNU Coding Standards}, for more information on what to put in
2397 makefiles.
2399 @menu
2400 * Preset Output Variables::     Output variables that are always set
2401 * Installation Directory Variables::  Other preset output variables
2402 * Changed Directory Variables:: Warnings about @file{datarootdir}
2403 * Build Directories::           Supporting multiple concurrent compiles
2404 * Automatic Remaking::          Makefile rules for configuring
2405 @end menu
2407 @node Preset Output Variables
2408 @subsection Preset Output Variables
2409 @cindex Output variables
2411 Some output variables are preset by the Autoconf macros.  Some of the
2412 Autoconf macros set additional output variables, which are mentioned in
2413 the descriptions for those macros.  @xref{Output Variable Index}, for a
2414 complete list of output variables.  @xref{Installation Directory
2415 Variables}, for the list of the preset ones related to installation
2416 directories.  Below are listed the other preset ones, many of which are
2417 precious variables (@pxref{Setting Output Variables},
2418 @code{AC_ARG_VAR}).
2420 The preset variables which are available during @file{config.status}
2421 (@pxref{Configuration Actions}) may also be used during
2422 @command{configure} tests.  For example, it is permissible to reference
2423 @samp{$srcdir} when constructing a list of directories to pass via
2424 option @option{-I} during a compiler feature check.  When used in this
2425 manner, coupled with the fact that @command{configure} is always run
2426 from the top build directory, it is sufficient to use just
2427 @samp{$srcdir} instead of @samp{$top_srcdir}.
2429 @c Just say no to ASCII sorting!  We're humans, not computers.
2430 @c These variables are listed as they would be in a dictionary:
2431 @c actor
2432 @c Actress
2433 @c actress
2435 @defvar CFLAGS
2436 @evindex CFLAGS
2437 @ovindex CFLAGS
2438 Debugging and optimization options for the C compiler.  If it is not set
2439 in the environment when @command{configure} runs, the default value is set
2440 when you call @code{AC_PROG_CC} (or empty if you don't).  @command{configure}
2441 uses this variable when compiling or linking programs to test for C features.
2443 If a compiler option affects only the behavior of the preprocessor
2444 (e.g., @option{-D@var{name}}), it should be put into @code{CPPFLAGS}
2445 instead.  If it affects only the linker (e.g., @option{-L@var{directory}}),
2446 it should be put into @code{LDFLAGS} instead.  If it
2447 affects only the compiler proper, @code{CFLAGS} is the natural home for
2448 it.  If an option affects multiple phases of the compiler, though,
2449 matters get tricky.  One approach to put such options directly into
2450 @code{CC}, e.g., @code{CC='gcc -m64'}.  Another is to put them into both
2451 @code{CPPFLAGS} and @code{LDFLAGS}, but not into @code{CFLAGS}.
2453 However, remember that some @file{Makefile} variables are reserved by
2454 the GNU Coding Standards for the use of the ``user''---the person
2455 building the package.  For instance, @code{CFLAGS} is one such variable.
2457 Sometimes package developers are tempted to set user variables such as
2458 @code{CFLAGS} because it appears to make their job easier.  However, the
2459 package itself should never set a user variable, particularly not to
2460 include switches that are required for proper compilation of the
2461 package.  Since these variables are documented as being for the package
2462 builder, that person rightfully expects to be able to override any of
2463 these variables at build time.  If the package developer needs to add
2464 switches without interfering with the user, the proper way to do that is
2465 to introduce an additional variable.  Automake makes this easy by
2466 introducing @code{AM_CFLAGS} (@pxref{Flag Variables Ordering, , ,
2467 automake, GNU Automake}), but the concept is the same even if
2468 Automake is not used.
2469 @end defvar
2471 @defvar configure_input
2472 @ovindex configure_input
2473 A comment saying that the file was generated automatically by
2474 @command{configure} and giving the name of the input file.
2475 @code{AC_OUTPUT} adds a comment line containing this variable to the top
2476 of every makefile it creates.  For other files, you should
2477 reference this variable in a comment at the top of each input file.  For
2478 example, an input shell script should begin like this:
2480 @example
2481 #!/bin/sh
2482 # @@configure_input@@
2483 @end example
2485 @noindent
2486 The presence of that line also reminds people editing the file that it
2487 needs to be processed by @command{configure} in order to be used.
2488 @end defvar
2490 @defvar CPPFLAGS
2491 @evindex CPPFLAGS
2492 @ovindex CPPFLAGS
2493 Preprocessor options for the C, C++, Objective C, and Objective C++
2494 preprocessors and compilers.  If
2495 it is not set in the environment when @command{configure} runs, the default
2496 value is empty.  @command{configure} uses this variable when preprocessing
2497 or compiling programs to test for C, C++, Objective C, and Objective C++
2498 features.
2500 This variable's contents should contain options like @option{-I},
2501 @option{-D}, and @option{-U} that affect only the behavior of the
2502 preprocessor.  Please see the explanation of @code{CFLAGS} for what you
2503 can do if an option affects other phases of the compiler as well.
2505 Currently, @command{configure} always links as part of a single
2506 invocation of the compiler that also preprocesses and compiles, so it
2507 uses this variable also when linking programs.  However, it is unwise to
2508 depend on this behavior because the GNU Coding Standards do
2509 not require it and many packages do not use @code{CPPFLAGS} when linking
2510 programs.
2512 @xref{Special Chars in Variables}, for limitations that @code{CPPFLAGS}
2513 might run into.
2514 @end defvar
2516 @defvar CXXFLAGS
2517 @evindex CXXFLAGS
2518 @ovindex CXXFLAGS
2519 Debugging and optimization options for the C++ compiler.  It acts like
2520 @code{CFLAGS}, but for C++ instead of C.
2521 @end defvar
2523 @defvar DEFS
2524 @ovindex DEFS
2525 @option{-D} options to pass to the C compiler.  If @code{AC_CONFIG_HEADERS}
2526 is called, @command{configure} replaces @samp{@@DEFS@@} with
2527 @option{-DHAVE_CONFIG_H} instead (@pxref{Configuration Headers}).  This
2528 variable is not defined while @command{configure} is performing its tests,
2529 only when creating the output files.  @xref{Setting Output Variables}, for
2530 how to check the results of previous tests.
2531 @end defvar
2533 @defvar ECHO_C
2534 @defvarx ECHO_N
2535 @defvarx ECHO_T
2536 @ovindex ECHO_C
2537 @ovindex ECHO_N
2538 @ovindex ECHO_T
2539 How does one suppress the trailing newline from @command{echo} for
2540 question-answer message pairs?  These variables provide a way:
2542 @example
2543 echo $ECHO_N "And the winner is... $ECHO_C"
2544 sleep 100000000000
2545 echo "$@{ECHO_T@}dead."
2546 @end example
2548 @noindent
2549 Some old and uncommon @command{echo} implementations offer no means to
2550 achieve this, in which case @code{ECHO_T} is set to tab.  You might not
2551 want to use it.
2552 @end defvar
2554 @defvar ERLCFLAGS
2555 @evindex ERLCFLAGS
2556 @ovindex ERLCFLAGS
2557 Debugging and optimization options for the Erlang compiler.  If it is not set
2558 in the environment when @command{configure} runs, the default value is empty.
2559 @command{configure} uses this variable when compiling
2560 programs to test for Erlang features.
2561 @end defvar
2563 @defvar FCFLAGS
2564 @evindex FCFLAGS
2565 @ovindex FCFLAGS
2566 Debugging and optimization options for the Fortran compiler.  If it
2567 is not set in the environment when @command{configure} runs, the default
2568 value is set when you call @code{AC_PROG_FC} (or empty if you don't).
2569 @command{configure} uses this variable when compiling or linking
2570 programs to test for Fortran features.
2571 @end defvar
2573 @defvar FFLAGS
2574 @evindex FFLAGS
2575 @ovindex FFLAGS
2576 Debugging and optimization options for the Fortran 77 compiler.  If it
2577 is not set in the environment when @command{configure} runs, the default
2578 value is set when you call @code{AC_PROG_F77} (or empty if you don't).
2579 @command{configure} uses this variable when compiling or linking
2580 programs to test for Fortran 77 features.
2581 @end defvar
2583 @defvar LDFLAGS
2584 @evindex LDFLAGS
2585 @ovindex LDFLAGS
2586 Options for the linker.  If it is not set
2587 in the environment when @command{configure} runs, the default value is empty.
2588 @command{configure} uses this variable when linking programs to test for
2589 C, C++, Objective C, Objective C++, and Fortran features.
2591 This variable's contents should contain options like @option{-s} and
2592 @option{-L} that affect only the behavior of the linker.  Please see the
2593 explanation of @code{CFLAGS} for what you can do if an option also
2594 affects other phases of the compiler.
2596 Don't use this variable to pass library names
2597 (@option{-l}) to the linker; use @code{LIBS} instead.
2598 @end defvar
2600 @defvar LIBS
2601 @evindex LIBS
2602 @ovindex LIBS
2603 @option{-l} options to pass to the linker.  The default value is empty,
2604 but some Autoconf macros may prepend extra libraries to this variable if
2605 those libraries are found and provide necessary functions, see
2606 @ref{Libraries}.  @command{configure} uses this variable when linking
2607 programs to test for C, C++, Objective C, Objective C++, and Fortran
2608 features.
2609 @end defvar
2611 @defvar OBJCFLAGS
2612 @evindex OBJCFLAGS
2613 @ovindex OBJCFLAGS
2614 Debugging and optimization options for the Objective C compiler.  It
2615 acts like @code{CFLAGS}, but for Objective C instead of C.
2616 @end defvar
2618 @defvar OBJCXXFLAGS
2619 @evindex OBJCXXFLAGS
2620 @ovindex OBJCXXFLAGS
2621 Debugging and optimization options for the Objective C++ compiler.  It
2622 acts like @code{CXXFLAGS}, but for Objective C++ instead of C++.
2623 @end defvar
2625 @defvar builddir
2626 @ovindex builddir
2627 Rigorously equal to @samp{.}.  Added for symmetry only.
2628 @end defvar
2630 @defvar abs_builddir
2631 @ovindex abs_builddir
2632 Absolute name of @code{builddir}.
2633 @end defvar
2635 @defvar top_builddir
2636 @ovindex top_builddir
2637 The relative name of the top level of the current build tree.  In the
2638 top-level directory, this is the same as @code{builddir}.
2639 @end defvar
2641 @defvar top_build_prefix
2642 @ovindex top_build_prefix
2643 The relative name of the top level of the current build tree with final
2644 slash if nonemtpy.  This is the same as @code{top_builddir}, except that
2645 it contains zero or more runs of @code{../}, so it should not be
2646 appended with a slash for concatenation.  This helps for @command{make}
2647 implementations that otherwise do not treat @file{./file} and @file{file}
2648 as equal in the toplevel build directory.
2649 @end defvar
2651 @defvar abs_top_builddir
2652 @ovindex abs_top_builddir
2653 Absolute name of @code{top_builddir}.
2654 @end defvar
2656 @defvar srcdir
2657 @ovindex srcdir
2658 The name of the directory that contains the source code for
2659 that makefile.
2660 @end defvar
2662 @defvar abs_srcdir
2663 @ovindex abs_srcdir
2664 Absolute name of @code{srcdir}.
2665 @end defvar
2667 @defvar top_srcdir
2668 @ovindex top_srcdir
2669 The name of the top-level source code directory for the
2670 package.  In the top-level directory, this is the same as @code{srcdir}.
2671 @end defvar
2673 @defvar abs_top_srcdir
2674 @ovindex abs_top_srcdir
2675 Absolute name of @code{top_srcdir}.
2676 @end defvar
2678 @node Installation Directory Variables
2679 @subsection Installation Directory Variables
2680 @cindex Installation directories
2681 @cindex Directories, installation
2683 The following variables specify the directories for
2684 package installation, see @ref{Directory Variables, , Variables for
2685 Installation Directories, standards, The GNU Coding
2686 Standards}, for more information.  Each variable corresponds to an
2687 argument of @command{configure}; trailing slashes are stripped so that
2688 expressions such as @samp{$@{prefix@}/lib} expand with only one slash
2689 between directory names.  See the end of this section for
2690 details on when and how to use these variables.
2692 @defvar bindir
2693 @ovindex bindir
2694 The directory for installing executables that users run.
2695 @end defvar
2697 @defvar datadir
2698 @ovindex datadir
2699 The directory for installing idiosyncratic read-only
2700 architecture-independent data.
2701 @end defvar
2703 @defvar datarootdir
2704 @ovindex datarootdir
2705 The root of the directory tree for read-only architecture-independent
2706 data files.
2707 @end defvar
2709 @defvar docdir
2710 @ovindex docdir
2711 The directory for installing documentation files (other than Info and
2712 man).
2713 @end defvar
2715 @defvar dvidir
2716 @ovindex dvidir
2717 The directory for installing documentation files in DVI format.
2718 @end defvar
2720 @defvar exec_prefix
2721 @ovindex exec_prefix
2722 The installation prefix for architecture-dependent files.  By default
2723 it's the same as @code{prefix}.  You should avoid installing anything
2724 directly to @code{exec_prefix}.  However, the default value for
2725 directories containing architecture-dependent files should be relative
2726 to @code{exec_prefix}.
2727 @end defvar
2729 @defvar htmldir
2730 @ovindex htmldir
2731 The directory for installing HTML documentation.
2732 @end defvar
2734 @defvar includedir
2735 @ovindex includedir
2736 The directory for installing C header files.
2737 @end defvar
2739 @defvar infodir
2740 @ovindex infodir
2741 The directory for installing documentation in Info format.
2742 @end defvar
2744 @defvar libdir
2745 @ovindex libdir
2746 The directory for installing object code libraries.
2747 @end defvar
2749 @defvar libexecdir
2750 @ovindex libexecdir
2751 The directory for installing executables that other programs run.
2752 @end defvar
2754 @defvar localedir
2755 @ovindex localedir
2756 The directory for installing locale-dependent but
2757 architecture-independent data, such as message catalogs.  This directory
2758 usually has a subdirectory per locale.
2759 @end defvar
2761 @defvar localstatedir
2762 @ovindex localstatedir
2763 The directory for installing modifiable single-machine data.
2764 @end defvar
2766 @defvar mandir
2767 @ovindex mandir
2768 The top-level directory for installing documentation in man format.
2769 @end defvar
2771 @defvar oldincludedir
2772 @ovindex oldincludedir
2773 The directory for installing C header files for non-GCC compilers.
2774 @end defvar
2776 @defvar pdfdir
2777 @ovindex pdfdir
2778 The directory for installing PDF documentation.
2779 @end defvar
2781 @defvar prefix
2782 @ovindex prefix
2783 The common installation prefix for all files.  If @code{exec_prefix}
2784 is defined to a different value, @code{prefix} is used only for
2785 architecture-independent files.
2786 @end defvar
2788 @defvar psdir
2789 @ovindex psdir
2790 The directory for installing PostScript documentation.
2791 @end defvar
2793 @defvar sbindir
2794 @ovindex sbindir
2795 The directory for installing executables that system
2796 administrators run.
2797 @end defvar
2799 @defvar sharedstatedir
2800 @ovindex sharedstatedir
2801 The directory for installing modifiable architecture-independent data.
2802 @end defvar
2804 @defvar sysconfdir
2805 @ovindex sysconfdir
2806 The directory for installing read-only single-machine data.
2807 @end defvar
2810 Most of these variables have values that rely on @code{prefix} or
2811 @code{exec_prefix}.  It is deliberate that the directory output
2812 variables keep them unexpanded: typically @samp{@@datarootdir@@} is
2813 replaced by @samp{$@{prefix@}/share}, not @samp{/usr/local/share}, and
2814 @samp{@@datadir@@} is replaced by @samp{$@{datarootdir@}}.
2816 This behavior is mandated by the GNU Coding Standards, so that when
2817 the user runs:
2819 @table @samp
2820 @item make
2821 she can still specify a different prefix from the one specified to
2822 @command{configure}, in which case, if needed, the package should hard
2823 code dependencies corresponding to the make-specified prefix.
2825 @item make install
2826 she can specify a different installation location, in which case the
2827 package @emph{must} still depend on the location which was compiled in
2828 (i.e., never recompile when @samp{make install} is run).  This is an
2829 extremely important feature, as many people may decide to install all
2830 the files of a package grouped together, and then install links from
2831 the final locations to there.
2832 @end table
2834 In order to support these features, it is essential that
2835 @code{datarootdir} remains defined as @samp{$@{prefix@}/share},
2836 so that its value can be expanded based
2837 on the current value of @code{prefix}.
2839 A corollary is that you should not use these variables except in
2840 makefiles.  For instance, instead of trying to evaluate @code{datadir}
2841 in @file{configure} and hard-coding it in makefiles using
2842 e.g., @samp{AC_DEFINE_UNQUOTED([DATADIR], ["$datadir"], [Data directory.])},
2843 you should add
2844 @option{-DDATADIR='$(datadir)'} to your makefile's definition of
2845 @code{CPPFLAGS} (@code{AM_CPPFLAGS} if you are also using Automake).
2847 Similarly, you should not rely on @code{AC_CONFIG_FILES} to replace
2848 @code{bindir} and friends in your shell scripts and other files; instead,
2849 let @command{make} manage their replacement.  For instance Autoconf
2850 ships templates of its shell scripts ending with @samp{.in}, and uses a
2851 makefile snippet similar to the following to build scripts like
2852 @command{autoheader} and @command{autom4te}:
2854 @example
2855 @group
2856 edit = sed \
2857         -e 's|@@bindir[@@]|$(bindir)|g' \
2858         -e 's|@@pkgdatadir[@@]|$(pkgdatadir)|g' \
2859         -e 's|@@prefix[@@]|$(prefix)|g'
2860 @end group
2862 @group
2863 autoheader autom4te: Makefile
2864         rm -f $@@ $@@.tmp
2865         srcdir=''; \
2866           test -f ./$@@.in || srcdir=$(srcdir)/; \
2867           $(edit) $$@{srcdir@}$@@.in >$@@.tmp
2868 @c $$ restore font-lock
2869         chmod +x $@@.tmp
2870         chmod a-w $@@.tmp
2871         mv $@@.tmp $@@
2872 @end group
2874 @group
2875 autoheader: $(srcdir)/autoheader.in
2876 autom4te: $(srcdir)/autom4te.in
2877 @end group
2878 @end example
2880 Some details are noteworthy:
2882 @table @asis
2883 @item @samp{@@bindir[@@]}
2884 The brackets prevent @command{configure} from replacing
2885 @samp{@@bindir@@} in the Sed expression itself.
2886 Brackets are preferable to a backslash here, since
2887 Posix says @samp{\@@} is not portable.
2889 @item @samp{$(bindir)}
2890 Don't use @samp{@@bindir@@}!  Use the matching makefile variable
2891 instead.
2893 @item @samp{$(pkgdatadir)}
2894 The example takes advantage of the variable @samp{$(pkgdatadir)}
2895 provided by Automake; it is equivalent to @samp{$(datadir)/$(PACKAGE)}.
2897 @item @samp{/}
2898 Don't use @samp{/} in the Sed expressions that replace file names since
2899 most likely the
2900 variables you use, such as @samp{$(bindir)}, contain @samp{/}.
2901 Use a shell metacharacter instead, such as @samp{|}.
2903 @item special characters
2904 File names, file name components, and the value of @code{VPATH} should
2905 not contain shell metacharacters or white
2906 space.  @xref{Special Chars in Variables}.
2908 @item dependency on @file{Makefile}
2909 Since @code{edit} uses values that depend on the configuration specific
2910 values (@code{prefix}, etc.)@: and not only on @code{VERSION} and so forth,
2911 the output depends on @file{Makefile}, not @file{configure.ac}.
2913 @item @samp{$@@}
2914 The main rule is generic, and uses @samp{$@@} extensively to
2915 avoid the need for multiple copies of the rule.
2917 @item Separated dependencies and single suffix rules
2918 You can't use them!  The above snippet cannot be (portably) rewritten
2921 @example
2922 autoconf autoheader: Makefile
2923 @group
2924 .in:
2925         rm -f $@@ $@@.tmp
2926         $(edit) $< >$@@.tmp
2927         chmod +x $@@.tmp
2928         mv $@@.tmp $@@
2929 @end group
2930 @end example
2932 @xref{Single Suffix Rules}, for details.
2934 @item @samp{$(srcdir)}
2935 Be sure to specify the name of the source directory,
2936 otherwise the package won't support separated builds.
2937 @end table
2939 For the more specific installation of Erlang libraries, the following variables
2940 are defined:
2942 @defvar ERLANG_INSTALL_LIB_DIR
2943 @ovindex ERLANG_INSTALL_LIB_DIR
2944 @acindex{ERLANG_SUBST_INSTALL_LIB_DIR}
2945 The common parent directory of Erlang library installation directories.
2946 This variable is set by calling the @code{AC_ERLANG_SUBST_INSTALL_LIB_DIR}
2947 macro in @file{configure.ac}.
2948 @end defvar
2950 @defvar ERLANG_INSTALL_LIB_DIR_@var{library}
2951 @ovindex ERLANG_INSTALL_LIB_DIR_@var{library}
2952 @acindex{ERLANG_SUBST_INSTALL_LIB_SUBDIR}
2953 The installation directory for Erlang library @var{library}.
2954 This variable is set by using the
2955 @samp{AC_ERLANG_SUBST_INSTALL_LIB_SUBDIR}
2956 macro in @file{configure.ac}.
2957 @end defvar
2959 @xref{Erlang Libraries}, for details.
2962 @node Changed Directory Variables
2963 @subsection Changed Directory Variables
2964 @cindex @file{datarootdir}
2966 In Autoconf 2.60, the set of directory variables has changed, and the
2967 defaults of some variables have been adjusted
2968 (@pxref{Installation Directory Variables}) to changes in the
2969 GNU Coding Standards.  Notably, @file{datadir}, @file{infodir}, and
2970 @file{mandir} are now expressed in terms of @file{datarootdir}.  If you are
2971 upgrading from an earlier Autoconf version, you may need to adjust your files
2972 to ensure that the directory variables are substituted correctly
2973 (@pxref{Defining Directories}), and that a definition of @file{datarootdir} is
2974 in place.  For example, in a @file{Makefile.in}, adding
2976 @example
2977 datarootdir = @@datarootdir@@
2978 @end example
2980 @noindent
2981 is usually sufficient.  If you use Automake to create @file{Makefile.in},
2982 it will add this for you.
2984 To help with the transition, Autoconf warns about files that seem to use
2985 @code{datarootdir} without defining it.  In some cases, it then expands
2986 the value of @code{$datarootdir} in substitutions of the directory
2987 variables.  The following example shows such a warning:
2989 @example
2990 $ @kbd{cat configure.ac}
2991 AC_INIT
2992 AC_CONFIG_FILES([Makefile])
2993 AC_OUTPUT
2994 $ @kbd{cat Makefile.in}
2995 prefix = @@prefix@@
2996 datadir = @@datadir@@
2997 $ @kbd{autoconf}
2998 $ @kbd{configure}
2999 configure: creating ./config.status
3000 config.status: creating Makefile
3001 config.status: WARNING:
3002                Makefile.in seems to ignore the --datarootdir setting
3003 $ @kbd{cat Makefile}
3004 prefix = /usr/local
3005 datadir = $@{prefix@}/share
3006 @end example
3008 Usually one can easily change the file to accommodate both older and newer
3009 Autoconf releases:
3011 @example
3012 $ @kbd{cat Makefile.in}
3013 prefix = @@prefix@@
3014 datarootdir = @@datarootdir@@
3015 datadir = @@datadir@@
3016 $ @kbd{configure}
3017 configure: creating ./config.status
3018 config.status: creating Makefile
3019 $ @kbd{cat Makefile}
3020 prefix = /usr/local
3021 datarootdir = $@{prefix@}/share
3022 datadir = $@{datarootdir@}
3023 @end example
3025 @acindex{DATAROOTDIR_CHECKED}
3026 In some cases, however, the checks may not be able to detect that a suitable
3027 initialization of @code{datarootdir} is in place, or they may fail to detect
3028 that such an initialization is necessary in the output file.  If, after
3029 auditing your package, there are still spurious @file{configure} warnings about
3030 @code{datarootdir}, you may add the line
3032 @example
3033 AC_DEFUN([AC_DATAROOTDIR_CHECKED])
3034 @end example
3036 @noindent
3037 to your @file{configure.ac} to disable the warnings.  This is an exception
3038 to the usual rule that you should not define a macro whose name begins with
3039 @code{AC_} (@pxref{Macro Names}).
3043 @node Build Directories
3044 @subsection Build Directories
3045 @cindex Build directories
3046 @cindex Directories, build
3048 You can support compiling a software package for several architectures
3049 simultaneously from the same copy of the source code.  The object files
3050 for each architecture are kept in their own directory.
3052 To support doing this, @command{make} uses the @code{VPATH} variable to
3053 find the files that are in the source directory.  GNU Make
3054 can do this.  Most other recent @command{make} programs can do this as
3055 well, though they may have difficulties and it is often simpler to
3056 recommend GNU @command{make} (@pxref{VPATH and Make}).  Older
3057 @command{make} programs do not support @code{VPATH}; when using them, the
3058 source code must be in the same directory as the object files.
3060 If you are using GNU Automake, the remaining details in this
3061 section are already covered for you, based on the contents of your
3062 @file{Makefile.am}.  But if you are using Autoconf in isolation, then
3063 supporting @code{VPATH} requires the following in your
3064 @file{Makefile.in}:
3066 @example
3067 srcdir = @@srcdir@@
3068 VPATH = @@srcdir@@
3069 @end example
3071 Do not set @code{VPATH} to the value of another variable (@pxref{Variables
3072 listed in VPATH}.
3074 @command{configure} substitutes the correct value for @code{srcdir} when
3075 it produces @file{Makefile}.
3077 Do not use the @command{make} variable @code{$<}, which expands to the
3078 file name of the file in the source directory (found with @code{VPATH}),
3079 except in implicit rules.  (An implicit rule is one such as @samp{.c.o},
3080 which tells how to create a @file{.o} file from a @file{.c} file.)  Some
3081 versions of @command{make} do not set @code{$<} in explicit rules; they
3082 expand it to an empty value.
3084 Instead, Make command lines should always refer to source
3085 files by prefixing them with @samp{$(srcdir)/}.  For example:
3087 @example
3088 time.info: time.texinfo
3089         $(MAKEINFO) '$(srcdir)/time.texinfo'
3090 @end example
3092 @node Automatic Remaking
3093 @subsection Automatic Remaking
3094 @cindex Automatic remaking
3095 @cindex Remaking automatically
3097 You can put rules like the following in the top-level @file{Makefile.in}
3098 for a package to automatically update the configuration information when
3099 you change the configuration files.  This example includes all of the
3100 optional files, such as @file{aclocal.m4} and those related to
3101 configuration header files.  Omit from the @file{Makefile.in} rules for
3102 any of these files that your package does not use.
3104 The @samp{$(srcdir)/} prefix is included because of limitations in the
3105 @code{VPATH} mechanism.
3107 The @file{stamp-} files are necessary because the timestamps of
3108 @file{config.h.in} and @file{config.h} are not changed if remaking
3109 them does not change their contents.  This feature avoids unnecessary
3110 recompilation.  You should include the file @file{stamp-h.in} in your
3111 package's distribution, so that @command{make} considers
3112 @file{config.h.in} up to date.  Don't use @command{touch}
3113 (@pxref{touch, , Limitations of Usual Tools}); instead, use
3114 @command{echo} (using
3115 @command{date} would cause needless differences, hence CVS
3116 conflicts, etc.).
3118 @example
3119 @group
3120 $(srcdir)/configure: configure.ac aclocal.m4
3121         cd '$(srcdir)' && autoconf
3123 # autoheader might not change config.h.in, so touch a stamp file.
3124 $(srcdir)/config.h.in: stamp-h.in
3125 $(srcdir)/stamp-h.in: configure.ac aclocal.m4
3126         cd '$(srcdir)' && autoheader
3127         echo timestamp > '$(srcdir)/stamp-h.in'
3129 config.h: stamp-h
3130 stamp-h: config.h.in config.status
3131         ./config.status
3133 Makefile: Makefile.in config.status
3134         ./config.status
3136 config.status: configure
3137         ./config.status --recheck
3138 @end group
3139 @end example
3141 @noindent
3142 (Be careful if you copy these lines directly into your makefile, as you
3143 need to convert the indented lines to start with the tab character.)
3145 In addition, you should use
3147 @example
3148 AC_CONFIG_FILES([stamp-h], [echo timestamp > stamp-h])
3149 @end example
3151 @noindent
3152 so @file{config.status} ensures that @file{config.h} is considered up to
3153 date.  @xref{Output}, for more information about @code{AC_OUTPUT}.
3155 @xref{config.status Invocation}, for more examples of handling
3156 configuration-related dependencies.
3158 @node Configuration Headers
3159 @section Configuration Header Files
3160 @cindex Configuration Header
3161 @cindex @file{config.h}
3163 When a package contains more than a few tests that define C preprocessor
3164 symbols, the command lines to pass @option{-D} options to the compiler
3165 can get quite long.  This causes two problems.  One is that the
3166 @command{make} output is hard to visually scan for errors.  More
3167 seriously, the command lines can exceed the length limits of some
3168 operating systems.  As an alternative to passing @option{-D} options to
3169 the compiler, @command{configure} scripts can create a C header file
3170 containing @samp{#define} directives.  The @code{AC_CONFIG_HEADERS}
3171 macro selects this kind of output.  Though it can be called anywhere
3172 between @code{AC_INIT} and @code{AC_OUTPUT}, it is customary to call
3173 it right after @code{AC_INIT}.
3175 The package should @samp{#include} the configuration header file before
3176 any other header files, to prevent inconsistencies in declarations (for
3177 example, if it redefines @code{const}).
3179 To provide for VPATH builds, remember to pass the C compiler a @option{-I.}
3180 option (or @option{-I..}; whichever directory contains @file{config.h}).
3181 Even if you use @samp{#include "config.h"}, the preprocessor searches only
3182 the directory of the currently read file, i.e., the source directory, not
3183 the build directory.
3185 With the appropriate @option{-I} option, you can use
3186 @samp{#include <config.h>}.  Actually, it's a good habit to use it,
3187 because in the rare case when the source directory contains another
3188 @file{config.h}, the build directory should be searched first.
3191 @defmac AC_CONFIG_HEADERS (@var{header} @dots{}, @ovar{cmds}, @ovar{init-cmds})
3192 @acindex{CONFIG_HEADERS}
3193 @cvindex HAVE_CONFIG_H
3194 This macro is one of the instantiating macros; see @ref{Configuration
3195 Actions}.  Make @code{AC_OUTPUT} create the file(s) in the
3196 blank-or-newline-separated list @var{header} containing C preprocessor
3197 @code{#define} statements, and replace @samp{@@DEFS@@} in generated
3198 files with @option{-DHAVE_CONFIG_H} instead of the value of @code{DEFS}.
3199 The usual name for @var{header} is @file{config.h}.
3201 If @var{header} already exists and its contents are identical to what
3202 @code{AC_OUTPUT} would put in it, it is left alone.  Doing this allows
3203 making some changes in the configuration without needlessly causing
3204 object files that depend on the header file to be recompiled.
3206 Usually the input file is named @file{@var{header}.in}; however, you can
3207 override the input file name by appending to @var{header} a
3208 colon-separated list of input files.  For example, you might need to make
3209 the input file name acceptable to DOS variants:
3211 @example
3212 AC_CONFIG_HEADERS([config.h:config.hin])
3213 @end example
3215 @end defmac
3217 @defmac AH_HEADER
3218 @ahindex{HEADER}
3219 This macro is defined as the name of the first declared config header
3220 and undefined if no config headers have been declared up to this point.
3221 A third-party macro may, for example, require use of a config header
3222 without invoking AC_CONFIG_HEADERS twice, like this:
3224 @example
3225 AC_CONFIG_COMMANDS_PRE(
3226         [m4_ifndef([AH_HEADER], [AC_CONFIG_HEADERS([config.h])])])
3227 @end example
3229 @end defmac
3231 @xref{Configuration Actions}, for more details on @var{header}.
3233 @menu
3234 * Header Templates::            Input for the configuration headers
3235 * autoheader Invocation::       How to create configuration templates
3236 * Autoheader Macros::           How to specify CPP templates
3237 @end menu
3239 @node Header Templates
3240 @subsection Configuration Header Templates
3241 @cindex Configuration Header Template
3242 @cindex Header templates
3243 @cindex @file{config.h.in}
3245 Your distribution should contain a template file that looks as you want
3246 the final header file to look, including comments, with @code{#undef}
3247 statements which are used as hooks.  For example, suppose your
3248 @file{configure.ac} makes these calls:
3250 @example
3251 AC_CONFIG_HEADERS([conf.h])
3252 AC_CHECK_HEADERS([unistd.h])
3253 @end example
3255 @noindent
3256 Then you could have code like the following in @file{conf.h.in}.
3257 The @file{conf.h} created by @command{configure} defines @samp{HAVE_UNISTD_H}
3258 to 1, if and only if the system has @file{unistd.h}.
3260 @example
3261 @group
3262 /* Define as 1 if you have unistd.h.  */
3263 #undef HAVE_UNISTD_H
3264 @end group
3265 @end example
3267 The format of the template file is stricter than what the C preprocessor
3268 is required to accept.  A directive line should contain only whitespace,
3269 @samp{#undef}, and @samp{HAVE_UNISTD_H}.  The use of @samp{#define}
3270 instead of @samp{#undef}, or of comments on the same line as
3271 @samp{#undef}, is strongly discouraged.  Each hook should only be listed
3272 once.  Other preprocessor lines, such as @samp{#ifdef} or
3273 @samp{#include}, are copied verbatim from the template into the
3274 generated header.
3276 Since it is a tedious task to keep a template header up to date, you may
3277 use @command{autoheader} to generate it, see @ref{autoheader Invocation}.
3279 During the instantiation of the header, each @samp{#undef} line in the
3280 template file for each symbol defined by @samp{AC_DEFINE} is changed to an
3281 appropriate @samp{#define}. If the corresponding @samp{AC_DEFINE} has not
3282 been executed during the @command{configure} run, the @samp{#undef} line is
3283 commented out.  (This is important, e.g., for @samp{_POSIX_SOURCE}:
3284 on many systems, it can be implicitly defined by the compiler, and
3285 undefining it in the header would then break compilation of subsequent
3286 headers.)
3288 Currently, @emph{all} remaining @samp{#undef} lines in the header
3289 template are commented out, whether or not there was a corresponding
3290 @samp{AC_DEFINE} for the macro name; but this behavior is not guaranteed
3291 for future releases of Autoconf.
3293 Generally speaking, since you should not use @samp{#define}, and you
3294 cannot guarantee whether a @samp{#undef} directive in the header
3295 template will be converted to a @samp{#define} or commented out in the
3296 generated header file, the template file cannot be used for conditional
3297 definition effects.  Consequently, if you need to use the construct
3299 @example
3300 @group
3301 #ifdef THIS
3302 # define THAT
3303 #endif
3304 @end group
3305 @end example
3307 @noindent
3308 you must place it outside of the template.
3309 If you absolutely need to hook it to the config header itself, please put
3310 the directives to a separate file, and @samp{#include} that file from the
3311 config header template.  If you are using @command{autoheader}, you would
3312 probably use @samp{AH_BOTTOM} to append the @samp{#include} directive.
3315 @node autoheader Invocation
3316 @subsection Using @command{autoheader} to Create @file{config.h.in}
3317 @cindex @command{autoheader}
3319 The @command{autoheader} program can create a template file of C
3320 @samp{#define} statements for @command{configure} to use.
3321 It searches for the first invocation of @code{AC_CONFIG_HEADERS} in
3322 @file{configure} sources to determine the name of the template.
3323 (If the first call of @code{AC_CONFIG_HEADERS} specifies more than one
3324 input file name, @command{autoheader} uses the first one.)
3326 It is recommended that only one input file is used.  If you want to append
3327 a boilerplate code, it is preferable to use
3328 @samp{AH_BOTTOM([#include <conf_post.h>])}.
3329 File @file{conf_post.h} is not processed during the configuration then,
3330 which make things clearer.  Analogically, @code{AH_TOP} can be used to
3331 prepend a boilerplate code.
3333 In order to do its job, @command{autoheader} needs you to document all
3334 of the symbols that you might use.  Typically this is done via an
3335 @code{AC_DEFINE} or @code{AC_DEFINE_UNQUOTED} call whose first argument
3336 is a literal symbol and whose third argument describes the symbol
3337 (@pxref{Defining Symbols}).  Alternatively, you can use
3338 @code{AH_TEMPLATE} (@pxref{Autoheader Macros}), or you can supply a
3339 suitable input file for a subsequent configuration header file.
3340 Symbols defined by Autoconf's builtin tests are already documented properly;
3341 you need to document only those that you
3342 define yourself.
3344 You might wonder why @command{autoheader} is needed: after all, why
3345 would @command{configure} need to ``patch'' a @file{config.h.in} to
3346 produce a @file{config.h} instead of just creating @file{config.h} from
3347 scratch?  Well, when everything rocks, the answer is just that we are
3348 wasting our time maintaining @command{autoheader}: generating
3349 @file{config.h} directly is all that is needed.  When things go wrong,
3350 however, you'll be thankful for the existence of @command{autoheader}.
3352 The fact that the symbols are documented is important in order to
3353 @emph{check} that @file{config.h} makes sense.  The fact that there is a
3354 well-defined list of symbols that should be defined (or not) is
3355 also important for people who are porting packages to environments where
3356 @command{configure} cannot be run: they just have to @emph{fill in the
3357 blanks}.
3359 But let's come back to the point: the invocation of @command{autoheader}@dots{}
3361 If you give @command{autoheader} an argument, it uses that file instead
3362 of @file{configure.ac} and writes the header file to the standard output
3363 instead of to @file{config.h.in}.  If you give @command{autoheader} an
3364 argument of @option{-}, it reads the standard input instead of
3365 @file{configure.ac} and writes the header file to the standard output.
3367 @command{autoheader} accepts the following options:
3369 @table @option
3370 @item --help
3371 @itemx -h
3372 Print a summary of the command line options and exit.
3374 @item --version
3375 @itemx -V
3376 Print the version number of Autoconf and exit.
3378 @item --verbose
3379 @itemx -v
3380 Report processing steps.
3382 @item --debug
3383 @itemx -d
3384 Don't remove the temporary files.
3386 @item --force
3387 @itemx -f
3388 Remake the template file even if newer than its input files.
3390 @item --include=@var{dir}
3391 @itemx -I @var{dir}
3392 Append @var{dir} to the include path.  Multiple invocations accumulate.
3394 @item --prepend-include=@var{dir}
3395 @itemx -B @var{dir}
3396 Prepend @var{dir} to the include path.  Multiple invocations accumulate.
3398 @item --warnings=@var{category}
3399 @itemx -W @var{category}
3400 @evindex WARNINGS
3401 Report the warnings related to @var{category} (which can actually be a
3402 comma separated list).  Current categories include:
3404 @table @samp
3405 @item obsolete
3406 report the uses of obsolete constructs
3408 @item all
3409 report all the warnings
3411 @item none
3412 report none
3414 @item error
3415 treats warnings as errors
3417 @item no-@var{category}
3418 disable warnings falling into @var{category}
3419 @end table
3421 @end table
3425 @node Autoheader Macros
3426 @subsection Autoheader Macros
3427 @cindex Autoheader macros
3429 @command{autoheader} scans @file{configure.ac} and figures out which C
3430 preprocessor symbols it might define.  It knows how to generate
3431 templates for symbols defined by @code{AC_CHECK_HEADERS},
3432 @code{AC_CHECK_FUNCS} etc., but if you @code{AC_DEFINE} any additional
3433 symbol, you must define a template for it.  If there are missing
3434 templates, @command{autoheader} fails with an error message.
3436 The template for a @var{symbol} is created
3437 by @command{autoheader} from
3438 the @var{description} argument to an @code{AC_DEFINE};
3439 see @ref{Defining Symbols}.
3441 For special needs, you can use the following macros.
3444 @defmac AH_TEMPLATE (@var{key}, @var{description})
3445 @ahindex{TEMPLATE}
3446 Tell @command{autoheader} to generate a template for @var{key}.  This macro
3447 generates standard templates just like @code{AC_DEFINE} when a
3448 @var{description} is given.
3450 For example:
3452 @example
3453 AH_TEMPLATE([CRAY_STACKSEG_END],
3454             [Define to one of _getb67, GETB67, getb67
3455              for Cray-2 and Cray-YMP systems.  This
3456              function is required for alloca.c support
3457              on those systems.])
3458 @end example
3460 @noindent
3461 generates the following template, with the description properly
3462 justified.
3464 @example
3465 /* Define to one of _getb67, GETB67, getb67 for Cray-2 and
3466    Cray-YMP systems.  This function is required for alloca.c
3467    support on those systems.  */
3468 #undef CRAY_STACKSEG_END
3469 @end example
3470 @end defmac
3473 @defmac AH_VERBATIM (@var{key}, @var{template})
3474 @ahindex{VERBATIM}
3475 Tell @command{autoheader} to include the @var{template} as-is in the header
3476 template file.  This @var{template} is associated with the @var{key},
3477 which is used to sort all the different templates and guarantee their
3478 uniqueness.  It should be a symbol that can be defined via @code{AC_DEFINE}.
3479 @end defmac
3482 @defmac AH_TOP (@var{text})
3483 @ahindex{TOP}
3484 Include @var{text} at the top of the header template file.
3485 @end defmac
3488 @defmac AH_BOTTOM (@var{text})
3489 @ahindex{BOTTOM}
3490 Include @var{text} at the bottom of the header template file.
3491 @end defmac
3494 Please note that @var{text} gets included ``verbatim'' to the template file,
3495 not to the resulting config header, so it can easily get mangled when the
3496 template is processed.  There is rarely a need for something other than
3498 @example
3499 AH_BOTTOM([#include <custom.h>])
3500 @end example
3504 @node Configuration Commands
3505 @section Running Arbitrary Configuration Commands
3506 @cindex Configuration commands
3507 @cindex Commands for configuration
3509 You can execute arbitrary commands before, during, and after
3510 @file{config.status} is run.  The three following macros accumulate the
3511 commands to run when they are called multiple times.
3512 @code{AC_CONFIG_COMMANDS} replaces the obsolete macro
3513 @code{AC_OUTPUT_COMMANDS}; see @ref{Obsolete Macros}, for details.
3515 @anchor{AC_CONFIG_COMMANDS}
3516 @defmac AC_CONFIG_COMMANDS (@var{tag}@dots{}, @ovar{cmds}, @ovar{init-cmds})
3517 @acindex{CONFIG_COMMANDS}
3518 Specify additional shell commands to run at the end of
3519 @file{config.status}, and shell commands to initialize any variables
3520 from @command{configure}.  Associate the commands with @var{tag}.
3521 Since typically the @var{cmds} create a file, @var{tag} should
3522 naturally be the name of that file.  If needed, the directory hosting
3523 @var{tag} is created.  This macro is one of the instantiating macros;
3524 see @ref{Configuration Actions}.
3526 Here is an unrealistic example:
3527 @example
3528 fubar=42
3529 AC_CONFIG_COMMANDS([fubar],
3530                    [echo this is extra $fubar, and so on.],
3531                    [fubar=$fubar])
3532 @end example
3534 Here is a better one:
3535 @example
3536 AC_CONFIG_COMMANDS([timestamp], [date >timestamp])
3537 @end example
3538 @end defmac
3540 The following two macros look similar, but in fact they are not of the same
3541 breed: they are executed directly by @file{configure}, so you cannot use
3542 @file{config.status} to rerun them.
3544 @c Yet it is good to leave them here.  The user sees them together and
3545 @c decides which best fits their needs.
3547 @defmac AC_CONFIG_COMMANDS_PRE (@var{cmds})
3548 @acindex{CONFIG_COMMANDS_PRE}
3549 Execute the @var{cmds} right before creating @file{config.status}.
3551 This macro presents the last opportunity to call @code{AC_SUBST},
3552 @code{AC_DEFINE}, or @code{AC_CONFIG_@var{ITEMS}} macros.
3553 @end defmac
3555 @defmac AC_CONFIG_COMMANDS_POST (@var{cmds})
3556 @acindex{CONFIG_COMMANDS_POST}
3557 Execute the @var{cmds} right after creating @file{config.status}.
3558 @end defmac
3563 @node Configuration Links
3564 @section Creating Configuration Links
3565 @cindex Configuration links
3566 @cindex Links for configuration
3568 You may find it convenient to create links whose destinations depend upon
3569 results of tests.  One can use @code{AC_CONFIG_COMMANDS} but the
3570 creation of relative symbolic links can be delicate when the package is
3571 built in a directory different from the source directory.
3573 @anchor{AC_CONFIG_LINKS}
3574 @defmac AC_CONFIG_LINKS (@var{dest}:@var{source}@dots{}, @ovar{cmds}, @
3575   @ovar{init-cmds})
3576 @acindex{CONFIG_LINKS}
3577 @cindex Links
3578 Make @code{AC_OUTPUT} link each of the existing files @var{source} to
3579 the corresponding link name @var{dest}.  Makes a symbolic link if
3580 possible, otherwise a hard link if possible, otherwise a copy.  The
3581 @var{dest} and @var{source} names should be relative to the top level
3582 source or build directory.  This macro is one of the instantiating
3583 macros; see @ref{Configuration Actions}.
3585 For example, this call:
3587 @example
3588 AC_CONFIG_LINKS([host.h:config/$machine.h
3589                 object.h:config/$obj_format.h])
3590 @end example
3592 @noindent
3593 creates in the current directory @file{host.h} as a link to
3594 @file{@var{srcdir}/config/$machine.h}, and @file{object.h} as a
3595 link to @file{@var{srcdir}/config/$obj_format.h}.
3597 The tempting value @samp{.} for @var{dest} is invalid: it makes it
3598 impossible for @samp{config.status} to guess the links to establish.
3600 One can then run:
3601 @example
3602 ./config.status host.h object.h
3603 @end example
3604 @noindent
3605 to create the links.
3606 @end defmac
3610 @node Subdirectories
3611 @section Configuring Other Packages in Subdirectories
3612 @cindex Configure subdirectories
3613 @cindex Subdirectory configure
3615 In most situations, calling @code{AC_OUTPUT} is sufficient to produce
3616 makefiles in subdirectories.  However, @command{configure} scripts
3617 that control more than one independent package can use
3618 @code{AC_CONFIG_SUBDIRS} to run @command{configure} scripts for other
3619 packages in subdirectories.
3621 @defmac AC_CONFIG_SUBDIRS (@var{dir} @dots{})
3622 @acindex{CONFIG_SUBDIRS}
3623 @ovindex subdirs
3624 Make @code{AC_OUTPUT} run @command{configure} in each subdirectory
3625 @var{dir} in the given blank-or-newline-separated list.  Each @var{dir} should
3626 be a literal, i.e., please do not use:
3628 @example
3629 @c If you change this example, adjust tests/torture.at:Non-literal AC_CONFIG_SUBDIRS.
3630 if test "x$package_foo_enabled" = xyes; then
3631   my_subdirs="$my_subdirs foo"
3633 AC_CONFIG_SUBDIRS([$my_subdirs])
3634 @end example
3636 @noindent
3637 because this prevents @samp{./configure --help=recursive} from
3638 displaying the options of the package @code{foo}.  Instead, you should
3639 write:
3641 @example
3642 if test "x$package_foo_enabled" = xyes; then
3643   AC_CONFIG_SUBDIRS([foo])
3645 @end example
3647 If a given @var{dir} is not found at @command{configure} run time, a
3648 warning is reported; if the subdirectory is optional, write:
3650 @example
3651 if test -d "$srcdir/foo"; then
3652   AC_CONFIG_SUBDIRS([foo])
3654 @end example
3656 @c NB: Yes, below we mean configure.in, not configure.ac.
3657 If a given @var{dir} contains @command{configure.gnu}, it is run instead
3658 of @command{configure}.  This is for packages that might use a
3659 non-Autoconf script @command{Configure}, which can't be called through a
3660 wrapper @command{configure} since it would be the same file on
3661 case-insensitive file systems.  Likewise, if a @var{dir} contains
3662 @file{configure.in} but no @command{configure}, the Cygnus
3663 @command{configure} script found by @code{AC_CONFIG_AUX_DIR} is used.
3665 The subdirectory @command{configure} scripts are given the same command
3666 line options that were given to this @command{configure} script, with minor
3667 changes if needed, which include:
3669 @itemize @minus
3670 @item
3671 adjusting a relative name for the cache file;
3673 @item
3674 adjusting a relative name for the source directory;
3676 @item
3677 propagating the current value of @code{$prefix}, including if it was
3678 defaulted, and if the default values of the top level and of the subdirectory
3679 @file{configure} differ.
3680 @end itemize
3682 This macro also sets the output variable @code{subdirs} to the list of
3683 directories @samp{@var{dir} @dots{}}.  Make rules can use
3684 this variable to determine which subdirectories to recurse into.
3686 This macro may be called multiple times.
3687 @end defmac
3689 @node Default Prefix
3690 @section Default Prefix
3691 @cindex Install prefix
3692 @cindex Prefix for install
3694 By default, @command{configure} sets the prefix for files it installs to
3695 @file{/usr/local}.  The user of @command{configure} can select a different
3696 prefix using the @option{--prefix} and @option{--exec-prefix} options.
3697 There are two ways to change the default: when creating
3698 @command{configure}, and when running it.
3700 Some software packages might want to install in a directory other than
3701 @file{/usr/local} by default.  To accomplish that, use the
3702 @code{AC_PREFIX_DEFAULT} macro.
3704 @defmac AC_PREFIX_DEFAULT (@var{prefix})
3705 @acindex{PREFIX_DEFAULT}
3706 Set the default installation prefix to @var{prefix} instead of
3707 @file{/usr/local}.
3708 @end defmac
3710 It may be convenient for users to have @command{configure} guess the
3711 installation prefix from the location of a related program that they
3712 have already installed.  If you wish to do that, you can call
3713 @code{AC_PREFIX_PROGRAM}.
3715 @anchor{AC_PREFIX_PROGRAM}
3716 @defmac AC_PREFIX_PROGRAM (@var{program})
3717 @acindex{PREFIX_PROGRAM}
3718 If the user did not specify an installation prefix (using the
3719 @option{--prefix} option), guess a value for it by looking for
3720 @var{program} in @env{PATH}, the way the shell does.  If @var{program}
3721 is found, set the prefix to the parent of the directory containing
3722 @var{program}, else default the prefix as described above
3723 (@file{/usr/local} or @code{AC_PREFIX_DEFAULT}).  For example, if
3724 @var{program} is @code{gcc} and the @env{PATH} contains
3725 @file{/usr/local/gnu/bin/gcc}, set the prefix to @file{/usr/local/gnu}.
3726 @end defmac
3730 @c ======================================================== Existing tests
3732 @node Existing Tests
3733 @chapter Existing Tests
3735 These macros test for particular system features that packages might
3736 need or want to use.  If you need to test for a kind of feature that
3737 none of these macros check for, you can probably do it by calling
3738 primitive test macros with appropriate arguments (@pxref{Writing
3739 Tests}).
3741 These tests print messages telling the user which feature they're
3742 checking for, and what they find.  They cache their results for future
3743 @command{configure} runs (@pxref{Caching Results}).
3745 Some of these macros set output variables.  @xref{Makefile
3746 Substitutions}, for how to get their values.  The phrase ``define
3747 @var{name}'' is used below as a shorthand to mean ``define the C
3748 preprocessor symbol @var{name} to the value 1''.  @xref{Defining
3749 Symbols}, for how to get those symbol definitions into your program.
3751 @menu
3752 * Common Behavior::             Macros' standard schemes
3753 * Alternative Programs::        Selecting between alternative programs
3754 * Files::                       Checking for the existence of files
3755 * Libraries::                   Library archives that might be missing
3756 * Library Functions::           C library functions that might be missing
3757 * Header Files::                Header files that might be missing
3758 * Declarations::                Declarations that may be missing
3759 * Structures::                  Structures or members that might be missing
3760 * Types::                       Types that might be missing
3761 * Compilers and Preprocessors::  Checking for compiling programs
3762 * System Services::             Operating system services
3763 * Posix Variants::              Special kludges for specific Posix variants
3764 * Erlang Libraries::            Checking for the existence of Erlang libraries
3765 @end menu
3767 @node Common Behavior
3768 @section Common Behavior
3769 @cindex Common autoconf behavior
3771 Much effort has been expended to make Autoconf easy to learn.  The most
3772 obvious way to reach this goal is simply to enforce standard interfaces
3773 and behaviors, avoiding exceptions as much as possible.  Because of
3774 history and inertia, unfortunately, there are still too many exceptions
3775 in Autoconf; nevertheless, this section describes some of the common
3776 rules.
3778 @menu
3779 * Standard Symbols::            Symbols defined by the macros
3780 * Default Includes::            Includes used by the generic macros
3781 @end menu
3783 @node Standard Symbols
3784 @subsection Standard Symbols
3785 @cindex Standard symbols
3787 All the generic macros that @code{AC_DEFINE} a symbol as a result of
3788 their test transform their @var{argument} values to a standard alphabet.
3789 First, @var{argument} is converted to upper case and any asterisks
3790 (@samp{*}) are each converted to @samp{P}.  Any remaining characters
3791 that are not alphanumeric are converted to underscores.
3793 For instance,
3795 @example
3796 AC_CHECK_TYPES([struct $Expensive*])
3797 @end example
3799 @noindent
3800 defines the symbol @samp{HAVE_STRUCT__EXPENSIVEP} if the check
3801 succeeds.
3804 @node Default Includes
3805 @subsection Default Includes
3806 @cindex Default includes
3807 @cindex Includes, default
3809 Several tests depend upon a set of header files.  Since these headers
3810 are not universally available, tests actually have to provide a set of
3811 protected includes, such as:
3813 @example
3814 @group
3815 #ifdef TIME_WITH_SYS_TIME
3816 # include <sys/time.h>
3817 # include <time.h>
3818 #else
3819 # ifdef HAVE_SYS_TIME_H
3820 #  include <sys/time.h>
3821 # else
3822 #  include <time.h>
3823 # endif
3824 #endif
3825 @end group
3826 @end example
3828 @noindent
3829 Unless you know exactly what you are doing, you should avoid using
3830 unconditional includes, and check the existence of the headers you
3831 include beforehand (@pxref{Header Files}).
3833 Most generic macros use the following macro to provide the default set
3834 of includes:
3836 @defmac AC_INCLUDES_DEFAULT (@ovar{include-directives})
3837 @acindex{INCLUDES_DEFAULT}
3838 Expand to @var{include-directives} if defined, otherwise to:
3840 @example
3841 @group
3842 #include <stdio.h>
3843 #ifdef HAVE_SYS_TYPES_H
3844 # include <sys/types.h>
3845 #endif
3846 #ifdef HAVE_SYS_STAT_H
3847 # include <sys/stat.h>
3848 #endif
3849 #ifdef STDC_HEADERS
3850 # include <stdlib.h>
3851 # include <stddef.h>
3852 #else
3853 # ifdef HAVE_STDLIB_H
3854 #  include <stdlib.h>
3855 # endif
3856 #endif
3857 #ifdef HAVE_STRING_H
3858 # if !defined STDC_HEADERS && defined HAVE_MEMORY_H
3859 #  include <memory.h>
3860 # endif
3861 # include <string.h>
3862 #endif
3863 #ifdef HAVE_STRINGS_H
3864 # include <strings.h>
3865 #endif
3866 #ifdef HAVE_INTTYPES_H
3867 # include <inttypes.h>
3868 #endif
3869 #ifdef HAVE_STDINT_H
3870 # include <stdint.h>
3871 #endif
3872 #ifdef HAVE_UNISTD_H
3873 # include <unistd.h>
3874 #endif
3875 @end group
3876 @end example
3878 If the default includes are used, then check for the presence of these
3879 headers and their compatibility, i.e., you don't need to run
3880 @code{AC_HEADER_STDC}, nor check for @file{stdlib.h} etc.
3882 These headers are checked for in the same order as they are included.
3883 For instance, on some systems @file{string.h} and @file{strings.h} both
3884 exist, but conflict.  Then @code{HAVE_STRING_H} is defined, not
3885 @code{HAVE_STRINGS_H}.
3886 @end defmac
3888 @node Alternative Programs
3889 @section Alternative Programs
3890 @cindex Programs, checking
3892 These macros check for the presence or behavior of particular programs.
3893 They are used to choose between several alternative programs and to
3894 decide what to do once one has been chosen.  If there is no macro
3895 specifically defined to check for a program you need, and you don't need
3896 to check for any special properties of it, then you can use one of the
3897 general program-check macros.
3899 @menu
3900 * Particular Programs::         Special handling to find certain programs
3901 * Generic Programs::            How to find other programs
3902 @end menu
3904 @node Particular Programs
3905 @subsection Particular Program Checks
3907 These macros check for particular programs---whether they exist, and
3908 in some cases whether they support certain features.
3910 @defmac AC_PROG_AWK
3911 @acindex{PROG_AWK}
3912 @ovindex AWK
3913 @caindex prog_AWK
3914 Check for @code{gawk}, @code{mawk}, @code{nawk}, and @code{awk}, in that
3915 order, and set output variable @code{AWK} to the first one that is found.
3916 It tries @code{gawk} first because that is reported to be the
3917 best implementation.  The result can be overridden by setting the
3918 variable @code{AWK} or the cache variable @code{ac_cv_prog_AWK}.
3920 Using this macro is sufficient to avoid the pitfalls of traditional
3921 @command{awk} (@pxref{awk, , Limitations of Usual Tools}).
3922 @end defmac
3924 @defmac AC_PROG_GREP
3925 @acindex{PROG_GREP}
3926 @ovindex GREP
3927 @caindex prog_GREP
3928 Look for the best available @code{grep} or @code{ggrep} that accepts the
3929 longest input lines possible, and that supports multiple @option{-e} options.
3930 Set the output variable @code{GREP} to whatever is chosen.
3931 @xref{grep, , Limitations of Usual Tools}, for more information about
3932 portability problems with the @command{grep} command family.  The result
3933 can be overridden by setting the @code{GREP} variable and is cached in the
3934 @code{ac_cv_path_GREP} variable.
3935 @end defmac
3937 @defmac AC_PROG_EGREP
3938 @acindex{PROG_EGREP}
3939 @ovindex EGREP
3940 @caindex prog_EGREP
3941 Check whether @code{$GREP -E} works, or else look for the best available
3942 @code{egrep} or @code{gegrep} that accepts the longest input lines possible.
3943 Set the output variable @code{EGREP} to whatever is chosen.  The result
3944 can be overridden by setting the @code{EGREP} variable and is cached in the
3945 @code{ac_cv_path_EGREP} variable.
3946 @end defmac
3948 @defmac AC_PROG_FGREP
3949 @acindex{PROG_FGREP}
3950 @ovindex FGREP
3951 @caindex prog_FGREP
3952 Check whether @code{$GREP -F} works, or else look for the best available
3953 @code{fgrep} or @code{gfgrep} that accepts the longest input lines possible.
3954 Set the output variable @code{FGREP} to whatever is chosen.  The result
3955 can be overridden by setting the @code{FGREP} variable and is cached in the
3956 @code{ac_cv_path_FGREP} variable.
3957 @end defmac
3959 @defmac AC_PROG_INSTALL
3960 @acindex{PROG_INSTALL}
3961 @ovindex INSTALL
3962 @ovindex INSTALL_PROGRAM
3963 @ovindex INSTALL_DATA
3964 @ovindex INSTALL_SCRIPT
3965 @caindex path_install
3966 Set output variable @code{INSTALL} to the name of a BSD-compatible
3967 @command{install} program, if one is found in the current @env{PATH}.
3968 Otherwise, set @code{INSTALL} to @samp{@var{dir}/install-sh -c},
3969 checking the directories specified to @code{AC_CONFIG_AUX_DIR} (or its
3970 default directories) to determine @var{dir} (@pxref{Output}).  Also set
3971 the variables @code{INSTALL_PROGRAM} and @code{INSTALL_SCRIPT} to
3972 @samp{$@{INSTALL@}} and @code{INSTALL_DATA} to @samp{$@{INSTALL@} -m 644}.
3974 @samp{@@INSTALL@@} is special, as its value may vary for different
3975 configuration files.
3977 This macro screens out various instances of @command{install} known not to
3978 work.  It prefers to find a C program rather than a shell script, for
3979 speed.  Instead of @file{install-sh}, it can also use @file{install.sh},
3980 but that name is obsolete because some @command{make} programs have a rule
3981 that creates @file{install} from it if there is no makefile.  Further, this
3982 macro requires @command{install} to be able to install multiple files into a
3983 target directory in a single invocation.
3985 Autoconf comes with a copy of @file{install-sh} that you can use.  If
3986 you use @code{AC_PROG_INSTALL}, you must include either
3987 @file{install-sh} or @file{install.sh} in your distribution; otherwise
3988 @command{configure} produces an error message saying it can't find
3989 them---even if the system you're on has a good @command{install} program.
3990 This check is a safety measure to prevent you from accidentally leaving
3991 that file out, which would prevent your package from installing on
3992 systems that don't have a BSD-compatible @command{install} program.
3994 If you need to use your own installation program because it has features
3995 not found in standard @command{install} programs, there is no reason to use
3996 @code{AC_PROG_INSTALL}; just put the file name of your program into your
3997 @file{Makefile.in} files.
3999 The result of the test can be overridden by setting the variable
4000 @code{INSTALL} or the cache variable @code{ac_cv_path_install}.
4001 @end defmac
4003 @defmac AC_PROG_MKDIR_P
4004 @acindex{PROG_MKDIR_P}
4005 @ovindex MKDIR_P
4006 @caindex path_mkdir
4007 Set output variable @code{MKDIR_P} to a program that ensures that for
4008 each argument, a directory named by this argument exists, creating it
4009 and its parent directories if needed, and without race conditions when
4010 two instances of the program attempt to make the same directory at
4011 nearly the same time.
4013 This macro uses the @samp{mkdir -p} command if possible.  Otherwise, it
4014 falls back on invoking @command{install-sh} with the @option{-d} option,
4015 so your package should
4016 contain @file{install-sh} as described under @code{AC_PROG_INSTALL}.
4017 An @file{install-sh} file that predates Autoconf 2.60 or Automake 1.10
4018 is vulnerable to race conditions, so if you want to support parallel
4019 installs from
4020 different packages into the same directory you need to make sure you
4021 have an up-to-date @file{install-sh}.  In particular, be careful about
4022 using @samp{autoreconf -if} if your Automake predates Automake 1.10.
4024 This macro is related to the @code{AS_MKDIR_P} macro (@pxref{Programming
4025 in M4sh}), but it sets an output variable intended for use in other
4026 files, whereas @code{AS_MKDIR_P} is intended for use in scripts like
4027 @command{configure}.  Also, @code{AS_MKDIR_P} does not accept options,
4028 but @code{MKDIR_P} supports the @option{-m} option, e.g., a makefile
4029 might invoke @code{$(MKDIR_P) -m 0 dir} to create an inaccessible
4030 directory, and conversely a makefile should use @code{$(MKDIR_P) --
4031 $(FOO)} if @var{FOO} might yield a value that begins with @samp{-}.
4032 Finally, @code{AS_MKDIR_P} does not check for race condition
4033 vulnerability, whereas @code{AC_PROG_MKDIR_P} does.
4035 @samp{@@MKDIR_P@@} is special, as its value may vary for different
4036 configuration files.
4038 The result of the test can be overridden by setting the variable
4039 @code{MKDIR_P} or the cache variable @code{ac_cv_path_mkdir}.
4040 @end defmac
4042 @anchor{AC_PROG_LEX}
4043 @defmac AC_PROG_LEX
4044 @acindex{PROG_LEX}
4045 @ovindex LEX
4046 @ovindex LEXLIB
4047 @cvindex YYTEXT_POINTER
4048 @ovindex LEX_OUTPUT_ROOT
4049 @caindex prog_LEX
4050 If @code{flex} is found, set output variable @code{LEX} to @samp{flex}
4051 and @code{LEXLIB} to @option{-lfl}, if that library is in a standard
4052 place.  Otherwise set @code{LEX} to @samp{lex} and @code{LEXLIB} to
4053 @option{-ll}, if found.  If neither variant is available, set @code{LEX}
4054 to @samp{:}; for packages that ship the generated @file{file.yy.c}
4055 alongside the source @file{file.l}, this default allows users without a
4056 lexer generator to still build the package even if the timestamp for
4057 @file{file.l} is inadvertantly changed.
4059 Define @code{YYTEXT_POINTER} if @code{yytext} defaults to @samp{char *} instead
4060 of to @samp{char []}.  Also set output variable @code{LEX_OUTPUT_ROOT} to
4061 the base of the file name that the lexer generates; usually
4062 @file{lex.yy}, but sometimes something else.  These results vary
4063 according to whether @code{lex} or @code{flex} is being used.
4065 You are encouraged to use Flex in your sources, since it is both more
4066 pleasant to use than plain Lex and the C source it produces is portable.
4067 In order to ensure portability, however, you must either provide a
4068 function @code{yywrap} or, if you don't use it (e.g., your scanner has
4069 no @samp{#include}-like feature), simply include a @samp{%noyywrap}
4070 statement in the scanner's source.  Once this done, the scanner is
4071 portable (unless @emph{you} felt free to use nonportable constructs) and
4072 does not depend on any library.  In this case, and in this case only, it
4073 is suggested that you use this Autoconf snippet:
4075 @example
4076 AC_PROG_LEX
4077 if test "x$LEX" != xflex; then
4078   LEX="$SHELL $missing_dir/missing flex"
4079   AC_SUBST([LEX_OUTPUT_ROOT], [lex.yy])
4080   AC_SUBST([LEXLIB], [''])
4082 @end example
4084 The shell script @command{missing} can be found in the Automake
4085 distribution.
4087 Remember that the user may have supplied an alternate location in
4088 @env{LEX}, so if Flex is required, it is better to check that the user
4089 provided something sufficient by parsing the output of @samp{$LEX
4090 --version} than by simply relying on @code{test "x$LEX" = xflex}.
4092 To ensure backward compatibility, Automake's @code{AM_PROG_LEX} invokes
4093 (indirectly) this macro twice, which causes an annoying but benign
4094 ``@code{AC_PROG_LEX} invoked multiple times'' warning.  Future versions
4095 of Automake will fix this issue; meanwhile, just ignore this message.
4097 As part of running the test, this macro may delete any file in the
4098 configuration directory named @file{lex.yy.c} or @file{lexyy.c}.
4100 The result of this test can be influenced by setting the variable
4101 @code{LEX} or the cache variable @code{ac_cv_prog_LEX}.
4102 @end defmac
4104 @anchor{AC_PROG_LN_S}
4105 @defmac AC_PROG_LN_S
4106 @acindex{PROG_LN_S}
4107 @ovindex LN_S
4108 If @samp{ln -s} works on the current file system (the operating system
4109 and file system support symbolic links), set the output variable
4110 @code{LN_S} to @samp{ln -s}; otherwise, if @samp{ln} works, set
4111 @code{LN_S} to @samp{ln}, and otherwise set it to @samp{cp -p}.
4113 If you make a link in a directory other than the current directory, its
4114 meaning depends on whether @samp{ln} or @samp{ln -s} is used.  To safely
4115 create links using @samp{$(LN_S)}, either find out which form is used
4116 and adjust the arguments, or always invoke @code{ln} in the directory
4117 where the link is to be created.
4119 In other words, it does not work to do:
4120 @example
4121 $(LN_S) foo /x/bar
4122 @end example
4124 Instead, do:
4126 @example
4127 (cd /x && $(LN_S) foo bar)
4128 @end example
4129 @end defmac
4131 @defmac AC_PROG_RANLIB
4132 @acindex{PROG_RANLIB}
4133 @ovindex RANLIB
4134 @c @caindex prog_RANLIB
4135 @c @caindex prog_ac_ct_RANLIB
4136 Set output variable @code{RANLIB} to @samp{ranlib} if @code{ranlib}
4137 is found, and otherwise to @samp{:} (do nothing).
4138 @end defmac
4140 @defmac AC_PROG_SED
4141 @acindex{PROG_SED}
4142 @ovindex SED
4143 @caindex path_SED
4144 Set output variable @code{SED} to a Sed implementation that conforms to
4145 Posix and does not have arbitrary length limits.  Report an error if no
4146 acceptable Sed is found.  @xref{sed, , Limitations of Usual Tools}, for more
4147 information about portability problems with Sed.
4149 The result of this test can be overridden by setting the @code{SED} variable
4150 and is cached in the @code{ac_cv_path_SED} variable.
4151 @end defmac
4153 @defmac AC_PROG_YACC
4154 @acindex{PROG_YACC}
4155 @evindex YACC
4156 @evindex YFLAGS
4157 @ovindex YACC
4158 @caindex prog_YACC
4159 If @code{bison} is found, set output variable @code{YACC} to @samp{bison
4160 -y}.  Otherwise, if @code{byacc} is found, set @code{YACC} to
4161 @samp{byacc}.  Otherwise set @code{YACC} to @samp{yacc}.
4162 The result of this test can be influenced by setting the variable
4163 @code{YACC} or the cache variable @code{ac_cv_prog_YACC}.
4164 @end defmac
4166 @node Generic Programs
4167 @subsection Generic Program and File Checks
4169 These macros are used to find programs not covered by the ``particular''
4170 test macros.  If you need to check the behavior of a program as well as
4171 find out whether it is present, you have to write your own test for it
4172 (@pxref{Writing Tests}).  By default, these macros use the environment
4173 variable @env{PATH}.  If you need to check for a program that might not
4174 be in the user's @env{PATH}, you can pass a modified path to use
4175 instead, like this:
4177 @example
4178 AC_PATH_PROG([INETD], [inetd], [/usr/libexec/inetd],
4179              [$PATH$PATH_SEPARATOR/usr/libexec$PATH_SEPARATOR]dnl
4180 [/usr/sbin$PATH_SEPARATOR/usr/etc$PATH_SEPARATOR/etc])
4181 @end example
4183 You are strongly encouraged to declare the @var{variable} passed to
4184 @code{AC_CHECK_PROG} etc.@: as precious, @xref{Setting Output Variables},
4185 @code{AC_ARG_VAR}, for more details.
4187 @anchor{AC_CHECK_PROG}
4188 @defmac AC_CHECK_PROG (@var{variable}, @var{prog-to-check-for}, @
4189   @var{value-if-found}, @ovar{value-if-not-found}, @dvar{path, $PATH}, @
4190   @ovar{reject})
4191 @acindex{CHECK_PROG}
4192 @caindex prog_@var{variable}
4193 Check whether program @var{prog-to-check-for} exists in @var{path}.  If
4194 it is found, set @var{variable} to @var{value-if-found}, otherwise to
4195 @var{value-if-not-found}, if given.  Always pass over @var{reject} (an
4196 absolute file name) even if it is the first found in the search path; in
4197 that case, set @var{variable} using the absolute file name of the
4198 @var{prog-to-check-for} found that is not @var{reject}.  If
4199 @var{variable} was already set, do nothing.  Calls @code{AC_SUBST} for
4200 @var{variable}.  The result of this test can be overridden by setting the
4201 @var{variable} variable or the cache variable
4202 @code{ac_cv_prog_@var{variable}}.
4203 @end defmac
4205 @anchor{AC_CHECK_PROGS}
4206 @defmac AC_CHECK_PROGS (@var{variable}, @var{progs-to-check-for}, @
4207   @ovar{value-if-not-found}, @dvar{path, $PATH})
4208 @acindex{CHECK_PROGS}
4209 @caindex prog_@var{variable}
4210 Check for each program in the blank-separated list
4211 @var{progs-to-check-for} existing in the @var{path}.  If one is found, set
4212 @var{variable} to the name of that program.  Otherwise, continue
4213 checking the next program in the list.  If none of the programs in the
4214 list are found, set @var{variable} to @var{value-if-not-found}; if
4215 @var{value-if-not-found} is not specified, the value of @var{variable}
4216 is not changed.  Calls @code{AC_SUBST} for @var{variable}.  The result of
4217 this test can be overridden by setting the @var{variable} variable or the
4218 cache variable @code{ac_cv_prog_@var{variable}}.
4219 @end defmac
4221 @defmac AC_CHECK_TARGET_TOOL (@var{variable}, @var{prog-to-check-for}, @
4222   @ovar{value-if-not-found}, @dvar{path, $PATH})
4223 @acindex{CHECK_TARGET_TOOL}
4224 Like @code{AC_CHECK_PROG}, but first looks for @var{prog-to-check-for}
4225 with a prefix of the target type as determined by
4226 @code{AC_CANONICAL_TARGET}, followed by a dash (@pxref{Canonicalizing}).
4227 If the tool cannot be found with a prefix, and if the build and target
4228 types are equal, then it is also searched for without a prefix.
4230 As noted in @ref{Specifying Target Triplets}, the
4231 target is rarely specified, because most of the time it is the same
4232 as the host: it is the type of system for which any compiler tool in
4233 the package produces code.  What this macro looks for is,
4234 for example, @emph{a tool @r{(assembler, linker, etc.)}@: that the
4235 compiler driver @r{(@command{gcc} for the GNU C Compiler)}
4236 uses to produce objects, archives or executables}.
4237 @end defmac
4239 @defmac AC_CHECK_TOOL (@var{variable}, @var{prog-to-check-for}, @
4240   @ovar{value-if-not-found}, @dvar{path, $PATH})
4241 @acindex{CHECK_TOOL}
4242 @c @caindex prog_@var{VARIABLE}
4243 @c @caindex prog_ac_ct_@var{VARIABLE}
4244 Like @code{AC_CHECK_PROG}, but first looks for @var{prog-to-check-for}
4245 with a prefix of the host type as specified by @option{--host}, followed by a
4246 dash.  For example, if the user runs
4247 @samp{configure --build=x86_64-gnu --host=i386-gnu}, then this call:
4248 @example
4249 AC_CHECK_TOOL([RANLIB], [ranlib], [:])
4250 @end example
4251 @noindent
4252 sets @code{RANLIB} to @file{i386-gnu-ranlib} if that program exists in
4253 @var{path}, or otherwise to @samp{ranlib} if that program exists in
4254 @var{path}, or to @samp{:} if neither program exists.
4256 When cross-compiling, this macro will issue a warning if no program
4257 prefixed with the host type could be found.
4258 For more information, see @ref{Specifying Target Triplets}.
4259 @end defmac
4261 @defmac AC_CHECK_TARGET_TOOLS (@var{variable}, @var{progs-to-check-for}, @
4262   @ovar{value-if-not-found}, @dvar{path, $PATH})
4263 @acindex{CHECK_TARGET_TOOLS}
4264 Like @code{AC_CHECK_TARGET_TOOL}, each of the tools in the list
4265 @var{progs-to-check-for} are checked with a prefix of the target type as
4266 determined by @code{AC_CANONICAL_TARGET}, followed by a dash
4267 (@pxref{Canonicalizing}).  If none of the tools can be found with a
4268 prefix, and if the build and target types are equal, then the first one
4269 without a prefix is used.  If a tool is found, set @var{variable} to
4270 the name of that program.  If none of the tools in the list are found,
4271 set @var{variable} to @var{value-if-not-found}; if @var{value-if-not-found}
4272 is not specified, the value of @var{variable} is not changed.  Calls
4273 @code{AC_SUBST} for @var{variable}.
4274 @end defmac
4276 @defmac AC_CHECK_TOOLS (@var{variable}, @var{progs-to-check-for}, @
4277   @ovar{value-if-not-found}, @dvar{path, $PATH})
4278 @acindex{CHECK_TOOLS}
4279 Like @code{AC_CHECK_TOOL}, each of the tools in the list
4280 @var{progs-to-check-for} are checked with a prefix of the host type as
4281 determined by @code{AC_CANONICAL_HOST}, followed by a dash
4282 (@pxref{Canonicalizing}).  If none of the tools can be found with a
4283 prefix, then the first one without a prefix is used.  If a tool is found,
4284 set @var{variable} to the name of that program.  If none of the tools in
4285 the list are found, set @var{variable} to @var{value-if-not-found}; if
4286 @var{value-if-not-found} is not specified, the value of @var{variable}
4287 is not changed.  Calls @code{AC_SUBST} for @var{variable}.
4289 When cross-compiling, this macro will issue a warning if no program
4290 prefixed with the host type could be found.
4291 For more information, see @ref{Specifying Target Triplets}.
4292 @end defmac
4294 @anchor{AC_PATH_PROG}
4295 @defmac AC_PATH_PROG (@var{variable}, @var{prog-to-check-for}, @
4296   @ovar{value-if-not-found}, @dvar{path, $PATH})
4297 @acindex{PATH_PROG}
4298 @caindex path_@var{variable}
4299 Like @code{AC_CHECK_PROG}, but set @var{variable} to the absolute
4300 name of @var{prog-to-check-for} if found.  The result of this test
4301 can be overridden by setting the @var{variable} variable.  A positive
4302 result of this test is cached in the @code{ac_cv_path_@var{variable}}
4303 variable.
4304 @end defmac
4306 @anchor{AC_PATH_PROGS}
4307 @defmac AC_PATH_PROGS (@var{variable}, @var{progs-to-check-for}, @
4308   @ovar{value-if-not-found}, @dvar{path, $PATH})
4309 @acindex{PATH_PROGS}
4310 @caindex path_@var{variable}
4311 Like @code{AC_CHECK_PROGS}, but if any of @var{progs-to-check-for}
4312 are found, set @var{variable} to the absolute name of the program
4313 found.  The result of this test can be overridden by setting the
4314 @var{variable} variable.  A positive result of this test is cached in
4315 the @code{ac_cv_path_@var{variable}} variable.
4316 @end defmac
4318 @defmac AC_PATH_PROGS_FEATURE_CHECK (@var{variable}, @
4319   @var{progs-to-check-for}, @var{feature-test}, @
4320   @ovar{action-if-not-found}, @dvar{path, $PATH})
4321 @acindex{PATH_PROGS_FEATURE_CHECK}
4322 @caindex path_@var{variable}
4323 This macro was introduced in Autoconf 2.62.  If @var{variable} is not
4324 empty, then set the cache variable @code{ac_cv_path_@var{variable}} to
4325 its value.  Otherwise, check for each program in the blank-separated
4326 list @var{progs-to-check-for} existing in @var{path}.  For each program
4327 found, execute @var{feature-test} with @code{ac_path_@var{variable}}
4328 set to the absolute name of the candidate program.  If no invocation of
4329 @var{feature-test} sets the shell variable
4330 @code{ac_cv_path_@var{variable}}, then @var{action-if-not-found} is
4331 executed.  @var{feature-test} will be run even when
4332 @code{ac_cv_path_@var{variable}} is set, to provide the ability to
4333 choose a better candidate found later in @var{path}; to accept the
4334 current setting and bypass all futher checks, @var{feature-test} can
4335 execute @code{ac_path_@var{variable}_found=:}.
4337 Note that this macro has some subtle differences from
4338 @code{AC_CHECK_PROGS}.  It is designed to be run inside
4339 @code{AC_CACHE_VAL}, therefore, it should have no side effects.  In
4340 particular, @var{variable} is not set to the final value of
4341 @code{ac_cv_path_@var{variable}}, nor is @code{AC_SUBST} automatically
4342 run.  Also, on failure, any action can be performed, whereas
4343 @code{AC_CHECK_PROGS} only performs
4344 @code{@var{variable}=@var{value-if-not-found}}.
4346 Here is an example, similar to what Autoconf uses in its own configure
4347 script.  It will search for an implementation of @command{m4} that
4348 supports the @code{indir} builtin, even if it goes by the name
4349 @command{gm4} or is not the first implementation on @env{PATH}.
4351 @example
4352 AC_CACHE_CHECK([for m4 that supports indir], [ac_cv_path_M4],
4353   [AC_PATH_PROGS_FEATURE_CHECK([M4], [m4 gm4],
4354     [[m4out=`echo 'changequote([,])indir([divnum])' | $ac_path_M4`
4355       test "x$m4out" = x0 \
4356       && ac_cv_path_M4=$ac_path_M4 ac_path_M4_found=:]],
4357     [AC_MSG_ERROR([could not find m4 that supports indir])])])
4358 AC_SUBST([M4], [$ac_cv_path_M4])
4359 @end example
4360 @end defmac
4362 @defmac AC_PATH_TARGET_TOOL (@var{variable}, @var{prog-to-check-for}, @
4363   @ovar{value-if-not-found}, @dvar{path, $PATH})
4364 @acindex{PATH_TARGET_TOOL}
4365 Like @code{AC_CHECK_TARGET_TOOL}, but set @var{variable} to the absolute
4366 name of the program if it is found.
4367 @end defmac
4369 @defmac AC_PATH_TOOL (@var{variable}, @var{prog-to-check-for}, @
4370   @ovar{value-if-not-found}, @dvar{path, $PATH})
4371 @acindex{PATH_TOOL}
4372 Like @code{AC_CHECK_TOOL}, but set @var{variable} to the absolute
4373 name of the program if it is found.
4375 When cross-compiling, this macro will issue a warning if no program
4376 prefixed with the host type could be found.
4377 For more information, see @ref{Specifying Target Triplets}.
4378 @end defmac
4381 @node Files
4382 @section Files
4383 @cindex File, checking
4385 You might also need to check for the existence of files.  Before using
4386 these macros, ask yourself whether a runtime test might not be a better
4387 solution.  Be aware that, like most Autoconf macros, they test a feature
4388 of the host machine, and therefore, they die when cross-compiling.
4390 @defmac AC_CHECK_FILE (@var{file}, @ovar{action-if-found}, @
4391   @ovar{action-if-not-found})
4392 @acindex{CHECK_FILE}
4393 @caindex file_@var{file}
4394 Check whether file @var{file} exists on the native system.  If it is
4395 found, execute @var{action-if-found}, otherwise do
4396 @var{action-if-not-found}, if given.  The result of this test is cached
4397 in the @code{ac_cv_file_@var{file}} variable, with characters not
4398 suitable for a variable name mapped to underscores.
4399 @end defmac
4401 @defmac AC_CHECK_FILES (@var{files}, @ovar{action-if-found}, @
4402   @ovar{action-if-not-found})
4403 @acindex{CHECK_FILES}
4404 @caindex file_@var{file}
4405 Executes @code{AC_CHECK_FILE} once for each file listed in @var{files}.
4406 Additionally, defines @samp{HAVE_@var{file}} (@pxref{Standard Symbols})
4407 for each file found.  The results of each test are cached in the
4408 @code{ac_cv_file_@var{file}} variable, with characters not suitable for
4409 a variable name mapped to underscores.
4410 @end defmac
4413 @node Libraries
4414 @section Library Files
4415 @cindex Library, checking
4417 The following macros check for the presence of certain C, C++, or Fortran
4418 library archive files.
4420 @anchor{AC_CHECK_LIB}
4421 @defmac AC_CHECK_LIB (@var{library}, @var{function}, @
4422   @ovar{action-if-found}, @ovar{action-if-not-found}, @ovar{other-libraries})
4423 @acindex{CHECK_LIB}
4424 @caindex lib_@var{library}_@var{function}
4425 Test whether the library @var{library} is available by trying to link
4426 a test program that calls function @var{function} with the library.
4427 @var{function} should be a function provided by the library.
4428 Use the base
4429 name of the library; e.g., to check for @option{-lmp}, use @samp{mp} as
4430 the @var{library} argument.
4432 @var{action-if-found} is a list of shell commands to run if the link
4433 with the library succeeds; @var{action-if-not-found} is a list of shell
4434 commands to run if the link fails.  If @var{action-if-found} is not
4435 specified, the default action prepends @option{-l@var{library}} to
4436 @code{LIBS} and defines @samp{HAVE_LIB@var{library}} (in all
4437 capitals).  This macro is intended to support building @code{LIBS} in
4438 a right-to-left (least-dependent to most-dependent) fashion such that
4439 library dependencies are satisfied as a natural side effect of
4440 consecutive tests.  Linkers are sensitive to library ordering
4441 so the order in which @code{LIBS} is generated is important to reliable
4442 detection of libraries.
4444 If linking with @var{library} results in unresolved symbols that would
4445 be resolved by linking with additional libraries, give those libraries
4446 as the @var{other-libraries} argument, separated by spaces:
4447 e.g., @option{-lXt -lX11}.  Otherwise, this macro may fail to detect
4448 that @var{library} is present, because linking the test program can
4449 fail with unresolved symbols.  The @var{other-libraries} argument
4450 should be limited to cases where it is desirable to test for one library
4451 in the presence of another that is not already in @code{LIBS}.
4453 @code{AC_CHECK_LIB} requires some care in usage, and should be avoided
4454 in some common cases.  Many standard functions like @code{gethostbyname}
4455 appear in the standard C library on some hosts, and in special libraries
4456 like @code{nsl} on other hosts.  On some hosts the special libraries
4457 contain variant implementations that you may not want to use.  These
4458 days it is normally better to use @code{AC_SEARCH_LIBS([gethostbyname],
4459 [nsl])} instead of @code{AC_CHECK_LIB([nsl], [gethostbyname])}.
4461 The result of this test is cached in the
4462 @code{ac_cv_lib_@var{library}_@var{function}} variable.
4463 @end defmac
4465 @anchor{AC_SEARCH_LIBS}
4466 @defmac AC_SEARCH_LIBS (@var{function}, @var{search-libs}, @
4467   @ovar{action-if-found}, @ovar{action-if-not-found}, @ovar{other-libraries})
4468 @acindex{SEARCH_LIBS}
4469 @caindex search_@var{function}
4470 Search for a library defining @var{function} if it's not already
4471 available.  This equates to calling
4472 @samp{AC_LINK_IFELSE([AC_LANG_CALL([], [@var{function}])])} first with
4473 no libraries, then for each library listed in @var{search-libs}.
4475 Prepend @option{-l@var{library}} to @code{LIBS} for the first library found
4476 to contain @var{function}, and run @var{action-if-found}.  If the
4477 function is not found, run @var{action-if-not-found}.
4479 If linking with @var{library} results in unresolved symbols that would
4480 be resolved by linking with additional libraries, give those libraries
4481 as the @var{other-libraries} argument, separated by spaces:
4482 e.g., @option{-lXt -lX11}.  Otherwise, this macro fails to detect
4483 that @var{function} is present, because linking the test program
4484 always fails with unresolved symbols.
4486 The result of this test is cached in the
4487 @code{ac_cv_search_@var{function}} variable as @samp{none required} if
4488 @var{function} is already available, as @samp{no} if no library
4489 containing @var{function} was found, otherwise as the
4490 @option{-l@var{library}} option that needs to be prepended to @code{LIBS}.
4491 @end defmac
4495 @node Library Functions
4496 @section Library Functions
4498 The following macros check for particular C library functions.
4499 If there is no macro specifically defined to check for a function you need,
4500 and you don't need to check for any special properties of
4501 it, then you can use one of the general function-check macros.
4503 @menu
4504 * Function Portability::        Pitfalls with usual functions
4505 * Particular Functions::        Special handling to find certain functions
4506 * Generic Functions::           How to find other functions
4507 @end menu
4509 @node Function Portability
4510 @subsection Portability of C Functions
4511 @cindex Portability of C functions
4512 @cindex C function portability
4514 Most usual functions can either be missing, or be buggy, or be limited
4515 on some architectures.  This section tries to make an inventory of these
4516 portability issues.  By definition, this list always requires
4517 additions.  Please help us keeping it as complete as possible.
4519 @table @asis
4520 @item @code{exit}
4521 @c @fuindex exit
4522 @prindex @code{exit}
4523 On ancient hosts, @code{exit} returned @code{int}.
4524 This is because @code{exit} predates @code{void}, and there was a long
4525 tradition of it returning @code{int}.
4527 On current hosts, the problem more likely is that @code{exit} is not
4528 declared, due to C++ problems of some sort or another.  For this reason
4529 we suggest that test programs not invoke @code{exit}, but return from
4530 @code{main} instead.
4532 @item @code{free}
4533 @c @fuindex free
4534 @prindex @code{free}
4535 The C standard says a call @code{free (NULL)} does nothing, but
4536 some old systems don't support this (e.g., NextStep).
4538 @item @code{isinf}
4539 @itemx @code{isnan}
4540 @c @fuindex isinf
4541 @c @fuindex isnan
4542 @prindex @code{isinf}
4543 @prindex @code{isnan}
4544 The C99 standard says that @code{isinf} and @code{isnan} are
4545 macros.  On some systems just macros are available
4546 (e.g., HP-UX and Solaris 10), on
4547 some systems both macros and functions (e.g., glibc 2.3.2), and on some
4548 systems only functions (e.g., IRIX 6 and Solaris 9).  In some cases
4549 these functions are declared in nonstandard headers like
4550 @code{<sunmath.h>} and defined in non-default libraries like
4551 @option{-lm} or @option{-lsunmath}.
4553 The C99 @code{isinf} and @code{isnan} macros work correctly with
4554 @code{long double} arguments, but pre-C99 systems that use functions
4555 typically assume @code{double} arguments.  On such a system,
4556 @code{isinf} incorrectly returns true for a finite @code{long double}
4557 argument that is outside the range of @code{double}.
4559 The best workaround for these issues is to use gnulib modules
4560 @code{isinf} and @code{isnan} (@pxref{Gnulib}).  But a lighter weight
4561 solution involves code like the following.
4563 @smallexample
4564 #include <math.h>
4566 #ifndef isnan
4567 # define isnan(x) \
4568     (sizeof (x) == sizeof (long double) ? isnan_ld (x) \
4569      : sizeof (x) == sizeof (double) ? isnan_d (x) \
4570      : isnan_f (x))
4571 static inline int isnan_f  (float       x) @{ return x != x; @}
4572 static inline int isnan_d  (double      x) @{ return x != x; @}
4573 static inline int isnan_ld (long double x) @{ return x != x; @}
4574 #endif
4576 #ifndef isinf
4577 # define isinf(x) \
4578     (sizeof (x) == sizeof (long double) ? isinf_ld (x) \
4579      : sizeof (x) == sizeof (double) ? isinf_d (x) \
4580      : isinf_f (x))
4581 static inline int isinf_f  (float       x)
4582 @{ return !isnan (x) && isnan (x - x); @}
4583 static inline int isinf_d  (double      x)
4584 @{ return !isnan (x) && isnan (x - x); @}
4585 static inline int isinf_ld (long double x)
4586 @{ return !isnan (x) && isnan (x - x); @}
4587 #endif
4588 @end smallexample
4590 Use @code{AC_C_INLINE} (@pxref{C Compiler}) so that this code works on
4591 compilers that lack the @code{inline} keyword.  Some optimizing
4592 compilers mishandle these definitions, but systems with that bug
4593 typically have many other floating point corner-case compliance problems
4594 anyway, so it's probably not worth worrying about.
4596 @item @code{malloc}
4597 @c @fuindex malloc
4598 @prindex @code{malloc}
4599 The C standard says a call @code{malloc (0)} is implementation
4600 dependent.  It can return either @code{NULL} or a new non-null pointer.
4601 The latter is more common (e.g., the GNU C Library) but is by
4602 no means universal.  @code{AC_FUNC_MALLOC}
4603 can be used to insist on non-@code{NULL} (@pxref{Particular Functions}).
4605 @item @code{putenv}
4606 @c @fuindex putenv
4607 @prindex @code{putenv}
4608 Posix prefers @code{setenv} to @code{putenv}; among other things,
4609 @code{putenv} is not required of all Posix implementations, but
4610 @code{setenv} is.
4612 Posix specifies that @code{putenv} puts the given string directly in
4613 @code{environ}, but some systems make a copy of it instead (e.g.,
4614 glibc 2.0, or BSD).  And when a copy is made, @code{unsetenv} might
4615 not free it, causing a memory leak (e.g., FreeBSD 4).
4617 On some systems @code{putenv ("FOO")} removes @samp{FOO} from the
4618 environment, but this is not standard usage and it dumps core
4619 on some systems (e.g., AIX).
4621 On MinGW, a call @code{putenv ("FOO=")} removes @samp{FOO} from the
4622 environment, rather than inserting it with an empty value.
4624 @item @code{realloc}
4625 @c @fuindex realloc
4626 @prindex @code{realloc}
4627 The C standard says a call @code{realloc (NULL, size)} is equivalent
4628 to @code{malloc (size)}, but some old systems don't support this (e.g.,
4629 NextStep).
4631 @item @code{signal} handler
4632 @c @fuindex signal
4633 @prindex @code{signal}
4634 @prindex @code{sigaction}
4635 Normally @code{signal} takes a handler function with a return type of
4636 @code{void}, but some old systems required @code{int} instead.  Any
4637 actual @code{int} value returned is not used; this is only a
4638 difference in the function prototype demanded.
4640 All systems we know of in current use return @code{void}.  The
4641 @code{int} was to support K&R C, where of course @code{void} is not
4642 available.  The obsolete macro @code{AC_TYPE_SIGNAL}
4643 (@pxref{AC_TYPE_SIGNAL}) can be used to establish the correct type in
4644 all cases.
4646 In most cases, it is more robust to use @code{sigaction} when it is
4647 available, rather than @code{signal}.
4649 @item @code{snprintf}
4650 @c @fuindex snprintf
4651 @prindex @code{snprintf}
4652 @c @fuindex vsnprintf
4653 @prindex @code{vsnprintf}
4654 The C99 standard says that if the output array isn't big enough
4655 and if no other errors occur, @code{snprintf} and @code{vsnprintf}
4656 truncate the output and return the number of bytes that ought to have
4657 been produced.  Some older systems return the truncated length (e.g.,
4658 GNU C Library 2.0.x or IRIX 6.5), some a negative value
4659 (e.g., earlier GNU C Library versions), and some the buffer
4660 length without truncation (e.g., 32-bit Solaris 7).  Also, some buggy
4661 older systems ignore the length and overrun the buffer (e.g., 64-bit
4662 Solaris 7).
4664 @item @code{sprintf}
4665 @c @fuindex sprintf
4666 @prindex @code{sprintf}
4667 @c @fuindex vsprintf
4668 @prindex @code{vsprintf}
4669 The C standard says @code{sprintf} and @code{vsprintf} return the
4670 number of bytes written.  On some ancient systems (SunOS 4 for
4671 instance) they return the buffer pointer instead, but these no
4672 longer need to be worried about.
4674 @item @code{sscanf}
4675 @c @fuindex sscanf
4676 @prindex @code{sscanf}
4677 On various old systems, e.g., HP-UX 9, @code{sscanf} requires
4678 that its
4679 input string be writable (though it doesn't actually change it).  This
4680 can be a problem when using @command{gcc} since it normally puts
4681 constant strings in read-only memory (@pxref{Incompatibilities,
4682 Incompatibilities of GCC, , gcc, Using and
4683 Porting the GNU Compiler Collection}).  Apparently in some cases even
4684 having format strings read-only can be a problem.
4686 @item @code{strerror_r}
4687 @c @fuindex strerror_r
4688 @prindex @code{strerror_r}
4689 Posix specifies that @code{strerror_r} returns an @code{int}, but many
4690 systems (e.g., GNU C Library version 2.2.4) provide a
4691 different version returning a @code{char *}.  @code{AC_FUNC_STRERROR_R}
4692 can detect which is in use (@pxref{Particular Functions}).
4694 @item @code{strnlen}
4695 @c @fuindex strnlen
4696 @prindex @code{strnlen}
4697 AIX 4.3 provides a broken version which produces the
4698 following results:
4700 @example
4701 strnlen ("foobar", 0) = 0
4702 strnlen ("foobar", 1) = 3
4703 strnlen ("foobar", 2) = 2
4704 strnlen ("foobar", 3) = 1
4705 strnlen ("foobar", 4) = 0
4706 strnlen ("foobar", 5) = 6
4707 strnlen ("foobar", 6) = 6
4708 strnlen ("foobar", 7) = 6
4709 strnlen ("foobar", 8) = 6
4710 strnlen ("foobar", 9) = 6
4711 @end example
4713 @item @code{sysconf}
4714 @c @fuindex sysconf
4715 @prindex @code{sysconf}
4716 @code{_SC_PAGESIZE} is standard, but some older systems (e.g., HP-UX
4717 9) have @code{_SC_PAGE_SIZE} instead.  This can be tested with
4718 @code{#ifdef}.
4720 @item @code{unlink}
4721 @c @fuindex unlink
4722 @prindex @code{unlink}
4723 The Posix spec says that @code{unlink} causes the given file to be
4724 removed only after there are no more open file handles for it.  Some
4725 non-Posix hosts have trouble with this requirement, though,
4726 and some DOS variants even corrupt the file system.
4728 @item @code{unsetenv}
4729 @c @fuindex unsetenv
4730 @prindex @code{unsetenv}
4731 On MinGW, @code{unsetenv} is not available, but a variable @samp{FOO}
4732 can be removed with a call @code{putenv ("FOO=")}, as described under
4733 @code{putenv} above.
4735 @item @code{va_copy}
4736 @c @fuindex va_copy
4737 @prindex @code{va_copy}
4738 The C99 standard provides @code{va_copy} for copying
4739 @code{va_list} variables.  It may be available in older environments
4740 too, though possibly as @code{__va_copy} (e.g., @command{gcc} in strict
4741 pre-C99 mode).  These can be tested with @code{#ifdef}.  A fallback to
4742 @code{memcpy (&dst, &src, sizeof (va_list))} gives maximum
4743 portability.
4745 @item @code{va_list}
4746 @c @fuindex va_list
4747 @prindex @code{va_list}
4748 @code{va_list} is not necessarily just a pointer.  It can be a
4749 @code{struct} (e.g., @command{gcc} on Alpha), which means @code{NULL} is
4750 not portable.  Or it can be an array (e.g., @command{gcc} in some
4751 PowerPC configurations), which means as a function parameter it can be
4752 effectively call-by-reference and library routines might modify the
4753 value back in the caller (e.g., @code{vsnprintf} in the GNU C Library
4754 2.1).
4756 @item Signed @code{>>}
4757 Normally the C @code{>>} right shift of a signed type replicates the
4758 high bit, giving a so-called ``arithmetic'' shift.  But care should be
4759 taken since Standard C doesn't require that behavior.  On those
4760 few processors without a native arithmetic shift (for instance Cray
4761 vector systems) zero bits may be shifted in, the same as a shift of an
4762 unsigned type.
4764 @item Integer @code{/}
4765 C divides signed integers by truncating their quotient toward zero,
4766 yielding the same result as Fortran.  However, before C99 the standard
4767 allowed C implementations to take the floor or ceiling of the quotient
4768 in some cases.  Hardly any implementations took advantage of this
4769 freedom, though, and it's probably not worth worrying about this issue
4770 nowadays.
4771 @end table
4774 @node Particular Functions
4775 @subsection Particular Function Checks
4776 @cindex Function, checking
4778 These macros check for particular C functions---whether they exist, and
4779 in some cases how they respond when given certain arguments.
4781 @anchor{AC_FUNC_ALLOCA}
4782 @defmac AC_FUNC_ALLOCA
4783 @acindex{FUNC_ALLOCA}
4784 @cvindex C_ALLOCA
4785 @cvindex HAVE_ALLOCA_H
4786 @ovindex ALLOCA
4787 @c @fuindex alloca
4788 @prindex @code{alloca}
4789 @hdrindex{alloca.h}
4790 @c @caindex working_alloca_h
4791 Check how to get @code{alloca}.  Tries to get a builtin version by
4792 checking for @file{alloca.h} or the predefined C preprocessor macros
4793 @code{__GNUC__} and @code{_AIX}.  If this macro finds @file{alloca.h},
4794 it defines @code{HAVE_ALLOCA_H}.
4796 If those attempts fail, it looks for the function in the standard C
4797 library.  If any of those methods succeed, it defines
4798 @code{HAVE_ALLOCA}.  Otherwise, it sets the output variable
4799 @code{ALLOCA} to @samp{$@{LIBOBJDIR@}alloca.o} and defines
4800 @code{C_ALLOCA} (so programs can periodically call @samp{alloca (0)} to
4801 garbage collect).  This variable is separate from @code{LIBOBJS} so
4802 multiple programs can share the value of @code{ALLOCA} without needing
4803 to create an actual library, in case only some of them use the code in
4804 @code{LIBOBJS}.  The @samp{$@{LIBOBJDIR@}} prefix serves the same
4805 purpose as in @code{LIBOBJS} (@pxref{AC_LIBOBJ vs LIBOBJS}).
4807 This macro does not try to get @code{alloca} from the System V R3
4808 @file{libPW} or the System V R4 @file{libucb} because those libraries
4809 contain some incompatible functions that cause trouble.  Some versions
4810 do not even contain @code{alloca} or contain a buggy version.  If you
4811 still want to use their @code{alloca}, use @code{ar} to extract
4812 @file{alloca.o} from them instead of compiling @file{alloca.c}.
4814 Source files that use @code{alloca} should start with a piece of code
4815 like the following, to declare it properly.
4817 @example
4818 @group
4819 #ifdef HAVE_ALLOCA_H
4820 # include <alloca.h>
4821 #elif defined __GNUC__
4822 # define alloca __builtin_alloca
4823 #elif defined _AIX
4824 # define alloca __alloca
4825 #elif defined _MSC_VER
4826 # include <malloc.h>
4827 # define alloca _alloca
4828 #else
4829 # include <stddef.h>
4830 # ifdef  __cplusplus
4831 extern "C"
4832 # endif
4833 void *alloca (size_t);
4834 #endif
4835 @end group
4836 @end example
4837 @end defmac
4839 @defmac AC_FUNC_CHOWN
4840 @acindex{FUNC_CHOWN}
4841 @cvindex HAVE_CHOWN
4842 @c @fuindex chown
4843 @prindex @code{chown}
4844 @caindex func_chown_works
4845 If the @code{chown} function is available and works (in particular, it
4846 should accept @option{-1} for @code{uid} and @code{gid}), define
4847 @code{HAVE_CHOWN}.  The result of this macro is cached in the
4848 @code{ac_cv_func_chown_works} variable.
4849 @end defmac
4851 @anchor{AC_FUNC_CLOSEDIR_VOID}
4852 @defmac AC_FUNC_CLOSEDIR_VOID
4853 @acindex{FUNC_CLOSEDIR_VOID}
4854 @cvindex CLOSEDIR_VOID
4855 @c @fuindex closedir
4856 @prindex @code{closedir}
4857 @caindex func_closedir_void
4858 If the @code{closedir} function does not return a meaningful value,
4859 define @code{CLOSEDIR_VOID}.  Otherwise, callers ought to check its
4860 return value for an error indicator.
4862 Currently this test is implemented by running a test program.  When
4863 cross compiling the pessimistic assumption that @code{closedir} does not
4864 return a meaningful value is made.
4866 The result of this macro is cached in the @code{ac_cv_func_closedir_void}
4867 variable.
4869 This macro is obsolescent, as @code{closedir} returns a meaningful value
4870 on current systems.  New programs need not use this macro.
4871 @end defmac
4873 @defmac AC_FUNC_ERROR_AT_LINE
4874 @acindex{FUNC_ERROR_AT_LINE}
4875 @c @fuindex error_at_line
4876 @prindex @code{error_at_line}
4877 @caindex lib_error_at_line
4878 If the @code{error_at_line} function is not found, require an
4879 @code{AC_LIBOBJ} replacement of @samp{error}.
4881 The result of this macro is cached in the @code{ac_cv_lib_error_at_line}
4882 variable.
4883 @end defmac
4885 @defmac AC_FUNC_FNMATCH
4886 @acindex{FUNC_FNMATCH}
4887 @c @fuindex fnmatch
4888 @prindex @code{fnmatch}
4889 @caindex func_fnmatch_works
4890 If the @code{fnmatch} function conforms to Posix, define
4891 @code{HAVE_FNMATCH}.  Detect common implementation bugs, for example,
4892 the bugs in Solaris 2.4.
4894 Unlike the other specific
4895 @code{AC_FUNC} macros, @code{AC_FUNC_FNMATCH} does not replace a
4896 broken/missing @code{fnmatch}.  This is for historical reasons.
4897 See @code{AC_REPLACE_FNMATCH} below.
4899 The result of this macro is cached in the @code{ac_cv_func_fnmatch_works}
4900 variable.
4902 This macro is obsolescent.  New programs should use Gnulib's
4903 @code{fnmatch-posix} module.  @xref{Gnulib}.
4904 @end defmac
4906 @defmac AC_FUNC_FNMATCH_GNU
4907 @acindex{FUNC_FNMATCH_GNU}
4908 @c @fuindex fnmatch
4909 @prindex @code{fnmatch}
4910 @caindex func_fnmatch_gnu
4911 Behave like @code{AC_REPLACE_FNMATCH} (@emph{replace}) but also test
4912 whether @code{fnmatch} supports GNU extensions.  Detect common
4913 implementation bugs, for example, the bugs in the GNU C
4914 Library 2.1.
4916 The result of this macro is cached in the @code{ac_cv_func_fnmatch_gnu}
4917 variable.
4919 This macro is obsolescent.  New programs should use Gnulib's
4920 @code{fnmatch-gnu} module.  @xref{Gnulib}.
4921 @end defmac
4923 @anchor{AC_FUNC_FORK}
4924 @defmac AC_FUNC_FORK
4925 @acindex{FUNC_FORK}
4926 @cvindex HAVE_VFORK_H
4927 @cvindex HAVE_WORKING_FORK
4928 @cvindex HAVE_WORKING_VFORK
4929 @cvindex vfork
4930 @c @fuindex fork
4931 @prindex @code{fork}
4932 @c @fuindex vfork
4933 @prindex @code{vfork}
4934 @hdrindex{vfork.h}
4935 @c @caindex func_fork
4936 @c @caindex func_fork_works
4937 This macro checks for the @code{fork} and @code{vfork} functions.  If a
4938 working @code{fork} is found, define @code{HAVE_WORKING_FORK}.  This macro
4939 checks whether @code{fork} is just a stub by trying to run it.
4941 If @file{vfork.h} is found, define @code{HAVE_VFORK_H}.  If a working
4942 @code{vfork} is found, define @code{HAVE_WORKING_VFORK}.  Otherwise,
4943 define @code{vfork} to be @code{fork} for backward compatibility with
4944 previous versions of @command{autoconf}.  This macro checks for several known
4945 errors in implementations of @code{vfork} and considers the system to not
4946 have a working @code{vfork} if it detects any of them.  It is not considered
4947 to be an implementation error if a child's invocation of @code{signal}
4948 modifies the parent's signal handler, since child processes rarely change
4949 their signal handlers.
4951 Since this macro defines @code{vfork} only for backward compatibility with
4952 previous versions of @command{autoconf} you're encouraged to define it
4953 yourself in new code:
4954 @example
4955 @group
4956 #ifndef HAVE_WORKING_VFORK
4957 # define vfork fork
4958 #endif
4959 @end group
4960 @end example
4961 @end defmac
4963 @defmac AC_FUNC_FSEEKO
4964 @acindex{FUNC_FSEEKO}
4965 @cvindex _LARGEFILE_SOURCE
4966 @cvindex HAVE_FSEEKO
4967 @c @fuindex fseeko
4968 @prindex @code{fseeko}
4969 @c @fuindex ftello
4970 @prindex @code{ftello}
4971 @c @caindex sys_largefile_source
4972 If the @code{fseeko} function is available, define @code{HAVE_FSEEKO}.
4973 Define @code{_LARGEFILE_SOURCE} if necessary to make the prototype
4974 visible on some systems (e.g., glibc 2.2).  Otherwise linkage problems
4975 may occur when compiling with @code{AC_SYS_LARGEFILE} on
4976 largefile-sensitive systems where @code{off_t} does not default to a
4977 64bit entity.  All systems with @code{fseeko} also supply @code{ftello}.
4978 @end defmac
4980 @defmac AC_FUNC_GETGROUPS
4981 @acindex{FUNC_GETGROUPS}
4982 @cvindex HAVE_GETGROUPS
4983 @ovindex GETGROUPS_LIBS
4984 @c @fuindex getgroups
4985 @prindex @code{getgroups}
4986 @caindex func_getgroups_works
4987 If the @code{getgroups} function is available and works (unlike on
4988 Ultrix 4.3, where @samp{getgroups (0, 0)} always fails), define
4989 @code{HAVE_GETGROUPS}.  Set @code{GETGROUPS_LIBS} to any libraries
4990 needed to get that function.  This macro runs @code{AC_TYPE_GETGROUPS}.
4991 @end defmac
4993 @anchor{AC_FUNC_GETLOADAVG}
4994 @defmac AC_FUNC_GETLOADAVG
4995 @acindex{FUNC_GETLOADAVG}
4996 @cvindex SVR4
4997 @cvindex DGUX
4998 @cvindex UMAX
4999 @cvindex UMAX4_3
5000 @cvindex HAVE_NLIST_H
5001 @cvindex NLIST_NAME_UNION
5002 @cvindex GETLOADAVG_PRIVILEGED
5003 @cvindex NEED_SETGID
5004 @cvindex C_GETLOADAVG
5005 @ovindex LIBOBJS
5006 @ovindex NEED_SETGID
5007 @ovindex KMEM_GROUP
5008 @ovindex GETLOADAVG_LIBS
5009 @c @fuindex getloadavg
5010 @prindex @code{getloadavg}
5011 Check how to get the system load averages.  To perform its tests
5012 properly, this macro needs the file @file{getloadavg.c}; therefore, be
5013 sure to set the @code{AC_LIBOBJ} replacement directory properly (see
5014 @ref{Generic Functions}, @code{AC_CONFIG_LIBOBJ_DIR}).
5016 If the system has the @code{getloadavg} function, define
5017 @code{HAVE_GETLOADAVG}, and set @code{GETLOADAVG_LIBS} to any libraries
5018 necessary to get that function.  Also add @code{GETLOADAVG_LIBS} to
5019 @code{LIBS}.  Otherwise, require an @code{AC_LIBOBJ} replacement for
5020 @samp{getloadavg} with source code in @file{@var{dir}/getloadavg.c}, and
5021 possibly define several other C preprocessor macros and output
5022 variables:
5024 @enumerate
5025 @item
5026 Define @code{C_GETLOADAVG}.
5028 @item
5029 Define @code{SVR4}, @code{DGUX}, @code{UMAX}, or @code{UMAX4_3} if on
5030 those systems.
5032 @item
5033 @hdrindex{nlist.h}
5034 If @file{nlist.h} is found, define @code{HAVE_NLIST_H}.
5036 @item
5037 If @samp{struct nlist} has an @samp{n_un.n_name} member, define
5038 @code{HAVE_STRUCT_NLIST_N_UN_N_NAME}.  The obsolete symbol
5039 @code{NLIST_NAME_UNION} is still defined, but do not depend upon it.
5041 @item
5042 Programs may need to be installed set-group-ID (or set-user-ID) for
5043 @code{getloadavg} to work.  In this case, define
5044 @code{GETLOADAVG_PRIVILEGED}, set the output variable @code{NEED_SETGID}
5045 to @samp{true} (and otherwise to @samp{false}), and set
5046 @code{KMEM_GROUP} to the name of the group that should own the installed
5047 program.
5048 @end enumerate
5050 The @code{AC_FUNC_GETLOADAVG} macro is obsolescent.  New programs should
5051 use Gnulib's @code{getloadavg} module.  @xref{Gnulib}.
5052 @end defmac
5054 @anchor{AC_FUNC_GETMNTENT}
5055 @defmac AC_FUNC_GETMNTENT
5056 @acindex{FUNC_GETMNTENT}
5057 @cvindex HAVE_GETMNTENT
5058 @c @fuindex getmntent
5059 @prindex @code{getmntent}
5060 @caindex search_getmntent
5061 Check for @code{getmntent} in the standard C library, and then in the
5062 @file{sun}, @file{seq}, and @file{gen} libraries, for UNICOS,
5063 IRIX 4, PTX, and UnixWare, respectively.  Then, if
5064 @code{getmntent} is available, define @code{HAVE_GETMNTENT} and set
5065 @code{ac_cv_func_getmntent} to @code{yes}.  Otherwise set
5066 @code{ac_cv_func_getmntent} to @code{no}.
5068 The result of this macro can be overridden by setting the cache variable
5069 @code{ac_cv_search_getmntent}.
5070 @end defmac
5072 @defmac AC_FUNC_GETPGRP
5073 @acindex{FUNC_GETPGRP}
5074 @cvindex GETPGRP_VOID
5075 @c @fuindex getpgid
5076 @c @fuindex getpgrp
5077 @prindex @code{getpgid}
5078 @prindex @code{getpgrp}
5079 @caindex func_getpgrp_void
5080 Define @code{GETPGRP_VOID} if it is an error to pass 0 to
5081 @code{getpgrp}; this is the Posix behavior.  On older BSD
5082 systems, you must pass 0 to @code{getpgrp}, as it takes an argument and
5083 behaves like Posix's @code{getpgid}.
5085 @example
5086 #ifdef GETPGRP_VOID
5087   pid = getpgrp ();
5088 #else
5089   pid = getpgrp (0);
5090 #endif
5091 @end example
5093 This macro does not check whether
5094 @code{getpgrp} exists at all; if you need to work in that situation,
5095 first call @code{AC_CHECK_FUNC} for @code{getpgrp}.
5097 The result of this macro is cached in the @code{ac_cv_func_getpgrp_void}
5098 variable.
5100 This macro is obsolescent, as current systems have a @code{getpgrp}
5101 whose signature conforms to Posix.  New programs need not use this macro.
5102 @end defmac
5104 @defmac AC_FUNC_LSTAT_FOLLOWS_SLASHED_SYMLINK
5105 @acindex{FUNC_LSTAT_FOLLOWS_SLASHED_SYMLINK}
5106 @cvindex LSTAT_FOLLOWS_SLASHED_SYMLINK
5107 @c @fuindex lstat
5108 @prindex @code{lstat}
5109 @caindex func_lstat_dereferences_slashed_symlink
5110 If @file{link} is a symbolic link, then @code{lstat} should treat
5111 @file{link/} the same as @file{link/.}.  However, many older
5112 @code{lstat} implementations incorrectly ignore trailing slashes.
5114 It is safe to assume that if @code{lstat} incorrectly ignores
5115 trailing slashes, then other symbolic-link-aware functions like
5116 @code{unlink} also incorrectly ignore trailing slashes.
5118 If @code{lstat} behaves properly, define
5119 @code{LSTAT_FOLLOWS_SLASHED_SYMLINK}, otherwise require an
5120 @code{AC_LIBOBJ} replacement of @code{lstat}.
5122 The result of this macro is cached in the
5123 @code{ac_cv_func_lstat_dereferences_slashed_symlink} variable.
5124 @end defmac
5126 @defmac AC_FUNC_MALLOC
5127 @acindex{FUNC_MALLOC}
5128 @cvindex HAVE_MALLOC
5129 @cvindex malloc
5130 @c @fuindex malloc
5131 @prindex @code{malloc}
5132 @caindex func_malloc_0_nonnull
5133 If the @code{malloc} function is compatible with the GNU C
5134 library @code{malloc} (i.e., @samp{malloc (0)} returns a valid
5135 pointer), define @code{HAVE_MALLOC} to 1.  Otherwise define
5136 @code{HAVE_MALLOC} to 0, ask for an @code{AC_LIBOBJ} replacement for
5137 @samp{malloc}, and define @code{malloc} to @code{rpl_malloc} so that the
5138 native @code{malloc} is not used in the main project.
5140 Typically, the replacement file @file{malloc.c} should look like (note
5141 the @samp{#undef malloc}):
5143 @verbatim
5144 #include <config.h>
5145 #undef malloc
5147 #include <sys/types.h>
5149 void *malloc ();
5151 /* Allocate an N-byte block of memory from the heap.
5152    If N is zero, allocate a 1-byte block.  */
5154 void *
5155 rpl_malloc (size_t n)
5157   if (n == 0)
5158     n = 1;
5159   return malloc (n);
5161 @end verbatim
5163 The result of this macro is cached in the
5164 @code{ac_cv_func_malloc_0_nonnull} variable.
5165 @end defmac
5167 @defmac AC_FUNC_MBRTOWC
5168 @acindex{FUNC_MBRTOWC}
5169 @cvindex HAVE_MBRTOWC
5170 @c @fuindex mbrtowc
5171 @prindex @code{mbrtowc}
5172 @caindex func_mbrtowc
5173 Define @code{HAVE_MBRTOWC} to 1 if the function @code{mbrtowc} and the
5174 type @code{mbstate_t} are properly declared.
5176 The result of this macro is cached in the @code{ac_cv_func_mbrtowc}
5177 variable.
5178 @end defmac
5180 @defmac AC_FUNC_MEMCMP
5181 @acindex{FUNC_MEMCMP}
5182 @ovindex LIBOBJS
5183 @c @fuindex memcmp
5184 @prindex @code{memcmp}
5185 @caindex func_memcmp_working
5186 If the @code{memcmp} function is not available, or does not work on
5187 8-bit data (like the one on SunOS 4.1.3), or fails when comparing 16
5188 bytes or more and with at least one buffer not starting on a 4-byte
5189 boundary (such as the one on NeXT x86 OpenStep), require an
5190 @code{AC_LIBOBJ} replacement for @samp{memcmp}.
5192 The result of this macro is cached in the
5193 @code{ac_cv_func_memcmp_working} variable.
5195 This macro is obsolescent, as current systems have a working
5196 @code{memcmp}.  New programs need not use this macro.
5197 @end defmac
5199 @defmac AC_FUNC_MKTIME
5200 @acindex{FUNC_MKTIME}
5201 @ovindex LIBOBJS
5202 @c @fuindex mktime
5203 @prindex @code{mktime}
5204 @caindex func_working_mktime
5205 If the @code{mktime} function is not available, or does not work
5206 correctly, require an @code{AC_LIBOBJ} replacement for @samp{mktime}.
5207 For the purposes of this test, @code{mktime} should conform to the
5208 Posix standard and should be the inverse of
5209 @code{localtime}.
5211 The result of this macro is cached in the
5212 @code{ac_cv_func_working_mktime} variable.
5213 @end defmac
5215 @anchor{AC_FUNC_MMAP}
5216 @defmac AC_FUNC_MMAP
5217 @acindex{FUNC_MMAP}
5218 @cvindex HAVE_MMAP
5219 @c @fuindex mmap
5220 @prindex @code{mmap}
5221 @caindex func_mmap_fixed_mapped
5222 If the @code{mmap} function exists and works correctly, define
5223 @code{HAVE_MMAP}.  This checks only private fixed mapping of already-mapped
5224 memory.
5226 The result of this macro is cached in the
5227 @code{ac_cv_func_mmap_fixed_mapped} variable.
5228 @end defmac
5230 @defmac AC_FUNC_OBSTACK
5231 @acindex{FUNC_OBSTACK}
5232 @cvindex HAVE_OBSTACK
5233 @cindex obstack
5234 @caindex func_obstack
5235 If the obstacks are found, define @code{HAVE_OBSTACK}, else require an
5236 @code{AC_LIBOBJ} replacement for @samp{obstack}.
5238 The result of this macro is cached in the @code{ac_cv_func_obstack}
5239 variable.
5240 @end defmac
5242 @defmac AC_FUNC_REALLOC
5243 @acindex{FUNC_REALLOC}
5244 @cvindex HAVE_REALLOC
5245 @cvindex realloc
5246 @c @fuindex realloc
5247 @prindex @code{realloc}
5248 @caindex func_realloc_0_nonnull
5249 If the @code{realloc} function is compatible with the GNU C
5250 library @code{realloc} (i.e., @samp{realloc (NULL, 0)} returns a
5251 valid pointer), define @code{HAVE_REALLOC} to 1.  Otherwise define
5252 @code{HAVE_REALLOC} to 0, ask for an @code{AC_LIBOBJ} replacement for
5253 @samp{realloc}, and define @code{realloc} to @code{rpl_realloc} so that
5254 the native @code{realloc} is not used in the main project.  See
5255 @code{AC_FUNC_MALLOC} for details.
5257 The result of this macro is cached in the
5258 @code{ac_cv_func_realloc_0_nonnull} variable.
5259 @end defmac
5261 @defmac AC_FUNC_SELECT_ARGTYPES
5262 @acindex{FUNC_SELECT_ARGTYPES}
5263 @cvindex SELECT_TYPE_ARG1
5264 @cvindex SELECT_TYPE_ARG234
5265 @cvindex SELECT_TYPE_ARG5
5266 @c @fuindex select
5267 @prindex @code{select}
5268 @c @caindex func_select_args
5269 Determines the correct type to be passed for each of the
5270 @code{select} function's arguments, and defines those types
5271 in @code{SELECT_TYPE_ARG1}, @code{SELECT_TYPE_ARG234}, and
5272 @code{SELECT_TYPE_ARG5} respectively.  @code{SELECT_TYPE_ARG1} defaults
5273 to @samp{int}, @code{SELECT_TYPE_ARG234} defaults to @samp{int *},
5274 and @code{SELECT_TYPE_ARG5} defaults to @samp{struct timeval *}.
5276 This macro is obsolescent, as current systems have a @code{select} whose
5277 signature conforms to Posix.  New programs need not use this macro.
5278 @end defmac
5280 @defmac AC_FUNC_SETPGRP
5281 @acindex{FUNC_SETPGRP}
5282 @cvindex SETPGRP_VOID
5283 @c @fuindex setpgrp
5284 @prindex @code{setpgrp}
5285 @caindex func_setpgrp_void
5286 If @code{setpgrp} takes no argument (the Posix version), define
5287 @code{SETPGRP_VOID}.  Otherwise, it is the BSD version, which takes
5288 two process IDs as arguments.  This macro does not check whether
5289 @code{setpgrp} exists at all; if you need to work in that situation,
5290 first call @code{AC_CHECK_FUNC} for @code{setpgrp}.
5292 The result of this macro is cached in the @code{ac_cv_func_setpgrp_void}
5293 variable.
5295 This macro is obsolescent, as current systems have a @code{setpgrp}
5296 whose signature conforms to Posix.  New programs need not use this macro.
5297 @end defmac
5299 @defmac AC_FUNC_STAT
5300 @defmacx AC_FUNC_LSTAT
5301 @acindex{FUNC_STAT}
5302 @acindex{FUNC_LSTAT}
5303 @cvindex HAVE_STAT_EMPTY_STRING_BUG
5304 @cvindex HAVE_LSTAT_EMPTY_STRING_BUG
5305 @c @fuindex stat
5306 @prindex @code{stat}
5307 @c @fuindex lstat
5308 @prindex @code{lstat}
5309 @caindex func_stat_empty_string_bug
5310 @caindex func_lstat_empty_string_bug
5311 Determine whether @code{stat} or @code{lstat} have the bug that it
5312 succeeds when given the zero-length file name as argument.  The @code{stat}
5313 and @code{lstat} from SunOS 4.1.4 and the Hurd (as of 1998-11-01) do
5314 this.
5316 If it does, then define @code{HAVE_STAT_EMPTY_STRING_BUG} (or
5317 @code{HAVE_LSTAT_EMPTY_STRING_BUG}) and ask for an @code{AC_LIBOBJ}
5318 replacement of it.
5320 The results of these macros are cached in the
5321 @code{ac_cv_func_stat_empty_string_bug} and the
5322 @code{ac_cv_func_lstat_empty_string_bug} variables, respectively.
5324 These macros are obsolescent, as no current systems have the bug.
5325 New programs need not use these macros.
5326 @end defmac
5328 @anchor{AC_FUNC_STRCOLL}
5329 @defmac AC_FUNC_STRCOLL
5330 @acindex{FUNC_STRCOLL}
5331 @cvindex HAVE_STRCOLL
5332 @c @fuindex strcoll
5333 @prindex @code{strcoll}
5334 @caindex func_strcoll_works
5335 If the @code{strcoll} function exists and works correctly, define
5336 @code{HAVE_STRCOLL}.  This does a bit more than
5337 @samp{AC_CHECK_FUNCS(strcoll)}, because some systems have incorrect
5338 definitions of @code{strcoll} that should not be used.
5340 The result of this macro is cached in the @code{ac_cv_func_strcoll_works}
5341 variable.
5342 @end defmac
5344 @defmac AC_FUNC_STRERROR_R
5345 @acindex{FUNC_STRERROR_R}
5346 @cvindex HAVE_STRERROR_R
5347 @cvindex HAVE_DECL_STRERROR_R
5348 @cvindex STRERROR_R_CHAR_P
5349 @c @fuindex strerror_r
5350 @caindex func_strerror_r_char_p
5351 @prindex @code{strerror_r}
5352 If @code{strerror_r} is available, define @code{HAVE_STRERROR_R}, and if
5353 it is declared, define @code{HAVE_DECL_STRERROR_R}.  If it returns a
5354 @code{char *} message, define @code{STRERROR_R_CHAR_P}; otherwise it
5355 returns an @code{int} error number.  The Thread-Safe Functions option of
5356 Posix requires @code{strerror_r} to return @code{int}, but
5357 many systems (including, for example, version 2.2.4 of the GNU C
5358 Library) return a @code{char *} value that is not necessarily equal to
5359 the buffer argument.
5361 The result of this macro is cached in the
5362 @code{ac_cv_func_strerror_r_char_p} variable.
5363 @end defmac
5365 @anchor{AC_FUNC_STRFTIME}
5366 @defmac AC_FUNC_STRFTIME
5367 @acindex{FUNC_STRFTIME}
5368 @cvindex HAVE_STRFTIME
5369 @c @fuindex strftime
5370 @prindex @code{strftime}
5371 Check for @code{strftime} in the @file{intl} library, for SCO Unix.
5372 Then, if @code{strftime} is available, define @code{HAVE_STRFTIME}.
5374 This macro is obsolescent, as no current systems require the @file{intl}
5375 library for @code{strftime}.  New programs need not use this macro.
5376 @end defmac
5378 @defmac AC_FUNC_STRTOD
5379 @acindex{FUNC_STRTOD}
5380 @ovindex POW_LIB
5381 @c @fuindex strtod
5382 @prindex @code{strtod}
5383 @caindex func_strtod
5384 @caindex func_pow
5385 If the @code{strtod} function does not exist or doesn't work correctly,
5386 ask for an @code{AC_LIBOBJ} replacement of @samp{strtod}.  In this case,
5387 because @file{strtod.c} is likely to need @samp{pow}, set the output
5388 variable @code{POW_LIB} to the extra library needed.
5390 This macro caches its result in the @code{ac_cv_func_strtod} variable
5391 and depends upon the result in the @code{ac_cv_func_pow} variable.
5392 @end defmac
5394 @defmac AC_FUNC_STRTOLD
5395 @acindex{FUNC_STRTOLD}
5396 @cvindex HAVE_STRTOLD
5397 @prindex @code{strtold}
5398 @caindex func_strtold
5399 If the @code{strtold} function exists and conforms to C99, define
5400 @code{HAVE_STRTOLD}.
5402 This macro caches its result in the @code{ac_cv_func_strtold} variable.
5403 @end defmac
5405 @defmac AC_FUNC_STRNLEN
5406 @acindex{FUNC_STRNLEN}
5407 @cvindex HAVE_STRNLEN
5408 @c @fuindex strnlen
5409 @prindex @code{strnlen}
5410 @caindex func_strnlen_working
5411 If the @code{strnlen} function is not available, or is buggy (like the one
5412 from AIX 4.3), require an @code{AC_LIBOBJ} replacement for it.
5414 This macro caches its result in the @code{ac_cv_func_strnlen_working}
5415 variable.
5416 @end defmac
5418 @anchor{AC_FUNC_UTIME_NULL}
5419 @defmac AC_FUNC_UTIME_NULL
5420 @acindex{FUNC_UTIME_NULL}
5421 @cvindex HAVE_UTIME_NULL
5422 @c @fuindex utime
5423 @prindex @code{utime}
5424 @caindex func_utime_null
5425 If @samp{utime (@var{file}, NULL)} sets @var{file}'s timestamp to
5426 the present, define @code{HAVE_UTIME_NULL}.
5428 This macro caches its result in the @code{ac_cv_func_utime_null}
5429 variable.
5431 This macro is obsolescent, as all current systems have a @code{utime}
5432 that behaves this way.  New programs need not use this macro.
5433 @end defmac
5435 @anchor{AC_FUNC_VPRINTF}
5436 @defmac AC_FUNC_VPRINTF
5437 @acindex{FUNC_VPRINTF}
5438 @cvindex HAVE_VPRINTF
5439 @cvindex HAVE_DOPRNT
5440 @c @fuindex vprintf
5441 @prindex @code{vprintf}
5442 @c @fuindex vsprintf
5443 @prindex @code{vsprintf}
5444 If @code{vprintf} is found, define @code{HAVE_VPRINTF}.  Otherwise, if
5445 @code{_doprnt} is found, define @code{HAVE_DOPRNT}.  (If @code{vprintf}
5446 is available, you may assume that @code{vfprintf} and @code{vsprintf}
5447 are also available.)
5449 This macro is obsolescent, as all current systems have @code{vprintf}.
5450 New programs need not use this macro.
5451 @end defmac
5453 @defmac AC_REPLACE_FNMATCH
5454 @acindex{REPLACE_FNMATCH}
5455 @c @fuindex fnmatch
5456 @prindex @code{fnmatch}
5457 @hdrindex{fnmatch.h}
5458 @caindex func_fnmatch_works
5459 If the @code{fnmatch} function does not conform to Posix (see
5460 @code{AC_FUNC_FNMATCH}), ask for its @code{AC_LIBOBJ} replacement.
5462 The files @file{fnmatch.c}, @file{fnmatch_loop.c}, and @file{fnmatch_.h}
5463 in the @code{AC_LIBOBJ} replacement directory are assumed to contain a
5464 copy of the source code of GNU @code{fnmatch}.  If necessary,
5465 this source code is compiled as an @code{AC_LIBOBJ} replacement, and the
5466 @file{fnmatch_.h} file is linked to @file{fnmatch.h} so that it can be
5467 included in place of the system @code{<fnmatch.h>}.
5469 This macro caches its result in the @code{ac_cv_func_fnmatch_works}
5470 variable.
5472 This macro is obsolescent, as it assumes the use of particular source
5473 files.  New programs should use Gnulib's @code{fnmatch-posix} module,
5474 which provides this macro along with the source files.  @xref{Gnulib}.
5475 @end defmac
5479 @node Generic Functions
5480 @subsection Generic Function Checks
5482 These macros are used to find functions not covered by the ``particular''
5483 test macros.  If the functions might be in libraries other than the
5484 default C library, first call @code{AC_CHECK_LIB} for those libraries.
5485 If you need to check the behavior of a function as well as find out
5486 whether it is present, you have to write your own test for
5487 it (@pxref{Writing Tests}).
5489 @anchor{AC_CHECK_FUNC}
5490 @defmac AC_CHECK_FUNC (@var{function}, @ovar{action-if-found}, @
5491   @ovar{action-if-not-found})
5492 @acindex{CHECK_FUNC}
5493 @caindex func_@var{function}
5494 If C function @var{function} is available, run shell commands
5495 @var{action-if-found}, otherwise @var{action-if-not-found}.  If you just
5496 want to define a symbol if the function is available, consider using
5497 @code{AC_CHECK_FUNCS} instead.  This macro checks for functions with C
5498 linkage even when @code{AC_LANG(C++)} has been called, since C is more
5499 standardized than C++.  (@pxref{Language Choice}, for more information
5500 about selecting the language for checks.)
5502 This macro caches its result in the @code{ac_cv_func_@var{function}}
5503 variable.
5504 @end defmac
5506 @anchor{AC_CHECK_FUNCS}
5507 @defmac AC_CHECK_FUNCS (@var{function}@dots{}, @ovar{action-if-found}, @
5508   @ovar{action-if-not-found})
5509 @acindex{CHECK_FUNCS}
5510 @cvindex HAVE_@var{function}
5511 For each @var{function} enumerated in the blank-or-newline-separated argument
5512 list, define @code{HAVE_@var{function}} (in all capitals) if it is available.
5513 If @var{action-if-found} is given, it is additional shell code to
5514 execute when one of the functions is found.  You can give it a value of
5515 @samp{break} to break out of the loop on the first match.  If
5516 @var{action-if-not-found} is given, it is executed when one of the
5517 functions is not found.
5519 Results are cached for each @var{function} as in @code{AC_CHECK_FUNC}.
5520 @end defmac
5522 @defmac AC_CHECK_FUNCS_ONCE (@var{function}@dots{})
5523 @acindex{CHECK_FUNCS_ONCE}
5524 @cvindex HAVE_@var{function}
5525 For each @var{function} enumerated in the blank-or-newline-separated argument
5526 list, define @code{HAVE_@var{function}} (in all capitals) if it is available.
5527 This is a once-only variant of @code{AC_CHECK_FUNCS}.  It generates the
5528 checking code at most once, so that @command{configure} is smaller and
5529 faster; but the checks cannot be conditionalized and are always done once,
5530 early during the @command{configure} run.
5531 @end defmac
5533 @sp 1
5535 Autoconf follows a philosophy that was formed over the years by those
5536 who have struggled for portability: isolate the portability issues in
5537 specific files, and then program as if you were in a Posix
5538 environment.  Some functions may be missing or unfixable, and your
5539 package must be ready to replace them.
5541 Suitable replacements for many such problem functions are available from
5542 Gnulib (@pxref{Gnulib}).
5544 @defmac AC_LIBOBJ (@var{function})
5545 @acindex{LIBOBJ}
5546 @ovindex LIBOBJS
5547 Specify that @samp{@var{function}.c} must be included in the executables
5548 to replace a missing or broken implementation of @var{function}.
5550 Technically, it adds @samp{@var{function}.$ac_objext} to the output
5551 variable @code{LIBOBJS} if it is not already in, and calls
5552 @code{AC_LIBSOURCE} for @samp{@var{function}.c}.  You should not
5553 directly change @code{LIBOBJS}, since this is not traceable.
5554 @end defmac
5556 @defmac AC_LIBSOURCE (@var{file})
5557 @acindex{LIBSOURCE}
5558 Specify that @var{file} might be needed to compile the project.  If you
5559 need to know what files might be needed by a @file{configure.ac}, you
5560 should trace @code{AC_LIBSOURCE}.  @var{file} must be a literal.
5562 This macro is called automatically from @code{AC_LIBOBJ}, but you must
5563 call it explicitly if you pass a shell variable to @code{AC_LIBOBJ}.  In
5564 that case, since shell variables cannot be traced statically, you must
5565 pass to @code{AC_LIBSOURCE} any possible files that the shell variable
5566 might cause @code{AC_LIBOBJ} to need.  For example, if you want to pass
5567 a variable @code{$foo_or_bar} to @code{AC_LIBOBJ} that holds either
5568 @code{"foo"} or @code{"bar"}, you should do:
5570 @example
5571 AC_LIBSOURCE([foo.c])
5572 AC_LIBSOURCE([bar.c])
5573 AC_LIBOBJ([$foo_or_bar])
5574 @end example
5576 @noindent
5577 There is usually a way to avoid this, however, and you are encouraged to
5578 simply call @code{AC_LIBOBJ} with literal arguments.
5580 Note that this macro replaces the obsolete @code{AC_LIBOBJ_DECL}, with
5581 slightly different semantics: the old macro took the function name,
5582 e.g., @code{foo}, as its argument rather than the file name.
5583 @end defmac
5585 @defmac AC_LIBSOURCES (@var{files})
5586 @acindex{LIBSOURCES}
5587 Like @code{AC_LIBSOURCE}, but accepts one or more @var{files} in a
5588 comma-separated M4 list.  Thus, the above example might be rewritten:
5590 @example
5591 AC_LIBSOURCES([foo.c, bar.c])
5592 AC_LIBOBJ([$foo_or_bar])
5593 @end example
5594 @end defmac
5596 @defmac AC_CONFIG_LIBOBJ_DIR (@var{directory})
5597 @acindex{CONFIG_LIBOBJ_DIR}
5598 Specify that @code{AC_LIBOBJ} replacement files are to be found in
5599 @var{directory}, a name relative to the top level of the
5600 source tree.  The replacement directory defaults to @file{.}, the top
5601 level directory, and the most typical value is @file{lib}, corresponding
5602 to @samp{AC_CONFIG_LIBOBJ_DIR([lib])}.
5604 @command{configure} might need to know the replacement directory for the
5605 following reasons: (i) some checks use the replacement files, (ii) some
5606 macros bypass broken system headers by installing links to the
5607 replacement headers (iii) when used in conjunction with Automake,
5608 within each makefile, @var{directory} is used as a relative path
5609 from @code{$(top_srcdir)} to each object named in @code{LIBOBJS} and
5610 @code{LTLIBOBJS}, etc.
5611 @end defmac
5613 @sp 1
5615 It is common to merely check for the existence of a function, and ask
5616 for its @code{AC_LIBOBJ} replacement if missing.  The following macro is
5617 a convenient shorthand.
5619 @defmac AC_REPLACE_FUNCS (@var{function}@dots{})
5620 @acindex{REPLACE_FUNCS}
5621 @cvindex HAVE_@var{function}
5622 @ovindex LIBOBJS
5623 Like @code{AC_CHECK_FUNCS}, but uses @samp{AC_LIBOBJ(@var{function})} as
5624 @var{action-if-not-found}.  You can declare your replacement function by
5625 enclosing the prototype in @samp{#ifndef HAVE_@var{function}}.  If the
5626 system has the function, it probably declares it in a header file you
5627 should be including, so you shouldn't redeclare it lest your declaration
5628 conflict.
5629 @end defmac
5631 @node Header Files
5632 @section Header Files
5633 @cindex Header, checking
5635 The following macros check for the presence of certain C header files.
5636 If there is no macro specifically defined to check for a header file you need,
5637 and you don't need to check for any special properties of
5638 it, then you can use one of the general header-file check macros.
5640 @menu
5641 * Header Portability::          Collected knowledge on common headers
5642 * Particular Headers::          Special handling to find certain headers
5643 * Generic Headers::             How to find other headers
5644 @end menu
5646 @node Header Portability
5647 @subsection Portability of Headers
5648 @cindex Portability of headers
5649 @cindex Header portability
5651 This section tries to collect knowledge about common headers, and the
5652 problems they cause.  By definition, this list always requires
5653 additions.  Please help us keeping it as complete as possible.
5655 @table @asis
5657 @item @file{limits.h}
5658 C99 says that @file{limits.h} defines @code{LLONG_MIN},
5659 @code{LLONG_MAX}, and @code{ULLONG_MAX}, but many almost-C99
5660 environments (e.g., default GCC 4.0.2 + glibc 2.4) do not
5661 define them.
5663 @item @file{inttypes.h} vs.@: @file{stdint.h}
5664 @hdrindex{inttypes.h}
5665 @hdrindex{stdint.h}
5666 The C99 standard says that @file{inttypes.h} includes
5667 @file{stdint.h}, so there's no need to include @file{stdint.h}
5668 separately in a standard environment.  Some implementations have
5669 @file{inttypes.h} but not @file{stdint.h} (e.g., Solaris 7), but we don't
5670 know of any implementation that has @file{stdint.h} but not
5671 @file{inttypes.h}.
5673 @item @file{linux/irda.h}
5674 @hdrindex{linux/irda.h}
5675 It requires @file{linux/types.h} and @file{sys/socket.h}.
5677 @item @file{linux/random.h}
5678 @hdrindex{linux/random.h}
5679 It requires @file{linux/types.h}.
5681 @item @file{net/if.h}
5682 @hdrindex{net/if.h}
5683 On Darwin, this file requires that @file{sys/socket.h} be included
5684 beforehand.  One should run:
5686 @example
5687 AC_CHECK_HEADERS([sys/socket.h])
5688 AC_CHECK_HEADERS([net/if.h], [], [],
5689 [#include <stdio.h>
5690 #ifdef STDC_HEADERS
5691 # include <stdlib.h>
5692 # include <stddef.h>
5693 #else
5694 # ifdef HAVE_STDLIB_H
5695 #  include <stdlib.h>
5696 # endif
5697 #endif
5698 #ifdef HAVE_SYS_SOCKET_H
5699 # include <sys/socket.h>
5700 #endif
5702 @end example
5704 @item @file{netinet/if_ether.h}
5705 @hdrindex{netinet/if_ether.h}
5706 On Darwin, this file requires that @file{stdio.h} and
5707 @file{sys/socket.h} be included beforehand.  One should run:
5709 @example
5710 AC_CHECK_HEADERS([sys/socket.h])
5711 AC_CHECK_HEADERS([netinet/if_ether.h], [], [],
5712 [#include <stdio.h>
5713 #ifdef STDC_HEADERS
5714 # include <stdlib.h>
5715 # include <stddef.h>
5716 #else
5717 # ifdef HAVE_STDLIB_H
5718 #  include <stdlib.h>
5719 # endif
5720 #endif
5721 #ifdef HAVE_SYS_SOCKET_H
5722 # include <sys/socket.h>
5723 #endif
5725 @end example
5727 @item @file{stdint.h}
5728 See above, item @file{inttypes.h} vs.@: @file{stdint.h}.
5730 @item @file{stdlib.h}
5731 @hdrindex{stdlib.h}
5732 On many systems (e.g., Darwin), @file{stdio.h} is a prerequisite.
5734 @item @file{sys/mount.h}
5735 @hdrindex{sys/mount.h}
5736 On FreeBSD 4.8 on ia32 and using gcc version 2.95.4,
5737 @file{sys/params.h} is a prerequisite.
5739 @item @file{sys/ptem.h}
5740 @hdrindex{sys/ptem.h}
5741 On Solaris 8, @file{sys/stream.h} is a prerequisite.
5743 @item @file{sys/socket.h}
5744 @hdrindex{sys/socket.h}
5745 On Darwin, @file{stdlib.h} is a prerequisite.
5747 @item @file{sys/ucred.h}
5748 @hdrindex{sys/ucred.h}
5749 On Tru64 5.1, @file{sys/types.h} is a prerequisite.
5751 @item @file{X11/extensions/scrnsaver.h}
5752 @hdrindex{X11/extensions/scrnsaver.h}
5753 Using XFree86, this header requires @file{X11/Xlib.h}, which is probably
5754 so required that you might not even consider looking for it.
5756 @example
5757 AC_CHECK_HEADERS([X11/extensions/scrnsaver.h], [], [],
5758 [[#include <X11/Xlib.h>
5760 @end example
5761 @end table
5764 @node Particular Headers
5765 @subsection Particular Header Checks
5767 These macros check for particular system header files---whether they
5768 exist, and in some cases whether they declare certain symbols.
5770 @defmac AC_HEADER_ASSERT
5771 @acindex{HEADER_ASSERT}
5772 @cvindex NDEBUG
5773 @hdrindex{assert.h}
5774 Check whether to enable assertions in the style of @file{assert.h}.
5775 Assertions are enabled by default, but the user can override this by
5776 invoking @command{configure} with the @option{--disable-assert} option.
5777 @end defmac
5779 @anchor{AC_HEADER_DIRENT}
5780 @defmac AC_HEADER_DIRENT
5781 @acindex{HEADER_DIRENT}
5782 @cvindex HAVE_DIRENT_H
5783 @cvindex HAVE_NDIR_H
5784 @cvindex HAVE_SYS_DIR_H
5785 @cvindex HAVE_SYS_NDIR_H
5786 @hdrindex{dirent.h}
5787 @hdrindex{sys/ndir.h}
5788 @hdrindex{sys/dir.h}
5789 @hdrindex{ndir.h}
5790 Check for the following header files.  For the first one that is
5791 found and defines @samp{DIR}, define the listed C preprocessor macro:
5793 @multitable {@file{sys/ndir.h}} {@code{HAVE_SYS_NDIR_H}}
5794 @item @file{dirent.h}   @tab @code{HAVE_DIRENT_H}
5795 @item @file{sys/ndir.h} @tab @code{HAVE_SYS_NDIR_H}
5796 @item @file{sys/dir.h}  @tab @code{HAVE_SYS_DIR_H}
5797 @item @file{ndir.h}     @tab @code{HAVE_NDIR_H}
5798 @end multitable
5800 The directory-library declarations in your source code should look
5801 something like the following:
5803 @example
5804 @group
5805 #include <sys/types.h>
5806 #ifdef HAVE_DIRENT_H
5807 # include <dirent.h>
5808 # define NAMLEN(dirent) strlen ((dirent)->d_name)
5809 #else
5810 # define dirent direct
5811 # define NAMLEN(dirent) ((dirent)->d_namlen)
5812 # ifdef HAVE_SYS_NDIR_H
5813 #  include <sys/ndir.h>
5814 # endif
5815 # ifdef HAVE_SYS_DIR_H
5816 #  include <sys/dir.h>
5817 # endif
5818 # ifdef HAVE_NDIR_H
5819 #  include <ndir.h>
5820 # endif
5821 #endif
5822 @end group
5823 @end example
5825 Using the above declarations, the program would declare variables to be
5826 of type @code{struct dirent}, not @code{struct direct}, and would access
5827 the length of a directory entry name by passing a pointer to a
5828 @code{struct dirent} to the @code{NAMLEN} macro.
5830 This macro also checks for the SCO Xenix @file{dir} and @file{x} libraries.
5832 This macro is obsolescent, as all current systems with directory
5833 libraries have @code{<dirent.h>}.  New programs need not use this macro.
5835 Also see @code{AC_STRUCT_DIRENT_D_INO} and
5836 @code{AC_STRUCT_DIRENT_D_TYPE} (@pxref{Particular Structures}).
5837 @end defmac
5839 @anchor{AC_HEADER_MAJOR}
5840 @defmac AC_HEADER_MAJOR
5841 @acindex{HEADER_MAJOR}
5842 @cvindex MAJOR_IN_MKDEV
5843 @cvindex MAJOR_IN_SYSMACROS
5844 @hdrindex{sys/mkdev.h}
5845 @hdrindex{sys/sysmacros.h}
5846 If @file{sys/types.h} does not define @code{major}, @code{minor}, and
5847 @code{makedev}, but @file{sys/mkdev.h} does, define
5848 @code{MAJOR_IN_MKDEV}; otherwise, if @file{sys/sysmacros.h} does, define
5849 @code{MAJOR_IN_SYSMACROS}.
5850 @end defmac
5852 @defmac AC_HEADER_RESOLV
5853 @acindex{HEADER_RESOLV}
5854 @cvindex HAVE_RESOLV_H
5855 @hdrindex{resolv.h}
5856 Checks for header @file{resolv.h}, checking for prerequisites first.
5857 To properly use @file{resolv.h}, your code should contain something like
5858 the following:
5860 @verbatim
5861 #ifdef HAVE_SYS_TYPES_H
5862 #  include <sys/types.h>
5863 #endif
5864 #ifdef HAVE_NETINET_IN_H
5865 #  include <netinet/in.h>   /* inet_ functions / structs */
5866 #endif
5867 #ifdef HAVE_ARPA_NAMESER_H
5868 #  include <arpa/nameser.h> /* DNS HEADER struct */
5869 #endif
5870 #ifdef HAVE_NETDB_H
5871 #  include <netdb.h>
5872 #endif
5873 #include <resolv.h>
5874 @end verbatim
5875 @end defmac
5877 @anchor{AC_HEADER_STAT}
5878 @defmac AC_HEADER_STAT
5879 @acindex{HEADER_STAT}
5880 @cvindex STAT_MACROS_BROKEN
5881 @hdrindex{sys/stat.h}
5882 If the macros @code{S_ISDIR}, @code{S_ISREG}, etc.@: defined in
5883 @file{sys/stat.h} do not work properly (returning false positives),
5884 define @code{STAT_MACROS_BROKEN}.  This is the case on Tektronix UTekV,
5885 Amdahl UTS and Motorola System V/88.
5887 This macro is obsolescent, as no current systems have the bug.
5888 New programs need not use this macro.
5889 @end defmac
5891 @defmac AC_HEADER_STDBOOL
5892 @acindex{HEADER_STDBOOL}
5893 @cvindex HAVE_STDBOOL_H
5894 @cvindex HAVE__BOOL
5895 @hdrindex{stdbool.h}
5896 @hdrindex{system.h}
5897 @caindex header_stdbool_h
5898 If @file{stdbool.h} exists and conforms to C99, define
5899 @code{HAVE_STDBOOL_H} to 1; if the type @code{_Bool} is defined, define
5900 @code{HAVE__BOOL} to 1.  To fulfill the C99 requirements, your
5901 @file{system.h} could contain the following code:
5903 @verbatim
5904 #ifdef HAVE_STDBOOL_H
5905 # include <stdbool.h>
5906 #else
5907 # ifndef HAVE__BOOL
5908 #  ifdef __cplusplus
5909 typedef bool _Bool;
5910 #  else
5911 #   define _Bool signed char
5912 #  endif
5913 # endif
5914 # define bool _Bool
5915 # define false 0
5916 # define true 1
5917 # define __bool_true_false_are_defined 1
5918 #endif
5919 @end verbatim
5921 Alternatively you can use the @samp{stdbool} package of Gnulib
5922 (@pxref{Gnulib}); it packages the above code into a replacement header
5923 and contains a few other bells and whistles.
5925 This macro caches its result in the @code{ac_cv_header_stdbool_h}
5926 variable.
5927 @end defmac
5929 @anchor{AC_HEADER_STDC}
5930 @defmac AC_HEADER_STDC
5931 @acindex{HEADER_STDC}
5932 @cvindex STDC_HEADERS
5933 @hdrindex{stdlib.h}
5934 @hdrindex{stdarg.h}
5935 @hdrindex{string.h}
5936 @hdrindex{float.h}
5937 @hdrindex{ctype.h}
5938 @caindex header_stdc
5939 Define @code{STDC_HEADERS} if the system has C header files
5940 conforming to ANSI C89 (ISO C90).
5941 Specifically, this macro checks for @file{stdlib.h}, @file{stdarg.h},
5942 @file{string.h}, and @file{float.h}; if the system has those, it
5943 probably has the rest of the C89 header files.  This macro also
5944 checks whether @file{string.h} declares @code{memchr} (and thus
5945 presumably the other @code{mem} functions), whether @file{stdlib.h}
5946 declare @code{free} (and thus presumably @code{malloc} and other related
5947 functions), and whether the @file{ctype.h} macros work on characters
5948 with the high bit set, as the C standard requires.
5950 If you use this macro, your code can refer to @code{STDC_HEADERS} to
5951 determine whether the system has conforming header files (and probably C
5952 library functions).
5954 This macro caches its result in the @code{ac_cv_header_stdc} variable.
5956 This macro is obsolescent, as current systems have conforming header
5957 files.  New programs need not use this macro.
5959 @hdrindex{string.h}
5960 @hdrindex{strings.h}
5961 Nowadays @file{string.h} is part of the C standard and declares functions like
5962 @code{strcpy}, and @file{strings.h} is standardized by Posix and declares
5963 BSD functions like @code{bcopy}; but
5964 historically, string functions were a major sticking point in this area.
5965 If you still want to worry about portability to ancient systems without
5966 standard headers, there is so much variation
5967 that it is probably easier to declare the functions you use than to
5968 figure out exactly what the system header files declare.  Some ancient systems
5969 contained a mix of functions from the C standard and from BSD;
5970 some were mostly standard but lacked @samp{memmove}; some defined the
5971 BSD functions as macros in @file{string.h} or
5972 @file{strings.h}; some had only the BSD functions but
5973 @file{string.h}; some declared the memory functions in @file{memory.h},
5974 some in @file{string.h}; etc.  It is probably sufficient to check for
5975 one string function and one memory function; if the library had the
5976 standard versions of those then it probably had most of the others.
5977 If you put the following in @file{configure.ac}:
5979 @example
5980 # This example is obsolescent.
5981 # Nowadays you can omit these macro calls.
5982 AC_HEADER_STDC
5983 AC_CHECK_FUNCS([strchr memcpy])
5984 @end example
5986 @noindent
5987 then, in your code, you can use declarations like this:
5989 @example
5990 @group
5991 /* This example is obsolescent.
5992    Nowadays you can just #include <string.h>.  */
5993 #ifdef STDC_HEADERS
5994 # include <string.h>
5995 #else
5996 # ifndef HAVE_STRCHR
5997 #  define strchr index
5998 #  define strrchr rindex
5999 # endif
6000 char *strchr (), *strrchr ();
6001 # ifndef HAVE_MEMCPY
6002 #  define memcpy(d, s, n) bcopy ((s), (d), (n))
6003 #  define memmove(d, s, n) bcopy ((s), (d), (n))
6004 # endif
6005 #endif
6006 @end group
6007 @end example
6009 @noindent
6010 If you use a function like @code{memchr}, @code{memset}, @code{strtok},
6011 or @code{strspn}, which have no BSD equivalent, then macros don't
6012 suffice to port to ancient hosts; you must provide an implementation of
6013 each function.  An easy
6014 way to incorporate your implementations only when needed (since the ones
6015 in system C libraries may be hand optimized) is to, taking @code{memchr}
6016 for example, put it in @file{memchr.c} and use
6017 @samp{AC_REPLACE_FUNCS([memchr])}.
6018 @end defmac
6020 @defmac AC_HEADER_SYS_WAIT
6021 @acindex{HEADER_SYS_WAIT}
6022 @cvindex HAVE_SYS_WAIT_H
6023 @hdrindex{sys/wait.h}
6024 @caindex header_sys_wait_h
6025 If @file{sys/wait.h} exists and is compatible with Posix, define
6026 @code{HAVE_SYS_WAIT_H}.  Incompatibility can occur if @file{sys/wait.h}
6027 does not exist, or if it uses the old BSD @code{union wait} instead
6028 of @code{int} to store a status value.  If @file{sys/wait.h} is not
6029 Posix compatible, then instead of including it, define the
6030 Posix macros with their usual interpretations.  Here is an
6031 example:
6033 @example
6034 @group
6035 #include <sys/types.h>
6036 #ifdef HAVE_SYS_WAIT_H
6037 # include <sys/wait.h>
6038 #endif
6039 #ifndef WEXITSTATUS
6040 # define WEXITSTATUS(stat_val) ((unsigned int) (stat_val) >> 8)
6041 #endif
6042 #ifndef WIFEXITED
6043 # define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
6044 #endif
6045 @end group
6046 @end example
6048 @noindent
6049 This macro caches its result in the @code{ac_cv_header_sys_wait_h}
6050 variable.
6052 This macro is obsolescent, as current systems are compatible with Posix.
6053 New programs need not use this macro.
6054 @end defmac
6056 @cvindex _POSIX_VERSION
6057 @hdrindex{unistd.h}
6058 @code{_POSIX_VERSION} is defined when @file{unistd.h} is included on
6059 Posix systems.  If there is no @file{unistd.h}, it is definitely
6060 not a Posix system.  However, some non-Posix systems do
6061 have @file{unistd.h}.
6063 The way to check whether the system supports Posix is:
6065 @example
6066 @group
6067 #ifdef HAVE_UNISTD_H
6068 # include <sys/types.h>
6069 # include <unistd.h>
6070 #endif
6072 #ifdef _POSIX_VERSION
6073 /* Code for Posix systems.  */
6074 #endif
6075 @end group
6076 @end example
6078 @anchor{AC_HEADER_TIME}
6079 @defmac AC_HEADER_TIME
6080 @acindex{HEADER_TIME}
6081 @cvindex TIME_WITH_SYS_TIME
6082 @hdrindex{time.h}
6083 @hdrindex{sys/time.h}
6084 @caindex header_time
6085 If a program may include both @file{time.h} and @file{sys/time.h},
6086 define @code{TIME_WITH_SYS_TIME}.  On some ancient systems,
6087 @file{sys/time.h} included @file{time.h}, but @file{time.h} was not
6088 protected against multiple inclusion, so programs could not explicitly
6089 include both files.  This macro is useful in programs that use, for
6090 example, @code{struct timeval} as well as
6091 @code{struct tm}.  It is best used in conjunction with
6092 @code{HAVE_SYS_TIME_H}, which can be checked for using
6093 @code{AC_CHECK_HEADERS([sys/time.h])}.
6095 @example
6096 @group
6097 #ifdef TIME_WITH_SYS_TIME
6098 # include <sys/time.h>
6099 # include <time.h>
6100 #else
6101 # ifdef HAVE_SYS_TIME_H
6102 #  include <sys/time.h>
6103 # else
6104 #  include <time.h>
6105 # endif
6106 #endif
6107 @end group
6108 @end example
6110 @noindent
6111 This macro caches its result in the @code{ac_cv_header_time} variable.
6113 This macro is obsolescent, as current systems can include both files
6114 when they exist.  New programs need not use this macro.
6115 @end defmac
6118 @defmac AC_HEADER_TIOCGWINSZ
6119 @acindex{HEADER_TIOCGWINSZ}
6120 @cvindex GWINSZ_IN_SYS_IOCTL
6121 @hdrindex{sys/ioctl.h}
6122 @hdrindex{termios.h}
6123 @c FIXME: I need clarifications from Jim.
6124 If the use of @code{TIOCGWINSZ} requires @file{<sys/ioctl.h>}, then
6125 define @code{GWINSZ_IN_SYS_IOCTL}.  Otherwise @code{TIOCGWINSZ} can be
6126 found in @file{<termios.h>}.
6128 Use:
6130 @example
6131 @group
6132 #ifdef HAVE_TERMIOS_H
6133 # include <termios.h>
6134 #endif
6136 #ifdef GWINSZ_IN_SYS_IOCTL
6137 # include <sys/ioctl.h>
6138 #endif
6139 @end group
6140 @end example
6141 @end defmac
6143 @node Generic Headers
6144 @subsection Generic Header Checks
6146 These macros are used to find system header files not covered by the
6147 ``particular'' test macros.  If you need to check the contents of a header
6148 as well as find out whether it is present, you have to write your own
6149 test for it (@pxref{Writing Tests}).
6151 @anchor{AC_CHECK_HEADER}
6152 @defmac AC_CHECK_HEADER (@var{header-file}, @ovar{action-if-found}, @
6153   @ovar{action-if-not-found}, @ovar{includes})
6154 @acindex{CHECK_HEADER}
6155 @caindex header_@var{header-file}
6156 If the system header file @var{header-file} is compilable, execute shell
6157 commands @var{action-if-found}, otherwise execute
6158 @var{action-if-not-found}.  If you just want to define a symbol if the
6159 header file is available, consider using @code{AC_CHECK_HEADERS}
6160 instead.
6162 @var{includes} is decoded to determine the appropriate include
6163 directives.  If omitted or empty, @file{configure} will check for both header
6164 existence (with the preprocessor) and usability (with the compiler),
6165 using @code{AC_INCLUDES_DEFAULT} for the compile test.  If
6166 there is a discrepancy between the results, a warning is issued to the
6167 user, and the compiler results are favored (@pxref{Present But
6168 Cannot Be Compiled}).  In general, favoring the compiler results means
6169 that a header will be treated as not found even though the file exists,
6170 because you did not provide enough prerequisites.
6172 Providing a non-empty @var{includes} argument allows the code to provide
6173 any prerequisites prior to including the header under test; it is common
6174 to use the argument @code{AC_INCLUDES_DEFAULT} (@pxref{Default
6175 Includes}).  With an explicit fourth argument, no preprocessor test is
6176 needed.  As a special case, an @var{includes} of exactly @samp{-}
6177 triggers the older preprocessor check, which merely determines existence
6178 of the file in the preprocessor search path; this should only be used as
6179 a last resort (it is safer to determine the actual prerequisites and
6180 perform a compiler check, or else use @code{AC_PREPROC_IFELSE} to make
6181 it obvious that only a preprocessor check is desired).
6183 This macro caches its result in the @code{ac_cv_header_@var{header-file}}
6184 variable, with characters not suitable for a variable name mapped to
6185 underscores.
6186 @end defmac
6188 @anchor{AC_CHECK_HEADERS}
6189 @defmac AC_CHECK_HEADERS (@var{header-file}@dots{}, @
6190   @ovar{action-if-found}, @ovar{action-if-not-found}, @
6191   @ovar{includes})
6192 @acindex{CHECK_HEADERS}
6193 @cvindex HAVE_@var{header}
6194 @caindex header_@var{header-file}
6195 For each given system header file @var{header-file} in the
6196 blank-separated argument list that exists, define
6197 @code{HAVE_@var{header-file}} (in all capitals).  If @var{action-if-found}
6198 is given, it is additional shell code to execute when one of the header
6199 files is found.  You can give it a value of @samp{break} to break out of
6200 the loop on the first match.  If @var{action-if-not-found} is given, it
6201 is executed when one of the header files is not found.
6203 @var{includes} is interpreted as in @code{AC_CHECK_HEADER}, in order to
6204 choose the set of preprocessor directives supplied before the header
6205 under test.
6207 This macro caches its result in the @code{ac_cv_header_@var{header-file}}
6208 variable, with characters not suitable for a variable name mapped to
6209 underscores.
6210 @end defmac
6212 Previous versions of Autoconf merely checked whether the header was
6213 accepted by the preprocessor.  This was changed because the old test was
6214 inappropriate for typical uses.  Headers are typically used to compile,
6215 not merely to preprocess, and the old behavior sometimes accepted
6216 headers that clashed at compile-time (@pxref{Present But Cannot Be
6217 Compiled}).  If you need to check whether a header is preprocessable,
6218 you can use @code{AC_PREPROC_IFELSE} (@pxref{Running the Preprocessor}).
6220 Actually requiring a header to compile improves the robustness of the
6221 test, but it also requires
6222 that you make sure that headers that must be included before the
6223 @var{header-file} be part of the @var{includes}, (@pxref{Default
6224 Includes}).  If looking for @file{bar.h}, which requires that
6225 @file{foo.h} be included before if it exists, we suggest the following
6226 scheme:
6228 @verbatim
6229 AC_CHECK_HEADERS([foo.h])
6230 AC_CHECK_HEADERS([bar.h], [], [],
6231 [#ifdef HAVE_FOO_H
6232 # include <foo.h>
6233 #endif
6235 @end verbatim
6237 The following variant generates smaller, faster @command{configure}
6238 files if you do not need the full power of @code{AC_CHECK_HEADERS}.
6240 @defmac AC_CHECK_HEADERS_ONCE (@var{header-file}@dots{})
6241 @acindex{CHECK_HEADERS_ONCE}
6242 @cvindex HAVE_@var{header}
6243 For each given system header file @var{header-file} in the
6244 blank-separated argument list that exists, define
6245 @code{HAVE_@var{header-file}} (in all capitals).
6246 This is a once-only variant of @code{AC_CHECK_HEADERS}.  It generates the
6247 checking code at most once, so that @command{configure} is smaller and
6248 faster; but the checks cannot be conditionalized and are always done once,
6249 early during the @command{configure} run.  Thus, this macro is only safe
6250 for checking headers that do not have prerequisites beyond what
6251 @code{AC_INCLUDES_DEFAULT} provides.
6252 @end defmac
6254 @node Declarations
6255 @section Declarations
6256 @cindex Declaration, checking
6258 The following macros check for the declaration of variables and
6259 functions.  If there is no macro specifically defined to check for a
6260 symbol you need, then you can use the general macros (@pxref{Generic
6261 Declarations}) or, for more complex tests, you may use
6262 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}).
6264 @menu
6265 * Particular Declarations::     Macros to check for certain declarations
6266 * Generic Declarations::        How to find other declarations
6267 @end menu
6269 @node Particular Declarations
6270 @subsection Particular Declaration Checks
6272 There are no specific macros for declarations.
6274 @node Generic Declarations
6275 @subsection Generic Declaration Checks
6277 These macros are used to find declarations not covered by the ``particular''
6278 test macros.
6280 @defmac AC_CHECK_DECL (@var{symbol}, @ovar{action-if-found}, @
6281   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6282 @acindex{CHECK_DECL}
6283 @caindex have_decl_@var{symbol}
6284 If @var{symbol} (a function, variable, or constant) is not declared in
6285 @var{includes} and a declaration is needed, run the shell commands
6286 @var{action-if-not-found}, otherwise @var{action-if-found}.
6287 @var{includes} is a series of include directives, defaulting to
6288 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
6289 prior to the declaration under test.
6291 This macro actually tests whether @var{symbol} is defined as a macro or
6292 can be used as an r-value, not whether it is really declared, because it
6293 is much safer to avoid introducing extra declarations when they are not
6294 needed.  In order to facilitate use of C++ and overloaded function
6295 declarations, it is possible to specify function argument types in
6296 parentheses for types which can be zero-initialized:
6298 @example
6299 AC_CHECK_DECL([basename(char *)])
6300 @end example
6302 This macro caches its result in the @code{ac_cv_have_decl_@var{symbol}}
6303 variable, with characters not suitable for a variable name mapped to
6304 underscores.
6305 @end defmac
6307 @anchor{AC_CHECK_DECLS}
6308 @defmac AC_CHECK_DECLS (@var{symbols}, @ovar{action-if-found}, @
6309   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6310 @acindex{CHECK_DECLS}
6311 @cvindex HAVE_DECL_@var{symbol}
6312 @caindex have_decl_@var{symbol}
6313 For each of the @var{symbols} (@emph{comma}-separated list with optional
6314 function argument types for C++ overloads), define
6315 @code{HAVE_DECL_@var{symbol}} (in all capitals) to @samp{1} if
6316 @var{symbol} is declared, otherwise to @samp{0}.  If
6317 @var{action-if-not-found} is given, it is additional shell code to
6318 execute when one of the function declarations is needed, otherwise
6319 @var{action-if-found} is executed.
6321 @var{includes} is a series of include directives, defaulting to
6322 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
6323 prior to the declarations under test.
6325 This macro uses an M4 list as first argument:
6326 @example
6327 AC_CHECK_DECLS([strdup])
6328 AC_CHECK_DECLS([strlen])
6329 AC_CHECK_DECLS([malloc, realloc, calloc, free])
6330 AC_CHECK_DECLS([j0], [], [], [[#include <math.h>]])
6331 AC_CHECK_DECLS([[basename(char *)], [dirname(char *)]])
6332 @end example
6334 Unlike the other @samp{AC_CHECK_*S} macros, when a @var{symbol} is not
6335 declared, @code{HAVE_DECL_@var{symbol}} is defined to @samp{0} instead
6336 of leaving @code{HAVE_DECL_@var{symbol}} undeclared.  When you are
6337 @emph{sure} that the check was performed, use
6338 @code{HAVE_DECL_@var{symbol}} in @code{#if}:
6340 @example
6341 #if !HAVE_DECL_SYMBOL
6342 extern char *symbol;
6343 #endif
6344 @end example
6346 @noindent
6347 If the test may have not been performed, however, because it is safer
6348 @emph{not} to declare a symbol than to use a declaration that conflicts
6349 with the system's one, you should use:
6351 @example
6352 #if defined HAVE_DECL_MALLOC && !HAVE_DECL_MALLOC
6353 void *malloc (size_t *s);
6354 #endif
6355 @end example
6357 @noindent
6358 You fall into the second category only in extreme situations: either
6359 your files may be used without being configured, or they are used during
6360 the configuration.  In most cases the traditional approach is enough.
6362 This macro caches its results in @code{ac_cv_have_decl_@var{symbol}}
6363 variables, with characters not suitable for a variable name mapped to
6364 underscores.
6365 @end defmac
6367 @defmac AC_CHECK_DECLS_ONCE (@var{symbols})
6368 @acindex{CHECK_DECLS_ONCE}
6369 @cvindex HAVE_DECL_@var{symbol}
6370 For each of the @var{symbols} (@emph{comma}-separated list), define
6371 @code{HAVE_DECL_@var{symbol}} (in all capitals) to @samp{1} if
6372 @var{symbol} is declared in the default include files, otherwise to
6373 @samp{0}.  This is a once-only variant of @code{AC_CHECK_DECLS}.  It
6374 generates the checking code at most once, so that @command{configure} is
6375 smaller and faster; but the checks cannot be conditionalized and are
6376 always done once, early during the @command{configure} run.
6377 @end defmac
6380 @node Structures
6381 @section Structures
6382 @cindex Structure, checking
6384 The following macros check for the presence of certain members in C
6385 structures.  If there is no macro specifically defined to check for a
6386 member you need, then you can use the general structure-member macros
6387 (@pxref{Generic Structures}) or, for more complex tests, you may use
6388 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}).
6390 @menu
6391 * Particular Structures::       Macros to check for certain structure members
6392 * Generic Structures::          How to find other structure members
6393 @end menu
6395 @node Particular Structures
6396 @subsection Particular Structure Checks
6398 The following macros check for certain structures or structure members.
6400 @defmac AC_STRUCT_DIRENT_D_INO
6401 @acindex{STRUCT_DIRENT_D_INO}
6402 @cvindex HAVE_STRUCT_DIRENT_D_INO
6403 @c @caindex header_dirent_dirent_h
6404 @c @caindex member_struct_dirent_d_ino
6405 Perform all the actions of @code{AC_HEADER_DIRENT} (@pxref{Particular
6406 Headers}).  Then, if @code{struct dirent} contains a @code{d_ino}
6407 member, define @code{HAVE_STRUCT_DIRENT_D_INO}.
6409 @code{HAVE_STRUCT_DIRENT_D_INO} indicates only the presence of
6410 @code{d_ino}, not whether its contents are always reliable.
6411 Traditionally, a zero @code{d_ino} indicated a deleted directory entry,
6412 though current systems hide this detail from the user and never return
6413 zero @code{d_ino} values.
6414 Many current systems report an incorrect @code{d_ino} for a directory
6415 entry that is a mount point.
6416 @end defmac
6418 @defmac AC_STRUCT_DIRENT_D_TYPE
6419 @acindex{STRUCT_DIRENT_D_TYPE}
6420 @cvindex HAVE_STRUCT_DIRENT_D_TYPE
6421 @c @caindex header_dirent_dirent_h
6422 @c @caindex member_struct_dirent_d_type
6423 Perform all the actions of @code{AC_HEADER_DIRENT} (@pxref{Particular
6424 Headers}).  Then, if @code{struct dirent} contains a @code{d_type}
6425 member, define @code{HAVE_STRUCT_DIRENT_D_TYPE}.
6426 @end defmac
6428 @anchor{AC_STRUCT_ST_BLOCKS}
6429 @defmac AC_STRUCT_ST_BLOCKS
6430 @acindex{STRUCT_ST_BLOCKS}
6431 @cvindex HAVE_STRUCT_STAT_ST_BLOCKS
6432 @cvindex HAVE_ST_BLOCKS
6433 @ovindex LIBOBJS
6434 @caindex member_struct_stat_st_blocks
6435 If @code{struct stat} contains an @code{st_blocks} member, define
6436 @code{HAVE_STRUCT_STAT_ST_BLOCKS}.  Otherwise, require an
6437 @code{AC_LIBOBJ} replacement of @samp{fileblocks}.  The former name,
6438 @code{HAVE_ST_BLOCKS} is to be avoided, as its support will cease in the
6439 future.
6441 This macro caches its result in the @code{ac_cv_member_struct_stat_st_blocks}
6442 variable.
6443 @end defmac
6445 @defmac AC_STRUCT_TM
6446 @acindex{STRUCT_TM}
6447 @cvindex TM_IN_SYS_TIME
6448 @hdrindex{time.h}
6449 @hdrindex{sys/time.h}
6450 If @file{time.h} does not define @code{struct tm}, define
6451 @code{TM_IN_SYS_TIME}, which means that including @file{sys/time.h}
6452 had better define @code{struct tm}.
6454 This macro is obsolescent, as @file{time.h} defines @code{struct tm} in
6455 current systems.  New programs need not use this macro.
6456 @end defmac
6458 @anchor{AC_STRUCT_TIMEZONE}
6459 @defmac AC_STRUCT_TIMEZONE
6460 @acindex{STRUCT_TIMEZONE}
6461 @cvindex HAVE_DECL_TZNAME
6462 @cvindex HAVE_STRUCT_TM_TM_ZONE
6463 @cvindex HAVE_TM_ZONE
6464 @cvindex HAVE_TZNAME
6465 @c @caindex member_struct_tm_tm_zone
6466 @c @caindex struct_tm
6467 Figure out how to get the current timezone.  If @code{struct tm} has a
6468 @code{tm_zone} member, define @code{HAVE_STRUCT_TM_TM_ZONE} (and the
6469 obsoleted @code{HAVE_TM_ZONE}).  Otherwise, if the external array
6470 @code{tzname} is found, define @code{HAVE_TZNAME}; if it is declared,
6471 define @code{HAVE_DECL_TZNAME}.
6472 @end defmac
6474 @node Generic Structures
6475 @subsection Generic Structure Checks
6477 These macros are used to find structure members not covered by the
6478 ``particular'' test macros.
6480 @defmac AC_CHECK_MEMBER (@var{aggregate}.@var{member}, @
6481   @ovar{action-if-found}, @ovar{action-if-not-found}, @
6482   @dvar{includes, AC_INCLUDES_DEFAULT})
6483 @acindex{CHECK_MEMBER}
6484 @caindex member_@var{aggregate}_@var{member}
6485 Check whether @var{member} is a member of the aggregate @var{aggregate}.
6486 If no @var{includes} are specified, the default includes are used
6487 (@pxref{Default Includes}).
6489 @example
6490 AC_CHECK_MEMBER([struct passwd.pw_gecos], [],
6491                 [AC_MSG_ERROR([we need `passwd.pw_gecos'])],
6492                 [[#include <pwd.h>]])
6493 @end example
6495 You can use this macro for submembers:
6497 @example
6498 AC_CHECK_MEMBER(struct top.middle.bot)
6499 @end example
6501 This macro caches its result in the
6502 @code{av_cv_member_@var{aggregate}_@var{member}} variable, with
6503 characters not suitable for a variable name mapped to underscores.
6504 @end defmac
6506 @anchor{AC_CHECK_MEMBERS}
6507 @defmac AC_CHECK_MEMBERS (@var{members}, @ovar{action-if-found}, @
6508   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6509 @acindex{CHECK_MEMBERS}
6510 @cvindex HAVE_@var{aggregate}_@var{member}
6511 Check for the existence of each @samp{@var{aggregate}.@var{member}} of
6512 @var{members} using the previous macro.  When @var{member} belongs to
6513 @var{aggregate}, define @code{HAVE_@var{aggregate}_@var{member}} (in all
6514 capitals, with spaces and dots replaced by underscores).  If
6515 @var{action-if-found} is given, it is executed for each of the found
6516 members.  If @var{action-if-not-found} is given, it is executed for each
6517 of the members that could not be found.
6519 @var{includes} is a series of include directives, defaulting to
6520 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
6521 prior to the members under test.
6523 This macro uses M4 lists:
6524 @example
6525 AC_CHECK_MEMBERS([struct stat.st_rdev, struct stat.st_blksize])
6526 @end example
6527 @end defmac
6530 @node Types
6531 @section Types
6532 @cindex Types
6533 @cindex C types
6535 The following macros check for C types, either builtin or typedefs.  If
6536 there is no macro specifically defined to check for a type you need, and
6537 you don't need to check for any special properties of it, then you can
6538 use a general type-check macro.
6540 @menu
6541 * Particular Types::            Special handling to find certain types
6542 * Generic Types::               How to find other types
6543 @end menu
6545 @node Particular Types
6546 @subsection Particular Type Checks
6548 @hdrindex{sys/types.h}
6549 @hdrindex{stdlib.h}
6550 @hdrindex{stdint.h}
6551 @hdrindex{inttypes.h}
6552 These macros check for particular C types in @file{sys/types.h},
6553 @file{stdlib.h}, @file{stdint.h}, @file{inttypes.h} and others, if they
6554 exist.
6556 The Gnulib @code{stdint} module is an alternate way to define many of
6557 these symbols; it is useful if you prefer your code to assume a
6558 C99-or-better environment.  @xref{Gnulib}.
6560 @anchor{AC_TYPE_GETGROUPS}
6561 @defmac AC_TYPE_GETGROUPS
6562 @acindex{TYPE_GETGROUPS}
6563 @cvindex GETGROUPS_T
6564 @caindex type_getgroups
6565 Define @code{GETGROUPS_T} to be whichever of @code{gid_t} or @code{int}
6566 is the base type of the array argument to @code{getgroups}.
6568 This macro caches the base type in the @code{ac_cv_type_getgroups}
6569 variable.
6570 @end defmac
6572 @defmac AC_TYPE_INT8_T
6573 @acindex{TYPE_INT8_T}
6574 @cvindex HAVE_INT8_T
6575 @cvindex int8_t
6576 @caindex c_int8_t
6577 If @file{stdint.h} or @file{inttypes.h} does not define the type
6578 @code{int8_t}, define @code{int8_t} to a signed
6579 integer type that is exactly 8 bits wide and that uses two's complement
6580 representation, if such a type exists.
6581 If you are worried about porting to hosts that lack such a type, you can
6582 use the results of this macro in C89-or-later code as follows:
6584 @example
6585 #if HAVE_STDINT_H
6586 # include <stdint.h>
6587 #endif
6588 #if defined INT8_MAX || defined int8_t
6589  @emph{code using int8_t}
6590 #else
6591  @emph{complicated alternative using >8-bit 'signed char'}
6592 #endif
6593 @end example
6595 This macro caches the type in the @code{ac_cv_c_int8_t} variable.
6596 @end defmac
6598 @defmac AC_TYPE_INT16_T
6599 @acindex{TYPE_INT16_T}
6600 @cvindex HAVE_INT16_T
6601 @cvindex int16_t
6602 @caindex c_int16_t
6603 This is like @code{AC_TYPE_INT8_T}, except for 16-bit integers.
6604 @end defmac
6606 @defmac AC_TYPE_INT32_T
6607 @acindex{TYPE_INT32_T}
6608 @cvindex HAVE_INT32_T
6609 @cvindex int32_t
6610 @caindex c_int32_t
6611 This is like @code{AC_TYPE_INT8_T}, except for 32-bit integers.
6612 @end defmac
6614 @defmac AC_TYPE_INT64_T
6615 @acindex{TYPE_INT64_T}
6616 @cvindex HAVE_INT64_T
6617 @cvindex int64_t
6618 @caindex c_int64_t
6619 This is like @code{AC_TYPE_INT8_T}, except for 64-bit integers.
6620 @end defmac
6622 @defmac AC_TYPE_INTMAX_T
6623 @acindex{TYPE_INTMAX_T}
6624 @cvindex HAVE_INTMAX_T
6625 @cvindex intmax_t
6626 @c @caindex type_intmax_t
6627 If @file{stdint.h} or @file{inttypes.h} defines the type @code{intmax_t},
6628 define @code{HAVE_INTMAX_T}.  Otherwise, define @code{intmax_t} to the
6629 widest signed integer type.
6630 @end defmac
6632 @defmac AC_TYPE_INTPTR_T
6633 @acindex{TYPE_INTPTR_T}
6634 @cvindex HAVE_INTPTR_T
6635 @cvindex intptr_t
6636 @c @caindex type_intptr_t
6637 If @file{stdint.h} or @file{inttypes.h} defines the type @code{intptr_t},
6638 define @code{HAVE_INTPTR_T}.  Otherwise, define @code{intptr_t} to a
6639 signed integer type wide enough to hold a pointer, if such a type
6640 exists.
6641 @end defmac
6643 @defmac AC_TYPE_LONG_DOUBLE
6644 @acindex{TYPE_LONG_DOUBLE}
6645 @cvindex HAVE_LONG_DOUBLE
6646 @caindex type_long_double
6647 If the C compiler supports a working @code{long double} type, define
6648 @code{HAVE_LONG_DOUBLE}.  The @code{long double} type might have the
6649 same range and precision as @code{double}.
6651 This macro caches its result in the @code{ac_cv_type_long_double}
6652 variable.
6654 This macro is obsolescent, as current C compilers support @code{long
6655 double}.  New programs need not use this macro.
6656 @end defmac
6658 @defmac AC_TYPE_LONG_DOUBLE_WIDER
6659 @acindex{TYPE_LONG_DOUBLE_WIDER}
6660 @cvindex HAVE_LONG_DOUBLE_WIDER
6661 @caindex type_long_double_wider
6662 If the C compiler supports a working @code{long double} type with more
6663 range or precision than the @code{double} type, define
6664 @code{HAVE_LONG_DOUBLE_WIDER}.
6666 This macro caches its result in the @code{ac_cv_type_long_double_wider}
6667 variable.
6668 @end defmac
6670 @defmac AC_TYPE_LONG_LONG_INT
6671 @acindex{TYPE_LONG_LONG_INT}
6672 @cvindex HAVE_LONG_LONG_INT
6673 @caindex type_long_long_int
6674 If the C compiler supports a working @code{long long int} type, define
6675 @code{HAVE_LONG_LONG_INT}.  However, this test does not test
6676 @code{long long int} values in preprocessor @code{#if} expressions,
6677 because too many compilers mishandle such expressions.
6678 @xref{Preprocessor Arithmetic}.
6680 This macro caches its result in the @code{ac_cv_type_long_long_int}
6681 variable.
6682 @end defmac
6684 @defmac AC_TYPE_MBSTATE_T
6685 @acindex{TYPE_MBSTATE_T}
6686 @cvindex mbstate_t
6687 @hdrindex{wchar.h}
6688 @caindex type_mbstate_t
6689 Define @code{HAVE_MBSTATE_T} if @code{<wchar.h>} declares the
6690 @code{mbstate_t} type.  Also, define @code{mbstate_t} to be a type if
6691 @code{<wchar.h>} does not declare it.
6693 This macro caches its result in the @code{ac_cv_type_mbstate_t}
6694 variable.
6695 @end defmac
6697 @anchor{AC_TYPE_MODE_T}
6698 @defmac AC_TYPE_MODE_T
6699 @acindex{TYPE_MODE_T}
6700 @cvindex mode_t
6701 @caindex type_mode_t
6702 Define @code{mode_t} to a suitable type, if standard headers do not
6703 define it.
6705 This macro caches its result in the @code{ac_cv_type_mode_t} variable.
6706 @end defmac
6708 @anchor{AC_TYPE_OFF_T}
6709 @defmac AC_TYPE_OFF_T
6710 @acindex{TYPE_OFF_T}
6711 @cvindex off_t
6712 @caindex type_off_t
6713 Define @code{off_t} to a suitable type, if standard headers do not
6714 define it.
6716 This macro caches its result in the @code{ac_cv_type_off_t} variable.
6717 @end defmac
6719 @anchor{AC_TYPE_PID_T}
6720 @defmac AC_TYPE_PID_T
6721 @acindex{TYPE_PID_T}
6722 @cvindex pid_t
6723 @caindex type_pid_t
6724 Define @code{pid_t} to a suitable type, if standard headers do not
6725 define it.
6727 This macro caches its result in the @code{ac_cv_type_pid_t} variable.
6728 @end defmac
6730 @anchor{AC_TYPE_SIZE_T}
6731 @defmac AC_TYPE_SIZE_T
6732 @acindex{TYPE_SIZE_T}
6733 @cvindex size_t
6734 @caindex type_size_t
6735 Define @code{size_t} to a suitable type, if standard headers do not
6736 define it.
6738 This macro caches its result in the @code{ac_cv_type_size_t} variable.
6739 @end defmac
6741 @defmac AC_TYPE_SSIZE_T
6742 @acindex{TYPE_SSIZE_T}
6743 @cvindex ssize_t
6744 @caindex type_ssize_t
6745 Define @code{ssize_t} to a suitable type, if standard headers do not
6746 define it.
6748 This macro caches its result in the @code{ac_cv_type_ssize_t} variable.
6749 @end defmac
6751 @anchor{AC_TYPE_UID_T}
6752 @defmac AC_TYPE_UID_T
6753 @acindex{TYPE_UID_T}
6754 @cvindex uid_t
6755 @cvindex gid_t
6756 @caindex type_uid_t
6757 Define @code{uid_t} and @code{gid_t} to suitable types, if standard
6758 headers do not define them.
6760 This macro caches its result in the @code{ac_cv_type_uid_t} variable.
6761 @end defmac
6763 @defmac AC_TYPE_UINT8_T
6764 @acindex{TYPE_UINT8_T}
6765 @cvindex HAVE_UINT8_T
6766 @cvindex uint8_t
6767 @caindex c_uint8_t
6768 If @file{stdint.h} or @file{inttypes.h} does not define the type
6769 @code{uint8_t}, define @code{uint8_t} to an
6770 unsigned integer type that is exactly 8 bits wide, if such a type
6771 exists.
6772 This is like @code{AC_TYPE_INT8_T}, except for unsigned integers.
6773 @end defmac
6775 @defmac AC_TYPE_UINT16_T
6776 @acindex{TYPE_UINT16_T}
6777 @cvindex HAVE_UINT16_T
6778 @cvindex uint16_t
6779 @caindex c_uint16_t
6780 This is like @code{AC_TYPE_UINT8_T}, except for 16-bit integers.
6781 @end defmac
6783 @defmac AC_TYPE_UINT32_T
6784 @acindex{TYPE_UINT32_T}
6785 @cvindex HAVE_UINT32_T
6786 @cvindex uint32_t
6787 @caindex c_uint32_t
6788 This is like @code{AC_TYPE_UINT8_T}, except for 32-bit integers.
6789 @end defmac
6791 @defmac AC_TYPE_UINT64_T
6792 @acindex{TYPE_UINT64_T}
6793 @cvindex HAVE_UINT64_T
6794 @cvindex uint64_t
6795 @caindex c_uint64_t
6796 This is like @code{AC_TYPE_UINT8_T}, except for 64-bit integers.
6797 @end defmac
6799 @defmac AC_TYPE_UINTMAX_T
6800 @acindex{TYPE_UINTMAX_T}
6801 @cvindex HAVE_UINTMAX_T
6802 @cvindex uintmax_t
6803 @c @caindex type_uintmax_t
6804 If @file{stdint.h} or @file{inttypes.h} defines the type @code{uintmax_t},
6805 define @code{HAVE_UINTMAX_T}.  Otherwise, define @code{uintmax_t} to the
6806 widest unsigned integer type.
6807 @end defmac
6809 @defmac AC_TYPE_UINTPTR_T
6810 @acindex{TYPE_UINTPTR_T}
6811 @cvindex HAVE_UINTPTR_T
6812 @cvindex uintptr_t
6813 @c @caindex type_uintptr_t
6814 If @file{stdint.h} or @file{inttypes.h} defines the type @code{uintptr_t},
6815 define @code{HAVE_UINTPTR_T}.  Otherwise, define @code{uintptr_t} to an
6816 unsigned integer type wide enough to hold a pointer, if such a type
6817 exists.
6818 @end defmac
6820 @defmac AC_TYPE_UNSIGNED_LONG_LONG_INT
6821 @acindex{TYPE_UNSIGNED_LONG_LONG_INT}
6822 @cvindex HAVE_UNSIGNED_LONG_LONG_INT
6823 @caindex type_unsigned_long_long_int
6824 If the C compiler supports a working @code{unsigned long long int} type,
6825 define @code{HAVE_UNSIGNED_LONG_LONG_INT}.  However, this test does not test
6826 @code{unsigned long long int} values in preprocessor @code{#if} expressions,
6827 because too many compilers mishandle such expressions.
6828 @xref{Preprocessor Arithmetic}.
6830 This macro caches its result in the @code{ac_cv_type_unsigned_long_long_int}
6831 variable.
6832 @end defmac
6834 @node Generic Types
6835 @subsection Generic Type Checks
6837 These macros are used to check for types not covered by the ``particular''
6838 test macros.
6840 @defmac AC_CHECK_TYPE (@var{type}, @ovar{action-if-found}, @
6841   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6842 @acindex{CHECK_TYPE}
6843 @caindex type_@var{type}
6844 Check whether @var{type} is defined.  It may be a compiler builtin type
6845 or defined by the @var{includes}.  @var{includes} is a series of include
6846 directives, defaulting to @code{AC_INCLUDES_DEFAULT} (@pxref{Default
6847 Includes}), which are used prior to the type under test.
6849 In C, @var{type} must be a type-name, so that the expression @samp{sizeof
6850 (@var{type})} is valid (but @samp{sizeof ((@var{type}))} is not).  The
6851 same test is applied when compiling for C++, which means that in C++
6852 @var{type} should be a type-id and should not be an anonymous
6853 @samp{struct} or @samp{union}.
6855 This macro caches its result in the @code{ac_cv_type_@var{type}}
6856 variable, with @samp{*} mapped to @samp{p} and other characters not
6857 suitable for a variable name mapped to underscores.
6858 @end defmac
6861 @defmac AC_CHECK_TYPES (@var{types}, @ovar{action-if-found}, @
6862   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6863 @acindex{CHECK_TYPES}
6864 @cvindex HAVE_@var{type}
6865 For each @var{type} of the @var{types} that is defined, define
6866 @code{HAVE_@var{type}} (in all capitals).  Each @var{type} must follow
6867 the rules of @code{AC_CHECK_TYPE}.  If no @var{includes} are
6868 specified, the default includes are used (@pxref{Default Includes}).  If
6869 @var{action-if-found} is given, it is additional shell code to execute
6870 when one of the types is found.  If @var{action-if-not-found} is given,
6871 it is executed when one of the types is not found.
6873 This macro uses M4 lists:
6874 @example
6875 AC_CHECK_TYPES([ptrdiff_t])
6876 AC_CHECK_TYPES([unsigned long long int, uintmax_t])
6877 AC_CHECK_TYPES([float_t], [], [], [[#include <math.h>]])
6878 @end example
6880 @end defmac
6882 Autoconf, up to 2.13, used to provide to another version of
6883 @code{AC_CHECK_TYPE}, broken by design.  In order to keep backward
6884 compatibility, a simple heuristic, quite safe but not totally, is
6885 implemented.  In case of doubt, read the documentation of the former
6886 @code{AC_CHECK_TYPE}, see @ref{Obsolete Macros}.
6889 @node Compilers and Preprocessors
6890 @section Compilers and Preprocessors
6891 @cindex Compilers
6892 @cindex Preprocessors
6894 @ovindex EXEEXT
6895 All the tests for compilers (@code{AC_PROG_CC}, @code{AC_PROG_CXX},
6896 @code{AC_PROG_F77}) define the output variable @code{EXEEXT} based on
6897 the output of the compiler, typically to the empty string if
6898 Posix and @samp{.exe} if a DOS variant.
6900 @ovindex OBJEXT
6901 They also define the output variable @code{OBJEXT} based on the
6902 output of the compiler, after @file{.c} files have been excluded, typically
6903 to @samp{o} if Posix, @samp{obj} if a DOS variant.
6905 If the compiler being used does not produce executables, the tests fail.  If
6906 the executables can't be run, and cross-compilation is not enabled, they
6907 fail too.  @xref{Manual Configuration}, for more on support for cross
6908 compiling.
6910 @menu
6911 * Specific Compiler Characteristics::  Some portability issues
6912 * Generic Compiler Characteristics::  Language independent tests and features
6913 * C Compiler::                  Checking its characteristics
6914 * C++ Compiler::                Likewise
6915 * Objective C Compiler::        Likewise
6916 * Objective C++ Compiler::      Likewise
6917 * Erlang Compiler and Interpreter::  Likewise
6918 * Fortran Compiler::            Likewise
6919 @end menu
6921 @node Specific Compiler Characteristics
6922 @subsection Specific Compiler Characteristics
6924 Some compilers exhibit different behaviors.
6926 @table @asis
6927 @item Static/Dynamic Expressions
6928 Autoconf relies on a trick to extract one bit of information from the C
6929 compiler: using negative array sizes.  For instance the following
6930 excerpt of a C source demonstrates how to test whether @samp{int} objects are 4
6931 bytes wide:
6933 @example
6934 static int test_array[sizeof (int) == 4 ? 1 : -1];
6935 @end example
6937 @noindent
6938 To our knowledge, there is a single compiler that does not support this
6939 trick: the HP C compilers (the real ones, not only the
6940 ``bundled'') on HP-UX 11.00.
6941 They incorrectly reject the above program with the diagnostic
6942 ``Variable-length arrays cannot have static storage.''
6943 This bug comes from HP compilers' mishandling of @code{sizeof (int)},
6944 not from the @code{? 1 : -1}, and
6945 Autoconf works around this problem by casting @code{sizeof (int)} to
6946 @code{long int} before comparing it.
6947 @end table
6949 @node Generic Compiler Characteristics
6950 @subsection Generic Compiler Characteristics
6952 @anchor{AC_CHECK_SIZEOF}
6953 @defmac AC_CHECK_SIZEOF (@var{type-or-expr}, @ovar{unused}, @
6954   @dvar{includes, AC_INCLUDES_DEFAULT})
6955 @acindex{CHECK_SIZEOF}
6956 @cvindex SIZEOF_@var{type-or-expr}
6957 @caindex sizeof_@var{type-or-expr}
6958 Define @code{SIZEOF_@var{type-or-expr}} (@pxref{Standard Symbols}) to be
6959 the size in bytes of @var{type-or-expr}, which may be either a type or
6960 an expression returning a value that has a size.  If the expression
6961 @samp{sizeof (@var{type-or-expr})} is invalid, the result is 0.
6962 @var{includes} is a series of include directives, defaulting to
6963 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
6964 prior to the expression under test.
6966 This macro now works even when cross-compiling.  The @var{unused}
6967 argument was used when cross-compiling.
6969 For example, the call
6971 @example
6972 @c If you change this example, adjust tests/semantics.at:AC_CHECK_SIZEOF struct.
6973 AC_CHECK_SIZEOF([int *])
6974 @end example
6976 @noindent
6977 defines @code{SIZEOF_INT_P} to be 8 on DEC Alpha AXP systems.
6979 This macro caches its result in the @code{ac_cv_sizeof_@var{type-or-expr}}
6980 variable, with @samp{*} mapped to @samp{p} and other characters not
6981 suitable for a variable name mapped to underscores.
6982 @end defmac
6984 @defmac AC_CHECK_ALIGNOF (@var{type}, @dvar{includes, AC_INCLUDES_DEFAULT})
6985 @acindex{CHECK_ALIGNOF}
6986 @cvindex ALIGNOF_@var{type}
6987 @caindex alignof_@var{type-or-expr}
6988 Define @code{ALIGNOF_@var{type}} (@pxref{Standard Symbols}) to be the
6989 alignment in bytes of @var{type}.  @samp{@var{type} y;} must be valid as
6990 a structure member declaration.  If @samp{type} is unknown, the result
6991 is 0.  If no @var{includes} are specified, the default includes are used
6992 (@pxref{Default Includes}).
6994 This macro caches its result in the @code{ac_cv_alignof_@var{type-or-expr}}
6995 variable, with @samp{*} mapped to @samp{p} and other characters not
6996 suitable for a variable name mapped to underscores.
6997 @end defmac
6999 @defmac AC_COMPUTE_INT (@var{var}, @var{expression}, @
7000   @dvar{includes, AC_INCLUDES_DEFAULT}, @ovar{action-if-fails})
7001 @acindex{COMPUTE_INT}
7002 Store into the shell variable @var{var} the value of the integer
7003 @var{expression}.  The
7004 value should fit in an initializer in a C variable of type @code{signed
7005 long}.  To support cross compilation (in which case, the macro only works on
7006 hosts that use twos-complement arithmetic), it should be possible to evaluate
7007 the expression at compile-time.  If no @var{includes} are specified, the
7008 default includes are used (@pxref{Default Includes}).
7010 Execute @var{action-if-fails} if the value cannot be determined correctly.
7011 @end defmac
7013 @defmac AC_LANG_WERROR
7014 @acindex{LANG_WERROR}
7015 Normally Autoconf ignores warnings generated by the compiler, linker, and
7016 preprocessor.  If this macro is used, warnings count as fatal
7017 errors for the current language.  This macro is useful when the
7018 results of configuration are used where warnings are unacceptable; for
7019 instance, if parts of a program are built with the GCC
7020 @option{-Werror}
7021 option.  If the whole program is built using @option{-Werror} it is
7022 often simpler to put @option{-Werror} in the compiler flags (@code{CFLAGS},
7023 etc.).
7024 @end defmac
7026 @defmac AC_OPENMP
7027 @acindex{OPENMP}
7028 @cvindex _OPENMP
7029 @ovindex OPENMP_CFLAGS
7030 @ovindex OPENMP_CXXFLAGS
7031 @ovindex OPENMP_FFLAGS
7032 @ovindex OPENMP_FCFLAGS
7033 OpenMP (@url{http://@/www.openmp.org/}) specifies extensions of C, C++,
7034 and Fortran that simplify optimization of shared memory parallelism,
7035 which is a common problem on multicore CPUs.
7037 If the current language is C, the macro @code{AC_OPENMP} sets the
7038 variable @code{OPENMP_CFLAGS} to the C compiler flags needed for
7039 supporting OpenMP@.  @code{OPENMP_CFLAGS} is set to empty if the
7040 compiler already supports OpenMP, if it has no way to activate OpenMP
7041 support, or if the user rejects OpenMP support by invoking
7042 @samp{configure} with the @samp{--disable-openmp} option.
7044 @code{OPENMP_CFLAGS} needs to be used when compiling programs, when
7045 preprocessing program source, and when linking programs.  Therefore you
7046 need to add @code{$(OPENMP_CFLAGS)} to the @code{CFLAGS} of C programs
7047 that use OpenMP@.  If you preprocess OpenMP-specific C code, you also
7048 need to add @code{$(OPENMP_CFLAGS)} to @code{CPPFLAGS}.  The presence of
7049 OpenMP support is revealed at compile time by the preprocessor macro
7050 @code{_OPENMP}.
7052 Linking a program with @code{OPENMP_CFLAGS} typically adds one more
7053 shared library to the program's dependencies, so its use is recommended
7054 only on programs that actually require OpenMP.
7056 If the current language is C++, @code{AC_OPENMP} sets the variable
7057 @code{OPENMP_CXXFLAGS}, suitably for the C++ compiler.  The same remarks
7058 hold as for C.
7060 If the current language is Fortran 77 or Fortran, @code{AC_OPENMP} sets
7061 the variable @code{OPENMP_FFLAGS} or @code{OPENMP_FCFLAGS},
7062 respectively.  Similar remarks as for C hold, except that
7063 @code{CPPFLAGS} is not used for Fortran, and no preprocessor macro
7064 signals OpenMP support.
7066 For portability, it is best to avoid spaces between @samp{#} and
7067 @samp{pragma omp}.  That is, write @samp{#pragma omp}, not
7068 @samp{# pragma omp}.  The Sun WorkShop 6.2 C compiler chokes on the
7069 latter.
7070 @end defmac
7072 @node C Compiler
7073 @subsection C Compiler Characteristics
7075 The following macros provide ways to find and exercise a C Compiler.
7076 There are a few constructs that ought to be avoided, but do not deserve
7077 being checked for, since they can easily be worked around.
7079 @table @asis
7080 @item Don't use lines containing solitary backslashes
7081 They tickle a bug in the HP-UX C compiler (checked on
7082 HP-UX 10.20,
7083 11.00, and 11i).  When given the following source:
7085 @example
7086 #ifdef __STDC__
7088 * A comment with backslash-newlines in it.  %@{ %@} *\
7091 char str[] = "\\
7092 " A string with backslash-newlines in it %@{ %@} \\
7094 char apostrophe = '\\
7098 #endif
7099 @end example
7101 @noindent
7102 the compiler incorrectly fails with the diagnostics ``Non-terminating
7103 comment at end of file'' and ``Missing @samp{#endif} at end of file.''
7104 Removing the lines with solitary backslashes solves the problem.
7106 @item Don't compile several files at once if output matters to you
7107 Some compilers, such as HP's, report names of files being
7108 compiled when given more than one file operand.  For instance:
7110 @example
7111 $ @kbd{cc a.c b.c}
7112 a.c:
7113 b.c:
7114 @end example
7116 @noindent
7117 This can cause problems if you observe the output of the compiler to
7118 detect failures.  Invoking @samp{cc -c a.c && cc -c b.c && cc -o c a.o
7119 b.o} solves the issue.
7121 @item Don't rely on @code{#error} failing
7122 The IRIX C compiler does not fail when #error is preprocessed; it
7123 simply emits a diagnostic and continues, exiting successfully.  So,
7124 instead of an error directive like @code{#error "Unsupported word size"}
7125 it is more portable to use an invalid directive like @code{#Unsupported
7126 word size} in Autoconf tests.  In ordinary source code, @code{#error} is
7127 OK, since installers with inadequate compilers like IRIX can simply
7128 examine these compilers' diagnostic output.
7130 @item Don't rely on correct @code{#line} support
7131 On Solaris, @command{c89} (at least Sun C 5.3 through 5.8)
7132 diagnoses @code{#line} directives whose line
7133 numbers are greater than 32767.  Nothing in Posix
7134 makes this invalid.  That is why Autoconf stopped issuing
7135 @code{#line} directives.
7136 @end table
7138 @defmac AC_PROG_CC (@ovar{compiler-search-list})
7139 @acindex{PROG_CC}
7140 @evindex CC
7141 @evindex CFLAGS
7142 @ovindex CC
7143 @ovindex CFLAGS
7144 @caindex prog_cc_c89
7145 Determine a C compiler to use.  If @code{CC} is not already set in the
7146 environment, check for @code{gcc} and @code{cc}, then for other C
7147 compilers.  Set output variable @code{CC} to the name of the compiler
7148 found.
7150 This macro may, however, be invoked with an optional first argument
7151 which, if specified, must be a blank-separated list of C compilers to
7152 search for.  This just gives the user an opportunity to specify an
7153 alternative search list for the C compiler.  For example, if you didn't
7154 like the default order, then you could invoke @code{AC_PROG_CC} like
7155 this:
7157 @example
7158 AC_PROG_CC([gcc cl cc])
7159 @end example
7161 If the C compiler does not handle function prototypes correctly by
7162 default, try to add an option to output variable @code{CC} to make it
7163 so.  This macro tries various options that select standard-conformance
7164 modes on various systems.
7166 After calling this macro you can check whether the C compiler has been
7167 set to accept ANSI C89 (ISO C90); if not, the shell
7168 variable
7169 @code{ac_cv_prog_cc_c89} is set to @samp{no}.  See also
7170 @code{AC_C_PROTOTYPES} below.
7172 If using the GNU C compiler, set shell variable @code{GCC} to
7173 @samp{yes}.  If output variable @code{CFLAGS} was not already set, set
7174 it to @option{-g -O2} for the GNU C compiler (@option{-O2} on systems
7175 where GCC does not accept @option{-g}), or @option{-g} for
7176 other compilers.  If your package does not like this default, then it is
7177 acceptable to insert the line @samp{: $@{CFLAGS=""@}} after @code{AC_INIT}
7178 and before @code{AC_PROG_CC} to select an empty default instead.
7180 Many Autoconf macros use a compiler, and thus call
7181 @samp{AC_REQUIRE([AC_PROG_CC])} to ensure that the compiler has been
7182 determined before the body of the outermost @code{AC_DEFUN} macro.
7183 Although @code{AC_PROG_CC} is safe to directly expand multiple times, it
7184 performs certain checks (such as the proper value of @env{EXEEXT}) only
7185 on the first invocation.  Therefore, care must be used when invoking
7186 this macro from within another macro rather than at the top level
7187 (@pxref{Expanded Before Required}).
7188 @end defmac
7190 @anchor{AC_PROG_CC_C_O}
7191 @defmac AC_PROG_CC_C_O
7192 @acindex{PROG_CC_C_O}
7193 @cvindex NO_MINUS_C_MINUS_O
7194 @caindex prog_cc_@var{compiler}_c_o
7195 If the C compiler does not accept the @option{-c} and @option{-o} options
7196 simultaneously, define @code{NO_MINUS_C_MINUS_O}.  This macro actually
7197 tests both the compiler found by @code{AC_PROG_CC}, and, if different,
7198 the first @code{cc} in the path.  The test fails if one fails.  This
7199 macro was created for GNU Make to choose the default C compilation
7200 rule.
7202 For the compiler @var{compiler}, this macro caches its result in the
7203 @code{ac_cv_prog_cc_@var{compiler}_c_o} variable.
7204 @end defmac
7207 @defmac AC_PROG_CPP
7208 @acindex{PROG_CPP}
7209 @evindex CPP
7210 @ovindex CPP
7211 Set output variable @code{CPP} to a command that runs the
7212 C preprocessor.  If @samp{$CC -E} doesn't work, @file{/lib/cpp} is used.
7213 It is only portable to run @code{CPP} on files with a @file{.c}
7214 extension.
7216 Some preprocessors don't indicate missing include files by the error
7217 status.  For such preprocessors an internal variable is set that causes
7218 other macros to check the standard error from the preprocessor and
7219 consider the test failed if any warnings have been reported.
7220 For most preprocessors, though, warnings do not cause include-file
7221 tests to fail unless @code{AC_PROG_CPP_WERROR} is also specified.
7222 @end defmac
7224 @defmac AC_PROG_CPP_WERROR
7225 @acindex{PROG_CPP_WERROR}
7226 @ovindex CPP
7227 This acts like @code{AC_PROG_CPP}, except it treats warnings from the
7228 preprocessor as errors even if the preprocessor exit status indicates
7229 success.  This is useful for avoiding headers that generate mandatory
7230 warnings, such as deprecation notices.
7231 @end defmac
7234 The following macros check for C compiler or machine architecture
7235 features.  To check for characteristics not listed here, use
7236 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}) or
7237 @code{AC_RUN_IFELSE} (@pxref{Runtime}).
7239 @defmac AC_PROG_CC_STDC
7240 @acindex{PROG_CC_STDC}
7241 @caindex prog_cc_stdc
7242 If the C compiler cannot compile ISO Standard C (currently
7243 C99), try to add an option to output variable @code{CC} to make it work.
7244 If the compiler does not support C99, fall back to supporting
7245 ANSI C89 (ISO C90).
7247 After calling this macro you can check whether the C compiler has been
7248 set to accept Standard C; if not, the shell variable
7249 @code{ac_cv_prog_cc_stdc} is set to @samp{no}.
7250 @end defmac
7252 @defmac AC_PROG_CC_C89
7253 @acindex{PROG_CC_C89}
7254 @caindex prog_cc_c89
7255 If the C compiler is not in ANSI C89 (ISO C90) mode by
7256 default, try to add an option to output variable @code{CC} to make it
7257 so.  This macro tries various options that select ANSI C89 on
7258 some system or another, preferring extended functionality modes over
7259 strict conformance modes.  It considers the compiler to be in
7260 ANSI C89 mode if it handles function prototypes correctly.
7262 After calling this macro you can check whether the C compiler has been
7263 set to accept ANSI C89; if not, the shell variable
7264 @code{ac_cv_prog_cc_c89} is set to @samp{no}.
7266 This macro is called automatically by @code{AC_PROG_CC}.
7267 @end defmac
7269 @defmac AC_PROG_CC_C99
7270 @acindex{PROG_CC_C99}
7271 @caindex prog_cc_c99
7272 If the C compiler is not in C99 mode by default, try to add an
7273 option to output variable @code{CC} to make it so.  This macro tries
7274 various options that select C99 on some system or another, preferring
7275 extended functionality modes over strict conformance modes.  It
7276 considers the compiler to be in C99 mode if it handles @code{_Bool},
7277 @code{//} comments, flexible array members, @code{inline}, signed and
7278 unsigned @code{long long int}, mixed code and declarations, named
7279 initialization of structs,
7280 @code{restrict}, @code{va_copy}, varargs macros, variable declarations
7281 in @code{for} loops, and variable length arrays.
7283 After calling this macro you can check whether the C compiler has been
7284 set to accept C99; if not, the shell variable
7285 @code{ac_cv_prog_cc_c99} is set to @samp{no}.
7286 @end defmac
7288 @defmac AC_C_BACKSLASH_A
7289 @acindex{C_BACKSLASH_A}
7290 @cvindex HAVE_C_BACKSLASH_A
7291 Define @samp{HAVE_C_BACKSLASH_A} to 1 if the C compiler understands
7292 @samp{\a}.
7294 This macro is obsolescent, as current C compilers understand @samp{\a}.
7295 New programs need not use this macro.
7296 @end defmac
7298 @anchor{AC_C_BIGENDIAN}
7299 @defmac AC_C_BIGENDIAN (@ovar{action-if-true}, @ovar{action-if-false}, @
7300   @ovar{action-if-unknown}, @ovar{action-if-universal})
7301 @acindex{C_BIGENDIAN}
7302 @cvindex WORDS_BIGENDIAN
7303 @cindex Endianness
7304 If words are stored with the most significant byte first (like Motorola
7305 and SPARC CPUs), execute @var{action-if-true}.  If words are stored with
7306 the least significant byte first (like Intel and VAX CPUs), execute
7307 @var{action-if-false}.
7309 This macro runs a test-case if endianness cannot be determined from the
7310 system header files.  When cross-compiling, the test-case is not run but
7311 grep'ed for some magic values.  @var{action-if-unknown} is executed if
7312 the latter case fails to determine the byte sex of the host system.
7314 In some cases a single run of a compiler can generate code for multiple
7315 architectures.  This can happen, for example, when generating Mac OS X
7316 universal binary files, which work on both PowerPC and Intel
7317 architectures.  In this case, the different variants might be for
7318 different architectures whose endiannesses differ.  If
7319 @command{configure} detects this, it executes @var{action-if-universal}
7320 instead of @var{action-if-unknown}.
7322 The default for @var{action-if-true} is to define
7323 @samp{WORDS_BIGENDIAN}.  The default for @var{action-if-false} is to do
7324 nothing.  The default for @var{action-if-unknown} is to
7325 abort configure and tell the installer how to bypass this test.
7326 And finally, the default for @var{action-if-universal} is to ensure that
7327 @samp{WORDS_BIGENDIAN} is defined if and only if a universal build is
7328 detected and the current code is big-endian; this default works only if
7329 @command{autoheader} is used (@pxref{autoheader Invocation}).
7331 If you use this macro without specifying @var{action-if-universal}, you
7332 should also use @code{AC_CONFIG_HEADERS}; otherwise
7333 @samp{WORDS_BIGENDIAN} may be set incorrectly for Mac OS X universal
7334 binary files.
7335 @end defmac
7337 @anchor{AC_C_CONST}
7338 @defmac AC_C_CONST
7339 @acindex{C_CONST}
7340 @cvindex const
7341 @caindex c_const
7342 If the C compiler does not fully support the @code{const} keyword,
7343 define @code{const} to be empty.  Some C compilers that do
7344 not define @code{__STDC__} do support @code{const}; some compilers that
7345 define @code{__STDC__} do not completely support @code{const}.  Programs
7346 can simply use @code{const} as if every C compiler supported it; for
7347 those that don't, the makefile or configuration header file
7348 defines it as empty.
7350 Occasionally installers use a C++ compiler to compile C code, typically
7351 because they lack a C compiler.  This causes problems with @code{const},
7352 because C and C++ treat @code{const} differently.  For example:
7354 @example
7355 const int foo;
7356 @end example
7358 @noindent
7359 is valid in C but not in C++.  These differences unfortunately cannot be
7360 papered over by defining @code{const} to be empty.
7362 If @command{autoconf} detects this situation, it leaves @code{const} alone,
7363 as this generally yields better results in practice.  However, using a
7364 C++ compiler to compile C code is not recommended or supported, and
7365 installers who run into trouble in this area should get a C compiler
7366 like GCC to compile their C code.
7368 This macro caches its result in the @code{ac_cv_c_const} variable.
7370 This macro is obsolescent, as current C compilers support @code{const}.
7371 New programs need not use this macro.
7372 @end defmac
7374 @defmac AC_C_RESTRICT
7375 @acindex{C_RESTRICT}
7376 @cvindex restrict
7377 @caindex c_restrict
7378 If the C compiler recognizes a variant spelling for the @code{restrict}
7379 keyword (@code{__restrict}, @code{__restrict__}, or @code{_Restrict}),
7380 then define @code{restrict} to that; this is more likely to do the right
7381 thing with compilers that support language variants where plain
7382 @code{restrict} is not a keyword.  Otherwise, if the C compiler
7383 recognizes the @code{restrict} keyword, don't do anything.
7384 Otherwise, define @code{restrict} to be empty.
7385 Thus, programs may simply use @code{restrict} as if every C compiler
7386 supported it; for those that do not, the makefile
7387 or configuration header defines it away.
7389 Although support in C++ for the @code{restrict} keyword is not
7390 required, several C++ compilers do accept the keyword.
7391 This macro works for them, too.
7393 This macro caches @samp{no} in the @code{ac_cv_c_restrict} variable
7394 if @code{restrict} is not supported, and a supported spelling otherwise.
7395 @end defmac
7397 @defmac AC_C_VOLATILE
7398 @acindex{C_VOLATILE}
7399 @cvindex volatile
7400 If the C compiler does not understand the keyword @code{volatile},
7401 define @code{volatile} to be empty.  Programs can simply use
7402 @code{volatile} as if every C compiler supported it; for those that do
7403 not, the makefile or configuration header defines it as
7404 empty.
7406 If the correctness of your program depends on the semantics of
7407 @code{volatile}, simply defining it to be empty does, in a sense, break
7408 your code.  However, given that the compiler does not support
7409 @code{volatile}, you are at its mercy anyway.  At least your
7410 program compiles, when it wouldn't before.
7411 @xref{Volatile Objects}, for more about @code{volatile}.
7413 In general, the @code{volatile} keyword is a standard C feature, so
7414 you might expect that @code{volatile} is available only when
7415 @code{__STDC__} is defined.  However, Ultrix 4.3's native compiler does
7416 support volatile, but does not define @code{__STDC__}.
7418 This macro is obsolescent, as current C compilers support @code{volatile}.
7419 New programs need not use this macro.
7420 @end defmac
7422 @anchor{AC_C_INLINE}
7423 @defmac AC_C_INLINE
7424 @acindex{C_INLINE}
7425 @cvindex inline
7426 If the C compiler supports the keyword @code{inline}, do nothing.
7427 Otherwise define @code{inline} to @code{__inline__} or @code{__inline}
7428 if it accepts one of those, otherwise define @code{inline} to be empty.
7429 @end defmac
7431 @anchor{AC_C_CHAR_UNSIGNED}
7432 @defmac AC_C_CHAR_UNSIGNED
7433 @acindex{C_CHAR_UNSIGNED}
7434 @cvindex __CHAR_UNSIGNED__
7435 If the C type @code{char} is unsigned, define @code{__CHAR_UNSIGNED__},
7436 unless the C compiler predefines it.
7438 These days, using this macro is not necessary.  The same information can
7439 be determined by this portable alternative, thus avoiding the use of
7440 preprocessor macros in the namespace reserved for the implementation.
7442 @example
7443 #include <limits.h>
7444 #if CHAR_MIN == 0
7445 # define CHAR_UNSIGNED 1
7446 #endif
7447 @end example
7448 @end defmac
7450 @defmac AC_C_STRINGIZE
7451 @acindex{C_STRINGIZE}
7452 @cvindex HAVE_STRINGIZE
7453 If the C preprocessor supports the stringizing operator, define
7454 @code{HAVE_STRINGIZE}.  The stringizing operator is @samp{#} and is
7455 found in macros such as this:
7457 @example
7458 #define x(y) #y
7459 @end example
7461 This macro is obsolescent, as current C compilers support the
7462 stringizing operator.  New programs need not use this macro.
7463 @end defmac
7465 @defmac AC_C_FLEXIBLE_ARRAY_MEMBER
7466 @acindex{C_FLEXIBLE_ARRAY_MEMBER}
7467 @cvindex FLEXIBLE_ARRAY_MEMBER
7468 If the C compiler supports flexible array members, define
7469 @code{FLEXIBLE_ARRAY_MEMBER} to nothing; otherwise define it to 1.
7470 That way, a declaration like this:
7472 @example
7473 struct s
7474   @{
7475     size_t n_vals;
7476     double val[FLEXIBLE_ARRAY_MEMBER];
7477   @};
7478 @end example
7480 @noindent
7481 will let applications use the ``struct hack'' even with compilers that
7482 do not support flexible array members.  To allocate and use such an
7483 object, you can use code like this:
7485 @example
7486 size_t i;
7487 size_t n = compute_value_count ();
7488 struct s *p =
7489    malloc (offsetof (struct s, val)
7490            + n * sizeof (double));
7491 p->n_vals = n;
7492 for (i = 0; i < n; i++)
7493   p->val[i] = compute_value (i);
7494 @end example
7495 @end defmac
7497 @defmac AC_C_VARARRAYS
7498 @acindex{C_VARARRAYS}
7499 @cvindex HAVE_C_VARARRAYS
7500 If the C compiler supports variable-length arrays, define
7501 @code{HAVE_C_VARARRAYS}.  A variable-length array is an array of automatic
7502 storage duration whose length is determined at run time, when the array
7503 is declared.
7504 @end defmac
7506 @defmac AC_C_TYPEOF
7507 @acindex{C_TYPEOF}
7508 @cvindex HAVE_TYPEOF
7509 @cvindex typeof
7510 If the C compiler supports GCC's @code{typeof} syntax either
7511 directly or
7512 through a different spelling of the keyword (e.g., @code{__typeof__}),
7513 define @code{HAVE_TYPEOF}.  If the support is available only through a
7514 different spelling, define @code{typeof} to that spelling.
7515 @end defmac
7517 @defmac AC_C_PROTOTYPES
7518 @acindex{C_PROTOTYPES}
7519 @cvindex PROTOTYPES
7520 @cvindex __PROTOTYPES
7521 @cvindex PARAMS
7522 If function prototypes are understood by the compiler (as determined by
7523 @code{AC_PROG_CC}), define @code{PROTOTYPES} and @code{__PROTOTYPES}.
7524 Defining @code{__PROTOTYPES} is for the benefit of
7525 header files that cannot use macros that infringe on user name space.
7527 This macro is obsolescent, as current C compilers support prototypes.
7528 New programs need not use this macro.
7529 @end defmac
7531 @anchor{AC_PROG_GCC_TRADITIONAL}
7532 @defmac AC_PROG_GCC_TRADITIONAL
7533 @acindex{PROG_GCC_TRADITIONAL}
7534 @ovindex CC
7535 Add @option{-traditional} to output variable @code{CC} if using the
7536 GNU C compiler and @code{ioctl} does not work properly without
7537 @option{-traditional}.  That usually happens when the fixed header files
7538 have not been installed on an old system.
7540 This macro is obsolescent, since current versions of the GNU C
7541 compiler fix the header files automatically when installed.
7542 @end defmac
7545 @node C++ Compiler
7546 @subsection C++ Compiler Characteristics
7549 @defmac AC_PROG_CXX (@ovar{compiler-search-list})
7550 @acindex{PROG_CXX}
7551 @evindex CXX
7552 @evindex CXXFLAGS
7553 @ovindex CXX
7554 @ovindex CXXFLAGS
7555 Determine a C++ compiler to use.  Check whether the environment variable
7556 @code{CXX} or @code{CCC} (in that order) is set; if so, then set output
7557 variable @code{CXX} to its value.
7559 Otherwise, if the macro is invoked without an argument, then search for
7560 a C++ compiler under the likely names (first @code{g++} and @code{c++}
7561 then other names).  If none of those checks succeed, then as a last
7562 resort set @code{CXX} to @code{g++}.
7564 This macro may, however, be invoked with an optional first argument
7565 which, if specified, must be a blank-separated list of C++ compilers to
7566 search for.  This just gives the user an opportunity to specify an
7567 alternative search list for the C++ compiler.  For example, if you
7568 didn't like the default order, then you could invoke @code{AC_PROG_CXX}
7569 like this:
7571 @example
7572 AC_PROG_CXX([gcc cl KCC CC cxx cc++ xlC aCC c++ g++])
7573 @end example
7575 If using the GNU C++ compiler, set shell variable @code{GXX} to
7576 @samp{yes}.  If output variable @code{CXXFLAGS} was not already set, set
7577 it to @option{-g -O2} for the GNU C++ compiler (@option{-O2} on
7578 systems where G++ does not accept @option{-g}), or @option{-g} for other
7579 compilers.  If your package does not like this default, then it is
7580 acceptable to insert the line @samp{: $@{CXXFLAGS=""@}} after @code{AC_INIT}
7581 and before @code{AC_PROG_CXX} to select an empty default instead.
7583 @end defmac
7585 @defmac AC_PROG_CXXCPP
7586 @acindex{PROG_CXXCPP}
7587 @evindex CXXCPP
7588 @ovindex CXXCPP
7589 Set output variable @code{CXXCPP} to a command that runs the C++
7590 preprocessor.  If @samp{$CXX -E} doesn't work, @file{/lib/cpp} is used.
7591 It is portable to run @code{CXXCPP} only on files with a @file{.c},
7592 @file{.C}, @file{.cc}, or @file{.cpp} extension.
7594 Some preprocessors don't indicate missing include files by the error
7595 status.  For such preprocessors an internal variable is set that causes
7596 other macros to check the standard error from the preprocessor and
7597 consider the test failed if any warnings have been reported.  However,
7598 it is not known whether such broken preprocessors exist for C++.
7599 @end defmac
7601 @defmac AC_PROG_CXX_C_O
7602 @acindex{PROG_CXX_C_O}
7603 @cvindex CXX_NO_MINUS_C_MINUS_O
7604 Test whether the C++ compiler accepts the options @option{-c} and
7605 @option{-o} simultaneously, and define @code{CXX_NO_MINUS_C_MINUS_O},
7606 if it does not.
7607 @end defmac
7610 @node Objective C Compiler
7611 @subsection Objective C Compiler Characteristics
7614 @defmac AC_PROG_OBJC (@ovar{compiler-search-list})
7615 @acindex{PROG_OBJC}
7616 @evindex OBJC
7617 @evindex OBJCFLAGS
7618 @ovindex OBJC
7619 @ovindex OBJCFLAGS
7620 Determine an Objective C compiler to use.  If @code{OBJC} is not already
7621 set in the environment, check for Objective C compilers.  Set output
7622 variable @code{OBJC} to the name of the compiler found.
7624 This macro may, however, be invoked with an optional first argument
7625 which, if specified, must be a blank-separated list of Objective C compilers to
7626 search for.  This just gives the user an opportunity to specify an
7627 alternative search list for the Objective C compiler.  For example, if you
7628 didn't like the default order, then you could invoke @code{AC_PROG_OBJC}
7629 like this:
7631 @example
7632 AC_PROG_OBJC([gcc objcc objc])
7633 @end example
7635 If using the GNU Objective C compiler, set shell variable
7636 @code{GOBJC} to @samp{yes}.  If output variable @code{OBJCFLAGS} was not
7637 already set, set it to @option{-g -O2} for the GNU Objective C
7638 compiler (@option{-O2} on systems where @command{gcc} does not accept
7639 @option{-g}), or @option{-g} for other compilers.
7640 @end defmac
7642 @defmac AC_PROG_OBJCPP
7643 @acindex{PROG_OBJCPP}
7644 @evindex OBJCPP
7645 @ovindex OBJCPP
7646 Set output variable @code{OBJCPP} to a command that runs the Objective C
7647 preprocessor.  If @samp{$OBJC -E} doesn't work, @file{/lib/cpp} is used.
7648 @end defmac
7651 @node Objective C++ Compiler
7652 @subsection Objective C++ Compiler Characteristics
7655 @defmac AC_PROG_OBJCXX (@ovar{compiler-search-list})
7656 @acindex{PROG_OBJCXX}
7657 @evindex OBJCXX
7658 @evindex OBJCXXFLAGS
7659 @ovindex OBJCXX
7660 @ovindex OBJCXXFLAGS
7661 Determine an Objective C++ compiler to use.  If @code{OBJCXX} is not already
7662 set in the environment, check for Objective C++ compilers.  Set output
7663 variable @code{OBJCXX} to the name of the compiler found.
7665 This macro may, however, be invoked with an optional first argument
7666 which, if specified, must be a blank-separated list of Objective C++ compilers
7667 to search for.  This just gives the user an opportunity to specify an
7668 alternative search list for the Objective C++ compiler.  For example, if you
7669 didn't like the default order, then you could invoke @code{AC_PROG_OBJCXX}
7670 like this:
7672 @example
7673 AC_PROG_OBJCXX([gcc g++ objcc++ objcxx])
7674 @end example
7676 If using the GNU Objective C++ compiler, set shell variable
7677 @code{GOBJCXX} to @samp{yes}.  If output variable @code{OBJCXXFLAGS} was not
7678 already set, set it to @option{-g -O2} for the GNU Objective C++
7679 compiler (@option{-O2} on systems where @command{gcc} does not accept
7680 @option{-g}), or @option{-g} for other compilers.
7681 @end defmac
7683 @defmac AC_PROG_OBJCXXCPP
7684 @acindex{PROG_OBJCXXCPP}
7685 @evindex OBJCXXCPP
7686 @ovindex OBJCXXCPP
7687 Set output variable @code{OBJCXXCPP} to a command that runs the Objective C++
7688 preprocessor.  If @samp{$OBJCXX -E} doesn't work, @file{/lib/cpp} is used.
7689 @end defmac
7692 @node Erlang Compiler and Interpreter
7693 @subsection Erlang Compiler and Interpreter Characteristics
7694 @cindex Erlang
7696 Autoconf defines the following macros for determining paths to the essential
7697 Erlang/OTP programs:
7699 @defmac AC_ERLANG_PATH_ERLC (@ovar{value-if-not-found}, @dvar{path, $PATH})
7700 @acindex{ERLANG_PATH_ERLC}
7701 @evindex ERLC
7702 @evindex ERLCFLAGS
7703 @ovindex ERLC
7704 @ovindex ERLCFLAGS
7705 Determine an Erlang compiler to use.  If @code{ERLC} is not already set in the
7706 environment, check for @command{erlc}.  Set output variable @code{ERLC} to the
7707 complete path of the compiler command found.  In addition, if @code{ERLCFLAGS}
7708 is not set in the environment, set it to an empty value.
7710 The two optional arguments have the same meaning as the two last arguments of
7711 macro @code{AC_PROG_PATH} for looking for the @command{erlc} program.  For
7712 example, to look for @command{erlc} only in the @file{/usr/lib/erlang/bin}
7713 directory:
7715 @example
7716 AC_ERLANG_PATH_ERLC([not found], [/usr/lib/erlang/bin])
7717 @end example
7718 @end defmac
7720 @defmac AC_ERLANG_NEED_ERLC (@dvar{path, $PATH})
7721 @acindex{ERLANG_NEED_ERLC}
7722 A simplified variant of the @code{AC_ERLANG_PATH_ERLC} macro, that prints an
7723 error message and exits the @command{configure} script if the @command{erlc}
7724 program is not found.
7725 @end defmac
7727 @defmac AC_ERLANG_PATH_ERL (@ovar{value-if-not-found}, @dvar{path, $PATH})
7728 @acindex{ERLANG_PATH_ERL}
7729 @evindex ERL
7730 @ovindex ERL
7731 Determine an Erlang interpreter to use.  If @code{ERL} is not already
7732 set in the
7733 environment, check for @command{erl}.  Set output variable @code{ERL} to the
7734 complete path of the interpreter command found.
7736 The two optional arguments have the same meaning as the two last arguments of
7737 macro @code{AC_PROG_PATH} for looking for the @command{erl} program.  For
7738 example, to look for @command{erl} only in the @file{/usr/lib/erlang/bin}
7739 directory:
7741 @example
7742 AC_ERLANG_PATH_ERL([not found], [/usr/lib/erlang/bin])
7743 @end example
7744 @end defmac
7746 @defmac AC_ERLANG_NEED_ERL (@dvar{path, $PATH})
7747 @acindex{ERLANG_NEED_ERL}
7748 A simplified variant of the @code{AC_ERLANG_PATH_ERL} macro, that prints an
7749 error message and exits the @command{configure} script if the @command{erl}
7750 program is not found.
7751 @end defmac
7754 @node Fortran Compiler
7755 @subsection Fortran Compiler Characteristics
7756 @cindex Fortran
7757 @cindex F77
7759 The Autoconf Fortran support is divided into two categories: legacy
7760 Fortran 77 macros (@code{F77}), and modern Fortran macros (@code{FC}).
7761 The former are intended for traditional Fortran 77 code, and have output
7762 variables like @code{F77}, @code{FFLAGS}, and @code{FLIBS}.  The latter
7763 are for newer programs that can (or must) compile under the newer
7764 Fortran standards, and have output variables like @code{FC},
7765 @code{FCFLAGS}, and @code{FCLIBS}.
7767 Except for the macros @code{AC_FC_SRCEXT}, @code{AC_FC_FREEFORM},
7768 @code{AC_FC_FIXEDFORM}, and @code{AC_FC_LINE_LENGTH} (see below), the
7769 @code{FC} and @code{F77} macros behave almost identically, and so they
7770 are documented together in this section.
7773 @defmac AC_PROG_F77 (@ovar{compiler-search-list})
7774 @acindex{PROG_F77}
7775 @evindex F77
7776 @evindex FFLAGS
7777 @ovindex F77
7778 @ovindex FFLAGS
7779 Determine a Fortran 77 compiler to use.  If @code{F77} is not already
7780 set in the environment, then check for @code{g77} and @code{f77}, and
7781 then some other names.  Set the output variable @code{F77} to the name
7782 of the compiler found.
7784 This macro may, however, be invoked with an optional first argument
7785 which, if specified, must be a blank-separated list of Fortran 77
7786 compilers to search for.  This just gives the user an opportunity to
7787 specify an alternative search list for the Fortran 77 compiler.  For
7788 example, if you didn't like the default order, then you could invoke
7789 @code{AC_PROG_F77} like this:
7791 @example
7792 AC_PROG_F77([fl32 f77 fort77 xlf g77 f90 xlf90])
7793 @end example
7795 If using @code{g77} (the GNU Fortran 77 compiler), then
7796 set the shell variable @code{G77} to @samp{yes}.
7797 If the output variable @code{FFLAGS} was not already set in the
7798 environment, then set it to @option{-g -02} for @code{g77} (or @option{-O2}
7799 where @code{g77} does not accept @option{-g}).  Otherwise, set
7800 @code{FFLAGS} to @option{-g} for all other Fortran 77 compilers.
7801 @end defmac
7803 @defmac AC_PROG_FC (@ovar{compiler-search-list}, @ovar{dialect})
7804 @acindex{PROG_FC}
7805 @evindex FC
7806 @evindex FCFLAGS
7807 @ovindex FC
7808 @ovindex FCFLAGS
7809 Determine a Fortran compiler to use.  If @code{FC} is not already set in
7810 the environment, then @code{dialect} is a hint to indicate what Fortran
7811 dialect to search for; the default is to search for the newest available
7812 dialect.  Set the output variable @code{FC} to the name of the compiler
7813 found.
7815 By default, newer dialects are preferred over older dialects, but if
7816 @code{dialect} is specified then older dialects are preferred starting
7817 with the specified dialect.  @code{dialect} can currently be one of
7818 Fortran 77, Fortran 90, or Fortran 95.  However, this is only a hint of
7819 which compiler @emph{name} to prefer (e.g., @code{f90} or @code{f95}),
7820 and no attempt is made to guarantee that a particular language standard
7821 is actually supported.  Thus, it is preferable that you avoid the
7822 @code{dialect} option, and use AC_PROG_FC only for code compatible with
7823 the latest Fortran standard.
7825 This macro may, alternatively, be invoked with an optional first argument
7826 which, if specified, must be a blank-separated list of Fortran
7827 compilers to search for, just as in @code{AC_PROG_F77}.
7829 If the output variable @code{FCFLAGS} was not already set in the
7830 environment, then set it to @option{-g -02} for GNU @code{g77} (or
7831 @option{-O2} where @code{g77} does not accept @option{-g}).  Otherwise,
7832 set @code{FCFLAGS} to @option{-g} for all other Fortran compilers.
7833 @end defmac
7835 @defmac AC_PROG_F77_C_O
7836 @defmacx AC_PROG_FC_C_O
7837 @acindex{PROG_F77_C_O}
7838 @acindex{PROG_FC_C_O}
7839 @cvindex F77_NO_MINUS_C_MINUS_O
7840 @cvindex FC_NO_MINUS_C_MINUS_O
7841 Test whether the Fortran compiler accepts the options @option{-c} and
7842 @option{-o} simultaneously, and define @code{F77_NO_MINUS_C_MINUS_O} or
7843 @code{FC_NO_MINUS_C_MINUS_O}, respectively, if it does not.
7844 @end defmac
7846 The following macros check for Fortran compiler characteristics.
7847 To check for characteristics not listed here, use
7848 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}) or
7849 @code{AC_RUN_IFELSE} (@pxref{Runtime}), making sure to first set the
7850 current language to Fortran 77 or Fortran via @code{AC_LANG([Fortran 77])}
7851 or @code{AC_LANG(Fortran)} (@pxref{Language Choice}).
7854 @defmac AC_F77_LIBRARY_LDFLAGS
7855 @defmacx AC_FC_LIBRARY_LDFLAGS
7856 @acindex{F77_LIBRARY_LDFLAGS}
7857 @ovindex FLIBS
7858 @acindex{FC_LIBRARY_LDFLAGS}
7859 @ovindex FCLIBS
7860 Determine the linker flags (e.g., @option{-L} and @option{-l}) for the
7861 @dfn{Fortran intrinsic and runtime libraries} that are required to
7862 successfully link a Fortran program or shared library.  The output
7863 variable @code{FLIBS} or @code{FCLIBS} is set to these flags (which
7864 should be included after @code{LIBS} when linking).
7866 This macro is intended to be used in those situations when it is
7867 necessary to mix, e.g., C++ and Fortran source code in a single
7868 program or shared library (@pxref{Mixing Fortran 77 With C and C++, , ,
7869 automake, GNU Automake}).
7871 For example, if object files from a C++ and Fortran compiler must be
7872 linked together, then the C++ compiler/linker must be used for linking
7873 (since special C++-ish things need to happen at link time like calling
7874 global constructors, instantiating templates, enabling exception
7875 support, etc.).
7877 However, the Fortran intrinsic and runtime libraries must be linked in
7878 as well, but the C++ compiler/linker doesn't know by default how to add
7879 these Fortran 77 libraries.  Hence, this macro was created to determine
7880 these Fortran libraries.
7882 The macros @code{AC_F77_DUMMY_MAIN} and @code{AC_FC_DUMMY_MAIN} or
7883 @code{AC_F77_MAIN} and @code{AC_FC_MAIN} are probably also necessary to
7884 link C/C++ with Fortran; see below.  Further, it is highly recommended
7885 that you use @code{AC_CONFIG_HEADERS} (@pxref{Configuration Headers})
7886 because the complex defines that the function wrapper macros create
7887 may not work with C/C++ compiler drivers.
7888 @end defmac
7890 @defmac AC_F77_DUMMY_MAIN (@ovar{action-if-found}, @ovar{action-if-not-found})
7891 @defmacx AC_FC_DUMMY_MAIN (@ovar{action-if-found}, @ovar{action-if-not-found})
7892 @acindex{F77_DUMMY_MAIN}
7893 @cvindex F77_DUMMY_MAIN
7894 @acindex{FC_DUMMY_MAIN}
7895 @cvindex FC_DUMMY_MAIN
7896 With many compilers, the Fortran libraries detected by
7897 @code{AC_F77_LIBRARY_LDFLAGS} or @code{AC_FC_LIBRARY_LDFLAGS} provide
7898 their own @code{main} entry function that initializes things like
7899 Fortran I/O, and which then calls a user-provided entry function named
7900 (say) @code{MAIN__} to run the user's program.  The
7901 @code{AC_F77_DUMMY_MAIN} and @code{AC_FC_DUMMY_MAIN} or
7902 @code{AC_F77_MAIN} and @code{AC_FC_MAIN} macros figure out how to deal with
7903 this interaction.
7905 When using Fortran for purely numerical functions (no I/O, etc.)@: often
7906 one prefers to provide one's own @code{main} and skip the Fortran
7907 library initializations.  In this case, however, one may still need to
7908 provide a dummy @code{MAIN__} routine in order to prevent linking errors
7909 on some systems.  @code{AC_F77_DUMMY_MAIN} or @code{AC_FC_DUMMY_MAIN}
7910 detects whether any such routine is @emph{required} for linking, and
7911 what its name is; the shell variable @code{F77_DUMMY_MAIN} or
7912 @code{FC_DUMMY_MAIN} holds this name, @code{unknown} when no solution
7913 was found, and @code{none} when no such dummy main is needed.
7915 By default, @var{action-if-found} defines @code{F77_DUMMY_MAIN} or
7916 @code{FC_DUMMY_MAIN} to the name of this routine (e.g., @code{MAIN__})
7917 @emph{if} it is required.  @var{action-if-not-found} defaults to
7918 exiting with an error.
7920 In order to link with Fortran routines, the user's C/C++ program should
7921 then include the following code to define the dummy main if it is
7922 needed:
7924 @example
7925 @c If you change this example, adjust tests/fortran.at:AC_F77_DUMMY_MAIN usage.
7926 #ifdef F77_DUMMY_MAIN
7927 #  ifdef __cplusplus
7928      extern "C"
7929 #  endif
7930    int F77_DUMMY_MAIN () @{ return 1; @}
7931 #endif
7932 @end example
7934 (Replace @code{F77} with @code{FC} for Fortran instead of Fortran 77.)
7936 Note that this macro is called automatically from @code{AC_F77_WRAPPERS}
7937 or @code{AC_FC_WRAPPERS}; there is generally no need to call it
7938 explicitly unless one wants to change the default actions.
7939 @end defmac
7941 @defmac AC_F77_MAIN
7942 @defmacx AC_FC_MAIN
7943 @acindex{F77_MAIN}
7944 @cvindex F77_MAIN
7945 @acindex{FC_MAIN}
7946 @cvindex FC_MAIN
7947 As discussed above, many Fortran libraries allow you to provide an entry
7948 point called (say) @code{MAIN__} instead of the usual @code{main}, which
7949 is then called by a @code{main} function in the Fortran libraries that
7950 initializes things like Fortran I/O@.  The
7951 @code{AC_F77_MAIN} and @code{AC_FC_MAIN} macros detect whether it is
7952 @emph{possible} to utilize such an alternate main function, and defines
7953 @code{F77_MAIN} and @code{FC_MAIN} to the name of the function.  (If no
7954 alternate main function name is found, @code{F77_MAIN} and @code{FC_MAIN} are
7955 simply defined to @code{main}.)
7957 Thus, when calling Fortran routines from C that perform things like I/O,
7958 one should use this macro and declare the "main" function like so:
7960 @example
7961 @c If you change this example, adjust tests/fortran.at:AC_F77_DUMMY_MAIN usage.
7962 #ifdef __cplusplus
7963   extern "C"
7964 #endif
7965 int F77_MAIN (int argc, char *argv[]);
7966 @end example
7968 (Again, replace @code{F77} with @code{FC} for Fortran instead of Fortran 77.)
7969 @end defmac
7971 @defmac AC_F77_WRAPPERS
7972 @defmacx AC_FC_WRAPPERS
7973 @acindex{F77_WRAPPERS}
7974 @cvindex F77_FUNC
7975 @cvindex F77_FUNC_
7976 @acindex{FC_WRAPPERS}
7977 @cvindex FC_FUNC
7978 @cvindex FC_FUNC_
7979 Defines C macros @code{F77_FUNC (name, NAME)}, @code{FC_FUNC (name, NAME)},
7980 @code{F77_FUNC_(name, NAME)}, and @code{FC_FUNC_(name, NAME)} to properly
7981 mangle the names of C/C++ identifiers, and identifiers with underscores,
7982 respectively, so that they match the name-mangling scheme used by the
7983 Fortran compiler.
7985 Fortran is case-insensitive, and in order to achieve this the Fortran
7986 compiler converts all identifiers into a canonical case and format.  To
7987 call a Fortran subroutine from C or to write a C function that is
7988 callable from Fortran, the C program must explicitly use identifiers in
7989 the format expected by the Fortran compiler.  In order to do this, one
7990 simply wraps all C identifiers in one of the macros provided by
7991 @code{AC_F77_WRAPPERS} or @code{AC_FC_WRAPPERS}.  For example, suppose
7992 you have the following Fortran 77 subroutine:
7994 @example
7995 @c If you change this example, adjust tests/fortran.at:AC_F77_DUMMY_MAIN usage.
7996       subroutine foobar (x, y)
7997       double precision x, y
7998       y = 3.14159 * x
7999       return
8000       end
8001 @end example
8003 You would then declare its prototype in C or C++ as:
8005 @example
8006 @c If you change this example, adjust tests/fortran.at:AC_F77_DUMMY_MAIN usage.
8007 #define FOOBAR_F77 F77_FUNC (foobar, FOOBAR)
8008 #ifdef __cplusplus
8009 extern "C"  /* prevent C++ name mangling */
8010 #endif
8011 void FOOBAR_F77 (double *x, double *y);
8012 @end example
8014 Note that we pass both the lowercase and uppercase versions of the
8015 function name to @code{F77_FUNC} so that it can select the right one.
8016 Note also that all parameters to Fortran 77 routines are passed as
8017 pointers (@pxref{Mixing Fortran 77 With C and C++, , , automake, GNU
8018 Automake}).
8020 (Replace @code{F77} with @code{FC} for Fortran instead of Fortran 77.)
8022 Although Autoconf tries to be intelligent about detecting the
8023 name-mangling scheme of the Fortran compiler, there may be Fortran
8024 compilers that it doesn't support yet.  In this case, the above code
8025 generates a compile-time error, but some other behavior
8026 (e.g., disabling Fortran-related features) can be induced by checking
8027 whether @code{F77_FUNC} or @code{FC_FUNC} is defined.
8029 Now, to call that routine from a C program, we would do something like:
8031 @example
8032 @c If you change this example, adjust tests/fortran.at:AC_F77_DUMMY_MAIN usage.
8034     double x = 2.7183, y;
8035     FOOBAR_F77 (&x, &y);
8037 @end example
8039 If the Fortran identifier contains an underscore (e.g., @code{foo_bar}),
8040 you should use @code{F77_FUNC_} or @code{FC_FUNC_} instead of
8041 @code{F77_FUNC} or @code{FC_FUNC} (with the same arguments).  This is
8042 because some Fortran compilers mangle names differently if they contain
8043 an underscore.
8044 @end defmac
8046 @defmac AC_F77_FUNC (@var{name}, @ovar{shellvar})
8047 @defmacx AC_FC_FUNC (@var{name}, @ovar{shellvar})
8048 @acindex{F77_FUNC}
8049 @acindex{FC_FUNC}
8050 Given an identifier @var{name}, set the shell variable @var{shellvar} to
8051 hold the mangled version @var{name} according to the rules of the
8052 Fortran linker (see also @code{AC_F77_WRAPPERS} or
8053 @code{AC_FC_WRAPPERS}).  @var{shellvar} is optional; if it is not
8054 supplied, the shell variable is simply @var{name}.  The purpose of
8055 this macro is to give the caller a way to access the name-mangling
8056 information other than through the C preprocessor as above, for example,
8057 to call Fortran routines from some language other than C/C++.
8058 @end defmac
8060 @defmac AC_FC_SRCEXT (@var{ext}, @ovar{action-if-success}, @
8061   @ovar{action-if-failure})
8062 @acindex{FC_SRCEXT}
8063 By default, the @code{FC} macros perform their tests using a @file{.f}
8064 extension for source-code files.  Some compilers, however, only enable
8065 newer language features for appropriately named files, e.g., Fortran 90
8066 features only for @file{.f90} files.  On the other hand, some other
8067 compilers expect all source files to end in @file{.f} and require
8068 special flags to support other file name extensions.  The
8069 @code{AC_FC_SRCEXT} macro deals with both of these issues.
8071 The @code{AC_FC_SRCEXT} tries to get the @code{FC} compiler to accept files
8072 ending with the extension .@var{ext} (i.e., @var{ext} does @emph{not}
8073 contain the dot).  If any special compiler flags are needed for this, it
8074 stores them in the output variable @code{FCFLAGS_}@var{ext}.  This
8075 extension and these flags are then used for all subsequent @code{FC} tests
8076 (until @code{AC_FC_SRCEXT} is called again).
8078 For example, you would use @code{AC_FC_SRCEXT(f90)} to employ the
8079 @file{.f90} extension in future tests, and it would set the
8080 @code{FCFLAGS_f90} output variable with any extra flags that are needed
8081 to compile such files.
8083 The @code{FCFLAGS_}@var{ext} can @emph{not} be simply absorbed into
8084 @code{FCFLAGS}, for two reasons based on the limitations of some
8085 compilers.  First, only one @code{FCFLAGS_}@var{ext} can be used at a
8086 time, so files with different extensions must be compiled separately.
8087 Second, @code{FCFLAGS_}@var{ext} must appear @emph{immediately} before
8088 the source-code file name when compiling.  So, continuing the example
8089 above, you might compile a @file{foo.f90} file in your makefile with the
8090 command:
8092 @example
8093 foo.o: foo.f90
8094      $(FC) -c $(FCFLAGS) $(FCFLAGS_f90) '$(srcdir)/foo.f90'
8095 @end example
8097 If @code{AC_FC_SRCEXT} succeeds in compiling files with the @var{ext}
8098 extension, it calls @var{action-if-success} (defaults to nothing).  If
8099 it fails, and cannot find a way to make the @code{FC} compiler accept such
8100 files, it calls @var{action-if-failure} (defaults to exiting with an
8101 error message).
8103 @end defmac
8105 @defmac AC_FC_FREEFORM (@ovar{action-if-success}, @ovar{action-if-failure})
8106 @acindex{FC_FREEFORM}
8108 The @code{AC_FC_FREEFORM} tries to ensure that the Fortran compiler
8109 (@code{$FC}) allows free-format source code (as opposed to the older
8110 fixed-format style from Fortran 77).  If necessary, it may add some
8111 additional flags to @code{FCFLAGS}.
8113 This macro is most important if you are using the default @file{.f}
8114 extension, since many compilers interpret this extension as indicating
8115 fixed-format source unless an additional flag is supplied.  If you
8116 specify a different extension with @code{AC_FC_SRCEXT}, such as
8117 @file{.f90}, then @code{AC_FC_FREEFORM} ordinarily succeeds without
8118 modifying @code{FCFLAGS}.  For extensions which the compiler does not
8119 know about, the flag set by the @code{AC_FC_SRCEXT} macro might let
8120 the compiler assume Fortran 77 by default, however.
8122 If @code{AC_FC_FREEFORM} succeeds in compiling free-form source, it
8123 calls @var{action-if-success} (defaults to nothing).  If it fails, it
8124 calls @var{action-if-failure} (defaults to exiting with an error
8125 message).
8126 @end defmac
8128 @defmac AC_FC_FIXEDFORM (@ovar{action-if-success}, @ovar{action-if-failure})
8129 @acindex{FC_FIXEDFORM}
8131 The @code{AC_FC_FIXEDFORM} tries to ensure that the Fortran compiler
8132 (@code{$FC}) allows the old fixed-format source code (as opposed to
8133 free-format style).  If necessary, it may add some additional flags to
8134 @code{FCFLAGS}.
8136 This macro is needed for some compilers alias names like @command{xlf95}
8137 which assume free-form source code by default, and in case you want to
8138 use fixed-form source with an extension like @file{.f90} which many
8139 compilers interpret as free-form by default.  If you specify a different
8140 extension with @code{AC_FC_SRCEXT}, such as @file{.f}, then
8141 @code{AC_FC_FIXEDFORM} ordinarily succeeds without modifying
8142 @code{FCFLAGS}.
8144 If @code{AC_FC_FIXEDFORM} succeeds in compiling fixed-form source, it
8145 calls @var{action-if-success} (defaults to nothing).  If it fails, it
8146 calls @var{action-if-failure} (defaults to exiting with an error
8147 message).
8148 @end defmac
8150 @defmac AC_FC_LINE_LENGTH (@ovar{length}, @ovar{action-if-success}, @
8151   @ovar{action-if-failure})
8152 @acindex{FC_LINE_LENGTH}
8154 The @code{AC_FC_LINE_LENGTH} macro tries to ensure that the Fortran compiler
8155 (@code{$FC}) accepts long source code lines.  The @var{length} argument
8156 may be given as 80, 132, or unlimited, and defaults to 132.  Note that
8157 line lengths above 254 columns are not portable, and some compilers
8158 do not accept more than 132 columns at least for fixed format source.
8159 If necessary, it may add some additional flags to @code{FCFLAGS}.
8161 If @code{AC_FC_LINE_LENGTH} succeeds in compiling fixed-form source, it
8162 calls @var{action-if-success} (defaults to nothing).  If it fails, it
8163 calls @var{action-if-failure} (defaults to exiting with an error
8164 message).
8165 @end defmac
8168 @node System Services
8169 @section System Services
8171 The following macros check for operating system services or capabilities.
8173 @anchor{AC_PATH_X}
8174 @defmac AC_PATH_X
8175 @acindex{PATH_X}
8176 @evindex XMKMF
8177 @cindex X Window System
8178 Try to locate the X Window System include files and libraries.  If the
8179 user gave the command line options @option{--x-includes=@var{dir}} and
8180 @option{--x-libraries=@var{dir}}, use those directories.
8182 If either or both were not given, get the missing values by running
8183 @code{xmkmf} (or an executable pointed to by the @code{XMKMF}
8184 environment variable) on a trivial @file{Imakefile} and examining the
8185 makefile that it produces.  Setting @code{XMKMF} to @samp{false}
8186 disables this method.
8188 If this method fails to find the X Window System, @command{configure}
8189 looks for the files in several directories where they often reside.
8190 If either method is successful, set the shell variables
8191 @code{x_includes} and @code{x_libraries} to their locations, unless they
8192 are in directories the compiler searches by default.
8194 If both methods fail, or the user gave the command line option
8195 @option{--without-x}, set the shell variable @code{no_x} to @samp{yes};
8196 otherwise set it to the empty string.
8197 @end defmac
8199 @anchor{AC_PATH_XTRA}
8200 @defmac AC_PATH_XTRA
8201 @acindex{PATH_XTRA}
8202 @ovindex X_CFLAGS
8203 @ovindex X_LIBS
8204 @ovindex X_EXTRA_LIBS
8205 @ovindex X_PRE_LIBS
8206 @cvindex X_DISPLAY_MISSING
8207 An enhanced version of @code{AC_PATH_X}.  It adds the C compiler flags
8208 that X needs to output variable @code{X_CFLAGS}, and the X linker flags
8209 to @code{X_LIBS}.  Define @code{X_DISPLAY_MISSING} if X is not
8210 available.
8212 This macro also checks for special libraries that some systems need in
8213 order to compile X programs.  It adds any that the system needs to
8214 output variable @code{X_EXTRA_LIBS}.  And it checks for special X11R6
8215 libraries that need to be linked with before @option{-lX11}, and adds
8216 any found to the output variable @code{X_PRE_LIBS}.
8218 @c This is an incomplete kludge.  Make a real way to do it.
8219 @c If you need to check for other X functions or libraries yourself, then
8220 @c after calling this macro, add the contents of @code{X_EXTRA_LIBS} to
8221 @c @code{LIBS} temporarily, like this: (FIXME - add example)
8222 @end defmac
8224 @anchor{AC_SYS_INTERPRETER}
8225 @defmac AC_SYS_INTERPRETER
8226 @acindex{SYS_INTERPRETER}
8227 Check whether the system supports starting scripts with a line of the
8228 form @samp{#!/bin/sh} to select the interpreter to use for the script.
8229 After running this macro, shell code in @file{configure.ac} can check
8230 the shell variable @code{interpval}; it is set to @samp{yes}
8231 if the system supports @samp{#!}, @samp{no} if not.
8232 @end defmac
8234 @defmac AC_SYS_LARGEFILE
8235 @acindex{SYS_LARGEFILE}
8236 @cvindex _FILE_OFFSET_BITS
8237 @cvindex _LARGE_FILES
8238 @ovindex CC
8239 @cindex Large file support
8240 @cindex LFS
8241 Arrange for 64-bit file offsets, known as
8242 @uref{http://@/www.unix-systems@/.org/@/version2/@/whatsnew/@/lfs20mar.html,
8243 large-file support}.  On some hosts, one must use special compiler
8244 options to build programs that can access large files.  Append any such
8245 options to the output variable @code{CC}.  Define
8246 @code{_FILE_OFFSET_BITS} and @code{_LARGE_FILES} if necessary.
8248 Large-file support can be disabled by configuring with the
8249 @option{--disable-largefile} option.
8251 If you use this macro, check that your program works even when
8252 @code{off_t} is wider than @code{long int}, since this is common when
8253 large-file support is enabled.  For example, it is not correct to print
8254 an arbitrary @code{off_t} value @code{X} with @code{printf ("%ld",
8255 (long int) X)}.
8257 The LFS introduced the @code{fseeko} and @code{ftello} functions to
8258 replace their C counterparts @code{fseek} and @code{ftell} that do not
8259 use @code{off_t}.  Take care to use @code{AC_FUNC_FSEEKO} to make their
8260 prototypes available when using them and large-file support is
8261 enabled.
8262 @end defmac
8264 @anchor{AC_SYS_LONG_FILE_NAMES}
8265 @defmac AC_SYS_LONG_FILE_NAMES
8266 @acindex{SYS_LONG_FILE_NAMES}
8267 @cvindex HAVE_LONG_FILE_NAMES
8268 If the system supports file names longer than 14 characters, define
8269 @code{HAVE_LONG_FILE_NAMES}.
8270 @end defmac
8272 @defmac AC_SYS_POSIX_TERMIOS
8273 @acindex{SYS_POSIX_TERMIOS}
8274 @cindex Posix termios headers
8275 @cindex termios Posix headers
8276 @caindex sys_posix_termios
8277 Check to see if the Posix termios headers and functions are available on the
8278 system.  If so, set the shell variable @code{ac_cv_sys_posix_termios} to
8279 @samp{yes}.  If not, set the variable to @samp{no}.
8280 @end defmac
8282 @node Posix Variants
8283 @section Posix Variants
8285 The following macro makes it possible to use features of Posix that are
8286 extensions to C, as well as platform extensions not defined by Posix.
8288 @anchor{AC_USE_SYSTEM_EXTENSIONS}
8289 @defmac AC_USE_SYSTEM_EXTENSIONS
8290 @acindex{USE_SYSTEM_EXTENSIONS}
8291 @cvindex _ALL_SOURCE
8292 @cvindex _GNU_SOURCE
8293 @cvindex _MINIX
8294 @cvindex _POSIX_1_SOURCE
8295 @cvindex _POSIX_PTHREAD_SEMANTICS
8296 @cvindex _POSIX_SOURCE
8297 @cvindex _TANDEM_SOURCE
8298 @cvindex __EXTENSIONS__
8299 This macro was introduced in Autoconf 2.60.  If possible, enable
8300 extensions to C or Posix on hosts that normally disable the extensions,
8301 typically due to standards-conformance namespace issues.  This should be
8302 called before any macros that run the C compiler.  The following
8303 preprocessor macros are defined where appropriate:
8305 @table @code
8306 @item _GNU_SOURCE
8307 Enable extensions on GNU/Linux.
8308 @item __EXTENSIONS__
8309 Enable general extensions on Solaris.
8310 @item _POSIX_PTHREAD_SEMANTICS
8311 Enable threading extensions on Solaris.
8312 @item _TANDEM_SOURCE
8313 Enable extensions for the HP NonStop platform.
8314 @item _ALL_SOURCE
8315 Enable extensions for AIX 3, and for Interix.
8316 @item _POSIX_SOURCE
8317 Enable Posix functions for Minix.
8318 @item _POSIX_1_SOURCE
8319 Enable additional Posix functions for Minix.
8320 @item _MINIX
8321 Identify Minix platform.  This particular preprocessor macro is
8322 obsolescent, and may be removed in a future release of Autoconf.
8323 @end table
8324 @end defmac
8327 @node Erlang Libraries
8328 @section Erlang Libraries
8329 @cindex Erlang, Library, checking
8331 The following macros check for an installation of Erlang/OTP, and for the
8332 presence of certain Erlang libraries.  All those macros require the
8333 configuration of an Erlang interpreter and an Erlang compiler
8334 (@pxref{Erlang Compiler and Interpreter}).
8336 @defmac AC_ERLANG_SUBST_ERTS_VER
8337 @acindex{ERLANG_SUBST_ERTS_VER}
8338 @ovindex ERLANG_ERTS_VER
8339 Set the output variable @code{ERLANG_ERTS_VER} to the version of the
8340 Erlang runtime system (as returned by Erlang's
8341 @code{erlang:system_info(version)} function).  The result of this test
8342 is cached if caching is enabled when running @command{configure}.  The
8343 @code{ERLANG_ERTS_VER} variable is not intended to be used for testing
8344 for features of specific ERTS versions, but to be used for substituting
8345 the ERTS version in Erlang/OTP release resource files (@code{.rel}
8346 files), as shown below.
8347 @end defmac
8349 @defmac AC_ERLANG_SUBST_ROOT_DIR
8350 @acindex{ERLANG_SUBST_ROOT_DIR}
8351 @ovindex ERLANG_ROOT_DIR
8352 Set the output variable @code{ERLANG_ROOT_DIR} to the path to the base
8353 directory in which Erlang/OTP is installed (as returned by Erlang's
8354 @code{code:root_dir/0} function).  The result of this test is cached if
8355 caching is enabled when running @command{configure}.
8356 @end defmac
8358 @defmac AC_ERLANG_SUBST_LIB_DIR
8359 @acindex{ERLANG_SUBST_LIB_DIR}
8360 @ovindex ERLANG_LIB_DIR
8361 Set the output variable @code{ERLANG_LIB_DIR} to the path of the library
8362 directory of Erlang/OTP (as returned by Erlang's
8363 @code{code:lib_dir/0} function), which subdirectories each contain an installed
8364 Erlang/OTP library.  The result of this test is cached if caching is enabled
8365 when running @command{configure}.
8366 @end defmac
8368 @defmac AC_ERLANG_CHECK_LIB (@var{library}, @ovar{action-if-found}, @
8369   @ovar{action-if-not-found})
8370 @acindex{ERLANG_CHECK_LIB}
8371 @ovindex ERLANG_LIB_DIR_@var{library}
8372 @ovindex ERLANG_LIB_VER_@var{library}
8373 Test whether the Erlang/OTP library @var{library} is installed by
8374 calling Erlang's @code{code:lib_dir/1} function.  The result of this
8375 test is cached if caching is enabled when running @command{configure}.
8376 @var{action-if-found} is a list of shell commands to run if the library
8377 is installed; @var{action-if-not-found} is a list of shell commands to
8378 run if it is not.  Additionally, if the library is installed, the output
8379 variable @samp{ERLANG_LIB_DIR_@var{library}} is set to the path to the
8380 library installation directory, and the output variable
8381 @samp{ERLANG_LIB_VER_@var{library}} is set to the version number that is
8382 part of the subdirectory name, if it is in the standard form
8383 (@code{@var{library}-@var{version}}).  If the directory name does not
8384 have a version part, @samp{ERLANG_LIB_VER_@var{library}} is set to the
8385 empty string.  If the library is not installed,
8386 @samp{ERLANG_LIB_DIR_@var{library}} and
8387 @samp{ERLANG_LIB_VER_@var{library}} are set to @code{"not found"}.  For
8388 example, to check if library @code{stdlib} is installed:
8390 @example
8391 AC_ERLANG_CHECK_LIB([stdlib],
8392   [echo "stdlib version \"$ERLANG_LIB_VER_stdlib\""
8393    echo "is installed in \"$ERLANG_LIB_DIR_stdlib\""],
8394   [AC_MSG_ERROR([stdlib was not found!])])
8395 @end example
8397 The @samp{ERLANG_LIB_VER_@var{library}} variables (set by
8398 @code{AC_ERLANG_CHECK_LIB}) and the @code{ERLANG_ERTS_VER} variable (set
8399 by @code{AC_ERLANG_SUBST_ERTS_VER}) are not intended to be used for
8400 testing for features of specific versions of libraries or of the Erlang
8401 runtime system.  Those variables are intended to be substituted in
8402 Erlang release resource files (@code{.rel} files).  For instance, to
8403 generate a @file{example.rel} file for an application depending on the
8404 @code{stdlib} library, @file{configure.ac} could contain:
8406 @example
8407 AC_ERLANG_SUBST_ERTS_VER
8408 AC_ERLANG_CHECK_LIB([stdlib],
8409   [],
8410   [AC_MSG_ERROR([stdlib was not found!])])
8411 AC_CONFIG_FILES([example.rel])
8412 @end example
8414 @noindent
8415 The @file{example.rel.in} file used to generate @file{example.rel}
8416 should contain:
8418 @example
8419 @{release,
8420     @{"@@PACKAGE@@", "@@VERSION@@"@},
8421     @{erts, "@@ERLANG_ERTS_VER@@"@},
8422     [@{stdlib, "@@ERLANG_LIB_VER_stdlib@@"@},
8423      @{@@PACKAGE@@, "@@VERSION@@"@}]@}.
8424 @end example
8425 @end defmac
8427 In addition to the above macros, which test installed Erlang libraries, the
8428 following macros determine the paths to the directories into which newly built
8429 Erlang libraries are to be installed:
8431 @defmac AC_ERLANG_SUBST_INSTALL_LIB_DIR
8432 @acindex{ERLANG_SUBST_INSTALL_LIB_DIR}
8433 @ovindex ERLANG_INSTALL_LIB_DIR
8435 Set the @code{ERLANG_INSTALL_LIB_DIR} output variable to the directory into
8436 which every built Erlang library should be installed in a separate
8437 subdirectory.
8438 If this variable is not set in the environment when @command{configure} runs,
8439 its default value is @code{$@{libdir@}/erlang/lib}.
8440 @end defmac
8442 @defmac AC_ERLANG_SUBST_INSTALL_LIB_SUBDIR (@var{library}, @var{version})
8443 @acindex{ERLANG_SUBST_INSTALL_LIB_SUBDIR}
8444 @ovindex ERLANG_INSTALL_LIB_DIR_@var{library}
8446 Set the @samp{ERLANG_INSTALL_LIB_DIR_@var{library}} output variable to the
8447 directory into which the built Erlang library @var{library} version
8448 @var{version} should be installed.  If this variable is not set in the
8449 environment when @command{configure} runs, its default value is
8450 @samp{$ERLANG_INSTALL_LIB_DIR/@var{library}-@var{version}}, the value of the
8451 @code{ERLANG_INSTALL_LIB_DIR} variable being set by the
8452 @code{AC_ERLANG_SUBST_INSTALL_LIB_DIR} macro.
8453 @end defmac
8459 @c ========================================================= Writing Tests
8461 @node Writing Tests
8462 @chapter Writing Tests
8464 If the existing feature tests don't do something you need, you have to
8465 write new ones.  These macros are the building blocks.  They provide
8466 ways for other macros to check whether various kinds of features are
8467 available and report the results.
8469 This chapter contains some suggestions and some of the reasons why the
8470 existing tests are written the way they are.  You can also learn a lot
8471 about how to write Autoconf tests by looking at the existing ones.  If
8472 something goes wrong in one or more of the Autoconf tests, this
8473 information can help you understand the assumptions behind them, which
8474 might help you figure out how to best solve the problem.
8476 These macros check the output of the compiler system of the current
8477 language (@pxref{Language Choice}).  They do not cache the results of
8478 their tests for future use (@pxref{Caching Results}), because they don't
8479 know enough about the information they are checking for to generate a
8480 cache variable name.  They also do not print any messages, for the same
8481 reason.  The checks for particular kinds of features call these macros
8482 and do cache their results and print messages about what they're
8483 checking for.
8485 When you write a feature test that could be applicable to more than one
8486 software package, the best thing to do is encapsulate it in a new macro.
8487 @xref{Writing Autoconf Macros}, for how to do that.
8489 @menu
8490 * Language Choice::             Selecting which language to use for testing
8491 * Writing Test Programs::       Forging source files for compilers
8492 * Running the Preprocessor::    Detecting preprocessor symbols
8493 * Running the Compiler::        Detecting language or header features
8494 * Running the Linker::          Detecting library features
8495 * Runtime::                     Testing for runtime features
8496 * Systemology::                 A zoology of operating systems
8497 * Multiple Cases::              Tests for several possible values
8498 @end menu
8500 @node Language Choice
8501 @section Language Choice
8502 @cindex Language
8504 Autoconf-generated @command{configure} scripts check for the C compiler and
8505 its features by default.  Packages that use other programming languages
8506 (maybe more than one, e.g., C and C++) need to test features of the
8507 compilers for the respective languages.  The following macros determine
8508 which programming language is used in the subsequent tests in
8509 @file{configure.ac}.
8511 @anchor{AC_LANG}
8512 @defmac AC_LANG (@var{language})
8513 @acindex{LANG}
8514 Do compilation tests using the compiler, preprocessor, and file
8515 extensions for the specified @var{language}.
8517 Supported languages are:
8519 @table @samp
8520 @item C
8521 Do compilation tests using @code{CC} and @code{CPP} and use extension
8522 @file{.c} for test programs.  Use compilation flags: @code{CPPFLAGS} with
8523 @code{CPP}, and both @code{CPPFLAGS} and @code{CFLAGS} with @code{CC}.
8525 @item C++
8526 Do compilation tests using @code{CXX} and @code{CXXCPP} and use
8527 extension @file{.C} for test programs.  Use compilation flags:
8528 @code{CPPFLAGS} with @code{CXXCPP}, and both @code{CPPFLAGS} and
8529 @code{CXXFLAGS} with @code{CXX}.
8531 @item Fortran 77
8532 Do compilation tests using @code{F77} and use extension @file{.f} for
8533 test programs.  Use compilation flags: @code{FFLAGS}.
8535 @item Fortran
8536 Do compilation tests using @code{FC} and use extension @file{.f} (or
8537 whatever has been set by @code{AC_FC_SRCEXT}) for test programs.  Use
8538 compilation flags: @code{FCFLAGS}.
8540 @item Erlang
8541 @ovindex ERLC
8542 @ovindex ERL
8543 @ovindex ERLCFLAGS
8544 Compile and execute tests using @code{ERLC} and @code{ERL} and use extension
8545 @file{.erl} for test Erlang modules.  Use compilation flags: @code{ERLCFLAGS}.
8547 @item Objective C
8548 Do compilation tests using @code{OBJC} and @code{OBJCPP} and use
8549 extension @file{.m} for test programs.  Use compilation flags:
8550 @code{CPPFLAGS} with @code{OBJCPP}, and both @code{CPPFLAGS} and
8551 @code{OBJCFLAGS} with @code{OBJC}.
8553 @item Objective C++
8554 Do compilation tests using @code{OBJCXX} and @code{OBJCXXCPP} and use
8555 extension @file{.mm} for test programs.  Use compilation flags:
8556 @code{CPPFLAGS} with @code{OBJCXXCPP}, and both @code{CPPFLAGS} and
8557 @code{OBJCXXFLAGS} with @code{OBJCXX}.
8558 @end table
8559 @end defmac
8561 @anchor{AC_LANG_PUSH}
8562 @defmac AC_LANG_PUSH (@var{language})
8563 @acindex{LANG_PUSH}
8564 Remember the current language (as set by @code{AC_LANG}) on a stack, and
8565 then select the @var{language}.  Use this macro and @code{AC_LANG_POP}
8566 in macros that need to temporarily switch to a particular language.
8567 @end defmac
8569 @defmac AC_LANG_POP (@ovar{language})
8570 @acindex{LANG_POP}
8571 Select the language that is saved on the top of the stack, as set by
8572 @code{AC_LANG_PUSH}, and remove it from the stack.
8574 If given, @var{language} specifies the language we just @emph{quit}.  It
8575 is a good idea to specify it when it's known (which should be the
8576 case@dots{}), since Autoconf detects inconsistencies.
8578 @example
8579 AC_LANG_PUSH([Fortran 77])
8580 # Perform some tests on Fortran 77.
8581 # @dots{}
8582 AC_LANG_POP([Fortran 77])
8583 @end example
8584 @end defmac
8586 @defmac AC_LANG_ASSERT (@var{language})
8587 @acindex{LANG_ASSERT}
8588 Check statically that the current language is @var{language}.
8589 You should use this in your language specific macros
8590 to avoid that they be called with an inappropriate language.
8592 This macro runs only at @command{autoconf} time, and incurs no cost at
8593 @command{configure} time.  Sadly enough and because Autoconf is a two
8594 layer language @footnote{Because M4 is not aware of Sh code,
8595 especially conditionals, some optimizations that look nice statically
8596 may produce incorrect results at runtime.}, the macros
8597 @code{AC_LANG_PUSH} and @code{AC_LANG_POP} cannot be ``optimizing'',
8598 therefore as much as possible you ought to avoid using them to wrap
8599 your code, rather, require from the user to run the macro with a
8600 correct current language, and check it with @code{AC_LANG_ASSERT}.
8601 And anyway, that may help the user understand she is running a Fortran
8602 macro while expecting a result about her Fortran 77 compiler@enddots{}
8603 @end defmac
8606 @defmac AC_REQUIRE_CPP
8607 @acindex{REQUIRE_CPP}
8608 Ensure that whichever preprocessor would currently be used for tests has
8609 been found.  Calls @code{AC_REQUIRE} (@pxref{Prerequisite Macros}) with an
8610 argument of either @code{AC_PROG_CPP} or @code{AC_PROG_CXXCPP},
8611 depending on which language is current.
8612 @end defmac
8615 @node Writing Test Programs
8616 @section Writing Test Programs
8618 Autoconf tests follow a common scheme: feed some program with some
8619 input, and most of the time, feed a compiler with some source file.
8620 This section is dedicated to these source samples.
8622 @menu
8623 * Guidelines::                  General rules for writing test programs
8624 * Test Functions::              Avoiding pitfalls in test programs
8625 * Generating Sources::          Source program boilerplate
8626 @end menu
8628 @node Guidelines
8629 @subsection Guidelines for Test Programs
8631 The most important rule to follow when writing testing samples is:
8633 @center @emph{Look for realism.}
8635 This motto means that testing samples must be written with the same
8636 strictness as real programs are written.  In particular, you should
8637 avoid ``shortcuts'' and simplifications.
8639 Don't just play with the preprocessor if you want to prepare a
8640 compilation.  For instance, using @command{cpp} to check whether a header is
8641 functional might let your @command{configure} accept a header which
8642 causes some @emph{compiler} error.  Do not hesitate to check a header with
8643 other headers included before, especially required headers.
8645 Make sure the symbols you use are properly defined, i.e., refrain from
8646 simply declaring a function yourself instead of including the proper
8647 header.
8649 Test programs should not write to standard output.  They
8650 should exit with status 0 if the test succeeds, and with status 1
8651 otherwise, so that success
8652 can be distinguished easily from a core dump or other failure;
8653 segmentation violations and other failures produce a nonzero exit
8654 status.  Unless you arrange for @code{exit} to be declared, test
8655 programs should @code{return}, not @code{exit}, from @code{main},
8656 because on many systems @code{exit} is not declared by default.
8658 Test programs can use @code{#if} or @code{#ifdef} to check the values of
8659 preprocessor macros defined by tests that have already run.  For
8660 example, if you call @code{AC_HEADER_STDBOOL}, then later on in
8661 @file{configure.ac} you can have a test program that includes
8662 @file{stdbool.h} conditionally:
8664 @example
8665 @group
8666 #ifdef HAVE_STDBOOL_H
8667 # include <stdbool.h>
8668 #endif
8669 @end group
8670 @end example
8672 Both @code{#if HAVE_STDBOOL_H} and @code{#ifdef HAVE_STDBOOL_H} will
8673 work with any standard C compiler.  Some developers prefer @code{#if}
8674 because it is easier to read, while others prefer @code{#ifdef} because
8675 it avoids diagnostics with picky compilers like GCC with the
8676 @option{-Wundef} option.
8678 If a test program needs to use or create a data file, give it a name
8679 that starts with @file{conftest}, such as @file{conftest.data}.  The
8680 @command{configure} script cleans up by running @samp{rm -f -r conftest*}
8681 after running test programs and if the script is interrupted.
8683 @node Test Functions
8684 @subsection Test Functions
8686 These days it's safe to assume support for function prototypes
8687 (introduced in C89).
8689 Functions that test programs declare should also be conditionalized for
8690 C++, which requires @samp{extern "C"} prototypes.  Make sure to not
8691 include any header files containing clashing prototypes.
8693 @example
8694 #ifdef __cplusplus
8695 extern "C"
8696 #endif
8697 void *valloc (size_t);
8698 @end example
8700 If a test program calls a function with invalid parameters (just to see
8701 whether it exists), organize the program to ensure that it never invokes
8702 that function.  You can do this by calling it in another function that is
8703 never invoked.  You can't do it by putting it after a call to
8704 @code{exit}, because GCC version 2 knows that @code{exit}
8705 never returns
8706 and optimizes out any code that follows it in the same block.
8708 If you include any header files, be sure to call the functions
8709 relevant to them with the correct number of arguments, even if they are
8710 just 0, to avoid compilation errors due to prototypes.  GCC
8711 version 2
8712 has internal prototypes for several functions that it automatically
8713 inlines; for example, @code{memcpy}.  To avoid errors when checking for
8714 them, either pass them the correct number of arguments or redeclare them
8715 with a different return type (such as @code{char}).
8718 @node Generating Sources
8719 @subsection Generating Sources
8721 Autoconf provides a set of macros that can be used to generate test
8722 source files.  They are written to be language generic, i.e., they
8723 actually depend on the current language (@pxref{Language Choice}) to
8724 ``format'' the output properly.
8727 @defmac AC_LANG_CONFTEST (@var{source})
8728 @acindex{LANG_CONFTEST}
8729 Save the @var{source} text in the current test source file:
8730 @file{conftest.@var{extension}} where the @var{extension} depends on the
8731 current language.  As of Autoconf 2.63b, the source file also contains
8732 the results of all of the @code{AC_DEFINE} performed so far.
8734 Note that the @var{source} is evaluated exactly once, like regular
8735 Autoconf macro arguments, and therefore (i) you may pass a macro
8736 invocation, (ii) if not, be sure to double quote if needed.
8738 This macro issues a warning during @command{autoconf} processing if
8739 @var{source} does not include an expansion of the macro
8740 @code{AC_LANG_DEFINES_PROVIDED} (note that both @code{AC_LANG_SOURCE} and
8741 @code{AC_LANG_PROGRAM} call this macro, and thus avoid the warning).
8743 This macro is seldom called directly, but is used under the hood by more
8744 common macros such as @code{AC_COMPILE_IFELSE} and @code{AC_RUN_IFELSE}.
8745 @end defmac
8747 @defmac AC_LANG_DEFINES_PROVIDED
8748 @acindex{LANG_DEFINES_PROVIDED}
8749 This macro is called as a witness that the file
8750 @file{conftest.@var{extension}} appropriate for the current language is
8751 complete, including all previously determined results from
8752 @code{AC_DEFINE}.  This macro is seldom called directly, but exists if
8753 you have a compelling reason to write a conftest file without using
8754 @code{AC_LANG_SOURCE}, yet still want to avoid a syntax warning from
8755 @code{AC_LANG_CONFTEST}.
8756 @end defmac
8758 @defmac AC_LANG_SOURCE (@var{source})
8759 @acindex{LANG_SOURCE}
8760 Expands into the @var{source}, with the definition of
8761 all the @code{AC_DEFINE} performed so far.  This macro includes an
8762 expansion of @code{AC_LANG_DEFINES_PROVIDED}.
8764 In many cases, you may find it more convenient to use the wrapper
8765 @code{AC_LANG_PROGRAM}.
8766 @end defmac
8768 For instance, executing (observe the double quotation!):
8770 @example
8771 @c If you change this example, adjust tests/compile.at:AC_LANG_SOURCE example.
8772 AC_INIT([Hello], [1.0], [bug-hello@@example.org], [],
8773         [http://www.example.org/])
8774 AC_DEFINE([HELLO_WORLD], ["Hello, World\n"],
8775   [Greetings string.])
8776 AC_LANG([C])
8777 AC_LANG_CONFTEST(
8778    [AC_LANG_SOURCE([[const char hw[] = "Hello, World\n";]])])
8779 gcc -E -dD conftest.c
8780 @end example
8782 @noindent
8783 on a system with @command{gcc} installed, results in:
8785 @example
8786 @c If you change this example, adjust tests/compile.at:AC_LANG_SOURCE example.
8787 @dots{}
8788 # 1 "conftest.c"
8790 #define PACKAGE_NAME "Hello"
8791 #define PACKAGE_TARNAME "hello"
8792 #define PACKAGE_VERSION "1.0"
8793 #define PACKAGE_STRING "Hello 1.0"
8794 #define PACKAGE_BUGREPORT "bug-hello@@example.org"
8795 #define PACKAGE_URL "http://www.example.org/"
8796 #define HELLO_WORLD "Hello, World\n"
8798 const char hw[] = "Hello, World\n";
8799 @end example
8801 When the test language is Fortran or Erlang, the @code{AC_DEFINE} definitions
8802 are not automatically translated into constants in the source code by this
8803 macro.
8805 @defmac AC_LANG_PROGRAM (@var{prologue}, @var{body})
8806 @acindex{LANG_PROGRAM}
8807 Expands into a source file which consists of the @var{prologue}, and
8808 then @var{body} as body of the main function (e.g., @code{main} in
8809 C).  Since it uses @code{AC_LANG_SOURCE}, the features of the latter are
8810 available.
8811 @end defmac
8813 For instance:
8815 @example
8816 @c If you change this example, adjust tests/compile.at:AC_LANG_PROGRAM example.
8817 AC_INIT([Hello], [1.0], [bug-hello@@example.org], [],
8818         [http://www.example.org/])
8819 AC_DEFINE([HELLO_WORLD], ["Hello, World\n"],
8820   [Greetings string.])
8821 AC_LANG_CONFTEST(
8822 [AC_LANG_PROGRAM([[const char hw[] = "Hello, World\n";]],
8823                  [[fputs (hw, stdout);]])])
8824 gcc -E -dD conftest.c
8825 @end example
8827 @noindent
8828 on a system with @command{gcc} installed, results in:
8830 @example
8831 @c If you change this example, adjust tests/compile.at:AC_LANG_PROGRAM example.
8832 @dots{}
8833 # 1 "conftest.c"
8835 #define PACKAGE_NAME "Hello"
8836 #define PACKAGE_TARNAME "hello"
8837 #define PACKAGE_VERSION "1.0"
8838 #define PACKAGE_STRING "Hello 1.0"
8839 #define PACKAGE_BUGREPORT "bug-hello@@example.org"
8840 #define PACKAGE_URL "http://www.example.org/"
8841 #define HELLO_WORLD "Hello, World\n"
8843 const char hw[] = "Hello, World\n";
8845 main ()
8847 fputs (hw, stdout);
8848   ;
8849   return 0;
8851 @end example
8853 In Erlang tests, the created source file is that of an Erlang module called
8854 @code{conftest} (@file{conftest.erl}).  This module defines and exports
8855 at least
8856 one @code{start/0} function, which is called to perform the test.  The
8857 @var{prologue} is optional code that is inserted between the module header and
8858 the @code{start/0} function definition.  @var{body} is the body of the
8859 @code{start/0} function without the final period (@pxref{Runtime}, about
8860 constraints on this function's behavior).
8862 For instance:
8864 @example
8865 AC_INIT([Hello], [1.0], [bug-hello@@example.org])
8866 AC_LANG(Erlang)
8867 AC_LANG_CONFTEST(
8868 [AC_LANG_PROGRAM([[-define(HELLO_WORLD, "Hello, world!").]],
8869                  [[io:format("~s~n", [?HELLO_WORLD])]])])
8870 cat conftest.erl
8871 @end example
8873 @noindent
8874 results in:
8876 @example
8877 -module(conftest).
8878 -export([start/0]).
8879 -define(HELLO_WORLD, "Hello, world!").
8880 start() ->
8881 io:format("~s~n", [?HELLO_WORLD])
8883 @end example
8885 @defmac AC_LANG_CALL (@var{prologue}, @var{function})
8886 @acindex{LANG_CALL}
8887 Expands into a source file which consists of the @var{prologue}, and
8888 then a call to the @var{function} as body of the main function (e.g.,
8889 @code{main} in C).  Since it uses @code{AC_LANG_PROGRAM}, the feature
8890 of the latter are available.
8892 This function will probably be replaced in the future by a version
8893 which would enable specifying the arguments.  The use of this macro is
8894 not encouraged, as it violates strongly the typing system.
8896 This macro cannot be used for Erlang tests.
8897 @end defmac
8899 @defmac AC_LANG_FUNC_LINK_TRY (@var{function})
8900 @acindex{LANG_FUNC_LINK_TRY}
8901 Expands into a source file which uses the @var{function} in the body of
8902 the main function (e.g., @code{main} in C).  Since it uses
8903 @code{AC_LANG_PROGRAM}, the features of the latter are available.
8905 As @code{AC_LANG_CALL}, this macro is documented only for completeness.
8906 It is considered to be severely broken, and in the future will be
8907 removed in favor of actual function calls (with properly typed
8908 arguments).
8910 This macro cannot be used for Erlang tests.
8911 @end defmac
8913 @node Running the Preprocessor
8914 @section Running the Preprocessor
8916 Sometimes one might need to run the preprocessor on some source file.
8917 @emph{Usually it is a bad idea}, as you typically need to @emph{compile}
8918 your project, not merely run the preprocessor on it; therefore you
8919 certainly want to run the compiler, not the preprocessor.  Resist the
8920 temptation of following the easiest path.
8922 Nevertheless, if you need to run the preprocessor, then use
8923 @code{AC_PREPROC_IFELSE}.
8925 The macros described in this section cannot be used for tests in Erlang or
8926 Fortran, since those languages require no preprocessor.
8928 @anchor{AC_PREPROC_IFELSE}
8929 @defmac AC_PREPROC_IFELSE (@var{input}, @ovar{action-if-true}, @
8930   @ovar{action-if-false})
8931 @acindex{PREPROC_IFELSE}
8932 Run the preprocessor of the current language (@pxref{Language Choice})
8933 on the @var{input}, run the shell commands @var{action-if-true} on
8934 success, @var{action-if-false} otherwise.  The @var{input} can be made
8935 by @code{AC_LANG_PROGRAM} and friends.
8937 This macro uses @code{CPPFLAGS}, but not @code{CFLAGS}, because
8938 @option{-g}, @option{-O}, etc.@: are not valid options to many C
8939 preprocessors.
8941 It is customary to report unexpected failures with
8942 @code{AC_MSG_FAILURE}.  If needed, @var{action-if-true} can further access
8943 the preprocessed output in the file @file{conftest.i}.
8944 @end defmac
8946 For instance:
8948 @example
8949 AC_INIT([Hello], [1.0], [bug-hello@@example.org])
8950 AC_DEFINE([HELLO_WORLD], ["Hello, World\n"],
8951   [Greetings string.])
8952 AC_PREPROC_IFELSE(
8953    [AC_LANG_PROGRAM([[const char hw[] = "Hello, World\n";]],
8954                     [[fputs (hw, stdout);]])],
8955    [AC_MSG_RESULT([OK])],
8956    [AC_MSG_FAILURE([unexpected preprocessor failure])])
8957 @end example
8959 @noindent
8960 results in:
8962 @example
8963 checking for gcc... gcc
8964 checking for C compiler default output file name... a.out
8965 checking whether the C compiler works... yes
8966 checking whether we are cross compiling... no
8967 checking for suffix of executables...
8968 checking for suffix of object files... o
8969 checking whether we are using the GNU C compiler... yes
8970 checking whether gcc accepts -g... yes
8971 checking for gcc option to accept ISO C89... none needed
8972 checking how to run the C preprocessor... gcc -E
8974 @end example
8976 @sp 1
8978 The macro @code{AC_TRY_CPP} (@pxref{Obsolete Macros}) used to play the
8979 role of @code{AC_PREPROC_IFELSE}, but double quotes its argument, making
8980 it impossible to use it to elaborate sources.  You are encouraged to
8981 get rid of your old use of the macro @code{AC_TRY_CPP} in favor of
8982 @code{AC_PREPROC_IFELSE}, but, in the first place, are you sure you need
8983 to run the @emph{preprocessor} and not the compiler?
8985 @anchor{AC_EGREP_HEADER}
8986 @defmac AC_EGREP_HEADER (@var{pattern}, @var{header-file}, @
8987   @var{action-if-found}, @ovar{action-if-not-found})
8988 @acindex{EGREP_HEADER}
8989 If the output of running the preprocessor on the system header file
8990 @var{header-file} matches the extended regular expression
8991 @var{pattern}, execute shell commands @var{action-if-found}, otherwise
8992 execute @var{action-if-not-found}.
8993 @end defmac
8995 @anchor{AC_EGREP_CPP}
8996 @defmac AC_EGREP_CPP (@var{pattern}, @var{program}, @
8997   @ovar{action-if-found}, @ovar{action-if-not-found})
8998 @acindex{EGREP_CPP}
8999 @var{program} is the text of a C or C++ program, on which shell
9000 variable, back quote, and backslash substitutions are performed.  If the
9001 output of running the preprocessor on @var{program} matches the
9002 extended regular expression @var{pattern}, execute shell commands
9003 @var{action-if-found}, otherwise execute @var{action-if-not-found}.
9004 @end defmac
9008 @node Running the Compiler
9009 @section Running the Compiler
9011 To check for a syntax feature of the current language's (@pxref{Language
9012 Choice}) compiler, such as whether it recognizes a certain keyword, or
9013 simply to try some library feature, use @code{AC_COMPILE_IFELSE} to try
9014 to compile a small program that uses that feature.
9016 @defmac AC_COMPILE_IFELSE (@var{input}, @ovar{action-if-true}, @
9017   @ovar{action-if-false})
9018 @acindex{COMPILE_IFELSE}
9019 Run the compiler and compilation flags of the current language
9020 (@pxref{Language Choice}) on the @var{input}, run the shell commands
9021 @var{action-if-true} on success, @var{action-if-false} otherwise.  The
9022 @var{input} can be made by @code{AC_LANG_PROGRAM} and friends.
9024 It is customary to report unexpected failures with
9025 @code{AC_MSG_FAILURE}.  This macro does not try to link; use
9026 @code{AC_LINK_IFELSE} if you need to do that (@pxref{Running the
9027 Linker}).  If needed, @var{action-if-true} can further access the
9028 just-compiled object file @file{conftest.$OBJEXT}.
9030 This macro uses @code{AC_REQUIRE} for the compiler associated with the
9031 current language, which means that if the compiler has not yet been
9032 determined, the compiler determination will be made prior to the body of
9033 the outermust @code{AC_DEFUN} macro that triggered this macro to
9034 expand (@pxref{Expanded Before Required}).
9035 @end defmac
9037 @ovindex ERL
9038 For tests in Erlang, the @var{input} must be the source code of a module named
9039 @code{conftest}.  @code{AC_COMPILE_IFELSE} generates a @file{conftest.beam}
9040 file that can be interpreted by the Erlang virtual machine (@code{ERL}).  It is
9041 recommended to use @code{AC_LANG_PROGRAM} to specify the test program,
9042 to ensure that the Erlang module has the right name.
9044 @node Running the Linker
9045 @section Running the Linker
9047 To check for a library, a function, or a global variable, Autoconf
9048 @command{configure} scripts try to compile and link a small program that
9049 uses it.  This is unlike Metaconfig, which by default uses @code{nm} or
9050 @code{ar} on the C library to try to figure out which functions are
9051 available.  Trying to link with the function is usually a more reliable
9052 approach because it avoids dealing with the variations in the options
9053 and output formats of @code{nm} and @code{ar} and in the location of the
9054 standard libraries.  It also allows configuring for cross-compilation or
9055 checking a function's runtime behavior if needed.  On the other hand,
9056 it can be slower than scanning the libraries once, but accuracy is more
9057 important than speed.
9059 @code{AC_LINK_IFELSE} is used to compile test programs to test for
9060 functions and global variables.  It is also used by @code{AC_CHECK_LIB}
9061 to check for libraries (@pxref{Libraries}), by adding the library being
9062 checked for to @code{LIBS} temporarily and trying to link a small
9063 program.
9065 @anchor{AC_LINK_IFELSE}
9066 @defmac AC_LINK_IFELSE (@var{input}, @ovar{action-if-true}, @
9067   @ovar{action-if-false})
9068 @acindex{LINK_IFELSE}
9069 Run the compiler (and compilation flags) and the linker of the current
9070 language (@pxref{Language Choice}) on the @var{input}, run the shell
9071 commands @var{action-if-true} on success, @var{action-if-false}
9072 otherwise.  The @var{input} can be made by @code{AC_LANG_PROGRAM} and
9073 friends.  If needed, @var{action-if-true} can further access the
9074 just-linked program file @file{conftest$EXEEXT}.
9076 @code{LDFLAGS} and @code{LIBS} are used for linking, in addition to the
9077 current compilation flags.
9079 It is customary to report unexpected failures with
9080 @code{AC_MSG_FAILURE}.  This macro does not try to execute the program;
9081 use @code{AC_RUN_IFELSE} if you need to do that (@pxref{Runtime}).
9082 @end defmac
9084 The @code{AC_LINK_IFELSE} macro cannot be used for Erlang tests, since Erlang
9085 programs are interpreted and do not require linking.
9089 @node Runtime
9090 @section Checking Runtime Behavior
9092 Sometimes you need to find out how a system performs at runtime, such
9093 as whether a given function has a certain capability or bug.  If you
9094 can, make such checks when your program runs instead of when it is
9095 configured.  You can check for things like the machine's endianness when
9096 your program initializes itself.
9098 If you really need to test for a runtime behavior while configuring,
9099 you can write a test program to determine the result, and compile and
9100 run it using @code{AC_RUN_IFELSE}.  Avoid running test programs if
9101 possible, because this prevents people from configuring your package for
9102 cross-compiling.
9104 @anchor{AC_RUN_IFELSE}
9105 @defmac AC_RUN_IFELSE (@var{input}, @ovar{action-if-true}, @
9106   @ovar{action-if-false}, @ovar{action-if-cross-compiling})
9107 @acindex{RUN_IFELSE}
9108 If @var{program} compiles and links successfully and returns an exit
9109 status of 0 when executed, run shell commands @var{action-if-true}.
9110 Otherwise, run shell commands @var{action-if-false}.
9112 The @var{input} can be made by @code{AC_LANG_PROGRAM} and friends.
9113 @code{LDFLAGS} and @code{LIBS} are used for linking, in addition to the
9114 compilation flags of the current language (@pxref{Language Choice}).
9115 Additionally, @var{action-if-true} can run @command{./conftest$EXEEXT}
9116 for further testing.
9118 If the compiler being used does not produce executables that run on the
9119 system where @command{configure} is being run, then the test program is
9120 not run.  If the optional shell commands @var{action-if-cross-compiling}
9121 are given, they are run instead.  Otherwise, @command{configure} prints
9122 an error message and exits.
9124 In the @var{action-if-false} section, the failing exit status is
9125 available in the shell variable @samp{$?}.  This exit status might be
9126 that of a failed compilation, or it might be that of a failed program
9127 execution.
9129 It is customary to report unexpected failures with
9130 @code{AC_MSG_FAILURE}.
9131 @end defmac
9133 Try to provide a pessimistic default value to use when cross-compiling
9134 makes runtime tests impossible.  You do this by passing the optional
9135 last argument to @code{AC_RUN_IFELSE}.  @command{autoconf} prints a
9136 warning message when creating @command{configure} each time it
9137 encounters a call to @code{AC_RUN_IFELSE} with no
9138 @var{action-if-cross-compiling} argument given.  You may ignore the
9139 warning, though users cannot configure your package for
9140 cross-compiling.  A few of the macros distributed with Autoconf produce
9141 this warning message.
9143 To configure for cross-compiling you can also choose a value for those
9144 parameters based on the canonical system name (@pxref{Manual
9145 Configuration}).  Alternatively, set up a test results cache file with
9146 the correct values for the host system (@pxref{Caching Results}).
9148 @ovindex cross_compiling
9149 To provide a default for calls of @code{AC_RUN_IFELSE} that are embedded
9150 in other macros, including a few of the ones that come with Autoconf,
9151 you can test whether the shell variable @code{cross_compiling} is set to
9152 @samp{yes}, and then use an alternate method to get the results instead
9153 of calling the macros.
9155 It is also permissible to temporarily assign to @code{cross_compiling}
9156 in order to force tests to behave as though they are in a
9157 cross-compilation environment, particularly since this provides a way to
9158 test your @var{action-if-cross-compiling} even when you are not using a
9159 cross-compiler.
9161 @example
9162 # We temporarily set cross-compile mode to force AC_COMPUTE_INT
9163 # to use the slow link-only method
9164 save_cross_compiling=$cross_compiling
9165 cross_compiling=yes
9166 AC_COMPUTE_INT([@dots{}])
9167 cross_compiling=$save_cross_compiling
9168 @end example
9170 A C or C++ runtime test should be portable.
9171 @xref{Portable C and C++}.
9173 Erlang tests must exit themselves the Erlang VM by calling the @code{halt/1}
9174 function: the given status code is used to determine the success of the test
9175 (status is @code{0}) or its failure (status is different than @code{0}), as
9176 explained above.  It must be noted that data output through the standard output
9177 (e.g., using @code{io:format/2}) may be truncated when halting the VM.
9178 Therefore, if a test must output configuration information, it is recommended
9179 to create and to output data into the temporary file named @file{conftest.out},
9180 using the functions of module @code{file}.  The @code{conftest.out} file is
9181 automatically deleted by the @code{AC_RUN_IFELSE} macro.  For instance, a
9182 simplified implementation of Autoconf's @code{AC_ERLANG_SUBST_LIB_DIR}
9183 macro is:
9185 @example
9186 AC_INIT([LibdirTest], [1.0], [bug-libdirtest@@example.org])
9187 AC_ERLANG_NEED_ERL
9188 AC_LANG(Erlang)
9189 AC_RUN_IFELSE(
9190   [AC_LANG_PROGRAM([], [dnl
9191     file:write_file("conftest.out", code:lib_dir()),
9192     halt(0)])],
9193   [echo "code:lib_dir() returned: `cat conftest.out`"],
9194   [AC_MSG_FAILURE([test Erlang program execution failed])])
9195 @end example
9198 @node Systemology
9199 @section Systemology
9200 @cindex Systemology
9202 This section aims at presenting some systems and pointers to
9203 documentation.  It may help you addressing particular problems reported
9204 by users.
9206 @uref{http://@/www.opengroup.org/@/susv3, Posix-conforming systems} are
9207 derived from the @uref{http://@/www.bell-labs.com/@/history/@/unix/, Unix
9208 operating system}.
9210 The @uref{http://@/bhami.com/@/rosetta.html, Rosetta Stone for Unix}
9211 contains a table correlating the features of various Posix-conforming
9212 systems.  @uref{http://@/www.levenez.com/@/unix/, Unix History} is a
9213 simplified diagram of how many Unix systems were derived from each
9214 other.
9216 @uref{http://@/heirloom.sourceforge.net/, The Heirloom Project}
9217 provides some variants of traditional implementations of Unix utilities.
9219 @table @asis
9220 @item Darwin
9221 @cindex Darwin
9222 Darwin is also known as Mac OS X@.  Beware that the file system @emph{can} be
9223 case-preserving, but case insensitive.  This can cause nasty problems,
9224 since for instance the installation attempt for a package having an
9225 @file{INSTALL} file can result in @samp{make install} report that
9226 nothing was to be done!
9228 That's all dependent on whether the file system is a UFS (case
9229 sensitive) or HFS+ (case preserving).  By default Apple wants you to
9230 install the OS on HFS+.  Unfortunately, there are some pieces of
9231 software which really need to be built on UFS@.  We may want to rebuild
9232 Darwin to have both UFS and HFS+ available (and put the /local/build
9233 tree on the UFS).
9235 @item QNX 4.25
9236 @cindex QNX 4.25
9237 @c FIXME: Please, if you feel like writing something more precise,
9238 @c it'd be great.  In particular, I can't understand the difference with
9239 @c QNX Neutrino.
9240 QNX is a realtime operating system running on Intel architecture
9241 meant to be scalable from the small embedded systems to the hundred
9242 processor super-computer.  It claims to be Posix certified.  More
9243 information is available on the
9244 @uref{http://@/www.qnx.com/, QNX home page}.
9246 @item Tru64
9247 @cindex Tru64
9248 @uref{http://@/h30097.www3.hp.com/@/docs/,
9249 Documentation of several versions of Tru64} is available in different
9250 formats.
9252 @item Unix version 7
9253 @cindex Unix version 7
9254 @cindex V7
9255 Officially this was called the ``Seventh Edition'' of ``the UNIX
9256 time-sharing system'' but we use the more-common name ``Unix version 7''.
9257 Documentation is available in the
9258 @uref{http://@/plan9.bell-labs.com/@/7thEdMan/, Unix Seventh Edition Manual}.
9259 Previous versions of Unix are called ``Unix version 6'', etc., but
9260 they were not as widely used.
9261 @end table
9264 @node Multiple Cases
9265 @section Multiple Cases
9267 Some operations are accomplished in several possible ways, depending on
9268 the OS variant.  Checking for them essentially requires a ``case
9269 statement''.  Autoconf does not directly provide one; however, it is
9270 easy to simulate by using a shell variable to keep track of whether a
9271 way to perform the operation has been found yet.
9273 Here is an example that uses the shell variable @code{fstype} to keep
9274 track of whether the remaining cases need to be checked.  Note that
9275 since the value of @code{fstype} is under our control, we don't have to
9276 use the longer @samp{test "x$fstype" = xno}.
9278 @example
9279 @group
9280 AC_MSG_CHECKING([how to get file system type])
9281 fstype=no
9282 # The order of these tests is important.
9283 AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <sys/statvfs.h>
9284 #include <sys/fstyp.h>]])],
9285                   [AC_DEFINE([FSTYPE_STATVFS], [1],
9286                      [Define if statvfs exists.])
9287                    fstype=SVR4])
9288 if test $fstype = no; then
9289   AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <sys/statfs.h>
9290 #include <sys/fstyp.h>]])],
9291                   [AC_DEFINE([FSTYPE_USG_STATFS], [1],
9292                      [Define if USG statfs.])
9293                    fstype=SVR3])
9295 if test $fstype = no; then
9296   AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <sys/statfs.h>
9297 #include <sys/vmount.h>]])]),
9298                   [AC_DEFINE([FSTYPE_AIX_STATFS], [1],
9299                      [Define if AIX statfs.])
9300                    fstype=AIX])
9302 # (more cases omitted here)
9303 AC_MSG_RESULT([$fstype])
9304 @end group
9305 @end example
9307 @c ====================================================== Results of Tests.
9309 @node Results
9310 @chapter Results of Tests
9312 Once @command{configure} has determined whether a feature exists, what can
9313 it do to record that information?  There are four sorts of things it can
9314 do: define a C preprocessor symbol, set a variable in the output files,
9315 save the result in a cache file for future @command{configure} runs, and
9316 print a message letting the user know the result of the test.
9318 @menu
9319 * Defining Symbols::            Defining C preprocessor symbols
9320 * Setting Output Variables::    Replacing variables in output files
9321 * Special Chars in Variables::  Characters to beware of in variables
9322 * Caching Results::             Speeding up subsequent @command{configure} runs
9323 * Printing Messages::           Notifying @command{configure} users
9324 @end menu
9326 @node Defining Symbols
9327 @section Defining C Preprocessor Symbols
9329 A common action to take in response to a feature test is to define a C
9330 preprocessor symbol indicating the results of the test.  That is done by
9331 calling @code{AC_DEFINE} or @code{AC_DEFINE_UNQUOTED}.
9333 By default, @code{AC_OUTPUT} places the symbols defined by these macros
9334 into the output variable @code{DEFS}, which contains an option
9335 @option{-D@var{symbol}=@var{value}} for each symbol defined.  Unlike in
9336 Autoconf version 1, there is no variable @code{DEFS} defined while
9337 @command{configure} is running.  To check whether Autoconf macros have
9338 already defined a certain C preprocessor symbol, test the value of the
9339 appropriate cache variable, as in this example:
9341 @example
9342 AC_CHECK_FUNC([vprintf], [AC_DEFINE([HAVE_VPRINTF], [1],
9343                           [Define if vprintf exists.])])
9344 if test "x$ac_cv_func_vprintf" != xyes; then
9345   AC_CHECK_FUNC([_doprnt], [AC_DEFINE([HAVE_DOPRNT], [1],
9346                             [Define if _doprnt exists.])])
9348 @end example
9350 If @code{AC_CONFIG_HEADERS} has been called, then instead of creating
9351 @code{DEFS}, @code{AC_OUTPUT} creates a header file by substituting the
9352 correct values into @code{#define} statements in a template file.
9353 @xref{Configuration Headers}, for more information about this kind of
9354 output.
9356 @defmac AC_DEFINE (@var{variable}, @var{value}, @ovar{description})
9357 @defmacx AC_DEFINE (@var{variable})
9358 @cvindex @var{variable}
9359 @acindex{DEFINE}
9360 Define @var{variable} to @var{value} (verbatim), by defining a C
9361 preprocessor macro for @var{variable}.  @var{variable} should be a C
9362 identifier, optionally suffixed by a parenthesized argument list to
9363 define a C preprocessor macro with arguments.  The macro argument list,
9364 if present, should be a comma-separated list of C identifiers, possibly
9365 terminated by an ellipsis @samp{...} if C99 syntax is employed.
9366 @var{variable} should not contain comments, white space, trigraphs,
9367 backslash-newlines, universal character names, or non-ASCII
9368 characters.
9370 @var{value} may contain backslash-escaped newlines, which will be
9371 preserved if you use @code{AC_CONFIG_HEADERS} but flattened if passed
9372 via @code{@@DEFS@@} (with no effect on the compilation, since the
9373 preprocessor sees only one line in the first place).  @var{value} should
9374 not contain raw newlines.  If you are not using
9375 @code{AC_CONFIG_HEADERS}, @var{value} should not contain any @samp{#}
9376 characters, as @command{make} tends to eat them.  To use a shell
9377 variable, use @code{AC_DEFINE_UNQUOTED} instead.
9379 @var{description} is only useful if you are using
9380 @code{AC_CONFIG_HEADERS}.  In this case, @var{description} is put into
9381 the generated @file{config.h.in} as the comment before the macro define.
9382 The following example defines the C preprocessor variable
9383 @code{EQUATION} to be the string constant @samp{"$a > $b"}:
9385 @example
9386 AC_DEFINE([EQUATION], ["$a > $b"],
9387   [Equation string.])
9388 @end example
9390 If neither @var{value} nor @var{description} are given, then
9391 @var{value} defaults to 1 instead of to the empty string.  This is for
9392 backwards compatibility with older versions of Autoconf, but this usage
9393 is obsolescent and may be withdrawn in future versions of Autoconf.
9395 If the @var{variable} is a literal string, it is passed to
9396 @code{m4_pattern_allow} (@pxref{Forbidden Patterns}).
9398 If multiple @code{AC_DEFINE} statements are executed for the same
9399 @var{variable} name (not counting any parenthesized argument list),
9400 the last one wins.
9401 @end defmac
9403 @defmac AC_DEFINE_UNQUOTED (@var{variable}, @var{value}, @ovar{description})
9404 @defmacx AC_DEFINE_UNQUOTED (@var{variable})
9405 @acindex{DEFINE_UNQUOTED}
9406 @cvindex @var{variable}
9407 Like @code{AC_DEFINE}, but three shell expansions are
9408 performed---once---on @var{variable} and @var{value}: variable expansion
9409 (@samp{$}), command substitution (@samp{`}), and backslash escaping
9410 (@samp{\}), as if in an unquoted here-document.  Single and double quote
9411 characters in the value have no
9412 special meaning.  Use this macro instead of @code{AC_DEFINE} when
9413 @var{variable} or @var{value} is a shell variable.  Examples:
9415 @example
9416 AC_DEFINE_UNQUOTED([config_machfile], ["$machfile"],
9417   [Configuration machine file.])
9418 AC_DEFINE_UNQUOTED([GETGROUPS_T], [$ac_cv_type_getgroups],
9419   [getgroups return type.])
9420 AC_DEFINE_UNQUOTED([$ac_tr_hdr], [1],
9421   [Translated header name.])
9422 @end example
9423 @end defmac
9425 Due to a syntactical bizarreness of the Bourne shell, do not use
9426 semicolons to separate @code{AC_DEFINE} or @code{AC_DEFINE_UNQUOTED}
9427 calls from other macro calls or shell code; that can cause syntax errors
9428 in the resulting @command{configure} script.  Use either blanks or
9429 newlines.  That is, do this:
9431 @example
9432 AC_CHECK_HEADER([elf.h],
9433   [AC_DEFINE([SVR4], [1], [System V Release 4]) LIBS="-lelf $LIBS"])
9434 @end example
9436 @noindent
9437 or this:
9439 @example
9440 AC_CHECK_HEADER([elf.h],
9441   [AC_DEFINE([SVR4], [1], [System V Release 4])
9442    LIBS="-lelf $LIBS"])
9443 @end example
9445 @noindent
9446 instead of this:
9448 @example
9449 AC_CHECK_HEADER([elf.h],
9450   [AC_DEFINE([SVR4], [1], [System V Release 4]); LIBS="-lelf $LIBS"])
9451 @end example
9453 @node Setting Output Variables
9454 @section Setting Output Variables
9455 @cindex Output variables
9457 Another way to record the results of tests is to set @dfn{output
9458 variables}, which are shell variables whose values are substituted into
9459 files that @command{configure} outputs.  The two macros below create new
9460 output variables.  @xref{Preset Output Variables}, for a list of output
9461 variables that are always available.
9463 @defmac AC_SUBST (@var{variable}, @ovar{value})
9464 @acindex{SUBST}
9465 Create an output variable from a shell variable.  Make @code{AC_OUTPUT}
9466 substitute the variable @var{variable} into output files (typically one
9467 or more makefiles).  This means that @code{AC_OUTPUT}
9468 replaces instances of @samp{@@@var{variable}@@} in input files with the
9469 value that the shell variable @var{variable} has when @code{AC_OUTPUT}
9470 is called.  The value can contain any non-@code{NUL} character, including
9471 newline.  If you are using Automake 1.11 or newer, for newlines in values
9472 you might want to consider using @code{AM_SUBST_NOTMAKE} to prevent
9473 @command{automake} from adding a line @code{@var{variable} =
9474 @@@var{variable}@@} to the @file{Makefile.in} files (@pxref{Optional, ,
9475 Automake, automake, Other things Automake recognizes}).
9477 Variable occurrences should not overlap: e.g., an input file should
9478 not contain @samp{@@@var{var1}@@@var{var2}@@} if @var{var1} and @var{var2}
9479 are variable names.
9480 The substituted value is not rescanned for more output variables;
9481 occurrences of @samp{@@@var{variable}@@} in the value are inserted
9482 literally into the output file.  (The algorithm uses the special marker
9483 @code{|#_!!_#|} internally, so neither the substituted value nor the
9484 output file may contain @code{|#_!!_#|}.)
9486 If @var{value} is given, in addition assign it to @var{variable}.
9488 The string @var{variable} is passed to @code{m4_pattern_allow}
9489 (@pxref{Forbidden Patterns}).
9490 @end defmac
9492 @defmac AC_SUBST_FILE (@var{variable})
9493 @acindex{SUBST_FILE}
9494 Another way to create an output variable from a shell variable.  Make
9495 @code{AC_OUTPUT} insert (without substitutions) the contents of the file
9496 named by shell variable @var{variable} into output files.  This means
9497 that @code{AC_OUTPUT} replaces instances of
9498 @samp{@@@var{variable}@@} in output files (such as @file{Makefile.in})
9499 with the contents of the file that the shell variable @var{variable}
9500 names when @code{AC_OUTPUT} is called.  Set the variable to
9501 @file{/dev/null} for cases that do not have a file to insert.
9502 This substitution occurs only when the @samp{@@@var{variable}@@} is on a
9503 line by itself, optionally surrounded by spaces and tabs.  The
9504 substitution replaces the whole line, including the spaces, tabs, and
9505 the terminating newline.
9507 This macro is useful for inserting makefile fragments containing
9508 special dependencies or other @command{make} directives for particular host
9509 or target types into makefiles.  For example, @file{configure.ac}
9510 could contain:
9512 @example
9513 AC_SUBST_FILE([host_frag])
9514 host_frag=$srcdir/conf/sun4.mh
9515 @end example
9517 @noindent
9518 and then a @file{Makefile.in} could contain:
9520 @example
9521 @@host_frag@@
9522 @end example
9524 The string @var{variable} is passed to @code{m4_pattern_allow}
9525 (@pxref{Forbidden Patterns}).
9526 @end defmac
9528 @cindex Precious Variable
9529 @cindex Variable, Precious
9530 Running @command{configure} in varying environments can be extremely
9531 dangerous.  If for instance the user runs @samp{CC=bizarre-cc
9532 ./configure}, then the cache, @file{config.h}, and many other output
9533 files depend upon @command{bizarre-cc} being the C compiler.  If
9534 for some reason the user runs @command{./configure} again, or if it is
9535 run via @samp{./config.status --recheck}, (@xref{Automatic Remaking},
9536 and @pxref{config.status Invocation}), then the configuration can be
9537 inconsistent, composed of results depending upon two different
9538 compilers.
9540 Environment variables that affect this situation, such as @samp{CC}
9541 above, are called @dfn{precious variables}, and can be declared as such
9542 by @code{AC_ARG_VAR}.
9544 @defmac AC_ARG_VAR (@var{variable}, @var{description})
9545 @acindex{ARG_VAR}
9546 Declare @var{variable} is a precious variable, and include its
9547 @var{description} in the variable section of @samp{./configure --help}.
9549 Being precious means that
9550 @itemize @minus
9551 @item
9552 @var{variable} is substituted via @code{AC_SUBST}.
9554 @item
9555 The value of @var{variable} when @command{configure} was launched is
9556 saved in the cache, including if it was not specified on the command
9557 line but via the environment.  Indeed, while @command{configure} can
9558 notice the definition of @code{CC} in @samp{./configure CC=bizarre-cc},
9559 it is impossible to notice it in @samp{CC=bizarre-cc ./configure},
9560 which, unfortunately, is what most users do.
9562 We emphasize that it is the @emph{initial} value of @var{variable} which
9563 is saved, not that found during the execution of @command{configure}.
9564 Indeed, specifying @samp{./configure FOO=foo} and letting
9565 @samp{./configure} guess that @code{FOO} is @code{foo} can be two
9566 different things.
9568 @item
9569 @var{variable} is checked for consistency between two
9570 @command{configure} runs.  For instance:
9572 @example
9573 $ @kbd{./configure --silent --config-cache}
9574 $ @kbd{CC=cc ./configure --silent --config-cache}
9575 configure: error: `CC' was not set in the previous run
9576 configure: error: changes in the environment can compromise \
9577 the build
9578 configure: error: run `make distclean' and/or \
9579 `rm config.cache' and start over
9580 @end example
9582 @noindent
9583 and similarly if the variable is unset, or if its content is changed.
9584 If the content has white space changes only, then the error is degraded
9585 to a warning only, but the old value is reused.
9587 @item
9588 @var{variable} is kept during automatic reconfiguration
9589 (@pxref{config.status Invocation}) as if it had been passed as a command
9590 line argument, including when no cache is used:
9592 @example
9593 $ @kbd{CC=/usr/bin/cc ./configure var=raboof --silent}
9594 $ @kbd{./config.status --recheck}
9595 running CONFIG_SHELL=/bin/sh /bin/sh ./configure var=raboof \
9596   CC=/usr/bin/cc  --no-create --no-recursion
9597 @end example
9598 @end itemize
9599 @end defmac
9601 @node Special Chars in Variables
9602 @section Special Characters in Output Variables
9603 @cindex Output variables, special characters in
9605 Many output variables are intended to be evaluated both by
9606 @command{make} and by the shell.  Some characters are expanded
9607 differently in these two contexts, so to avoid confusion these
9608 variables' values should not contain any of the following characters:
9610 @example
9611 " # $ & ' ( ) * ; < > ? [ \ ^ ` |
9612 @end example
9614 Also, these variables' values should neither contain newlines, nor start
9615 with @samp{~}, nor contain white space or @samp{:} immediately followed
9616 by @samp{~}.  The values can contain nonempty sequences of white space
9617 characters like tabs and spaces, but each such sequence might
9618 arbitrarily be replaced by a single space during substitution.
9620 These restrictions apply both to the values that @command{configure}
9621 computes, and to the values set directly by the user.  For example, the
9622 following invocations of @command{configure} are problematic, since they
9623 attempt to use special characters within @code{CPPFLAGS} and white space
9624 within @code{$(srcdir)}:
9626 @example
9627 CPPFLAGS='-DOUCH="&\"#$*?"' '../My Source/ouch-1.0/configure'
9629 '../My Source/ouch-1.0/configure' CPPFLAGS='-DOUCH="&\"#$*?"'
9630 @end example
9632 @node Caching Results
9633 @section Caching Results
9634 @cindex Cache
9636 To avoid checking for the same features repeatedly in various
9637 @command{configure} scripts (or in repeated runs of one script),
9638 @command{configure} can optionally save the results of many checks in a
9639 @dfn{cache file} (@pxref{Cache Files}).  If a @command{configure} script
9640 runs with caching enabled and finds a cache file, it reads the results
9641 of previous runs from the cache and avoids rerunning those checks.  As a
9642 result, @command{configure} can then run much faster than if it had to
9643 perform all of the checks every time.
9645 @defmac AC_CACHE_VAL (@var{cache-id}, @var{commands-to-set-it})
9646 @acindex{CACHE_VAL}
9647 Ensure that the results of the check identified by @var{cache-id} are
9648 available.  If the results of the check were in the cache file that was
9649 read, and @command{configure} was not given the @option{--quiet} or
9650 @option{--silent} option, print a message saying that the result was
9651 cached; otherwise, run the shell commands @var{commands-to-set-it}.  If
9652 the shell commands are run to determine the value, the value is
9653 saved in the cache file just before @command{configure} creates its output
9654 files.  @xref{Cache Variable Names}, for how to choose the name of the
9655 @var{cache-id} variable.
9657 The @var{commands-to-set-it} @emph{must have no side effects} except for
9658 setting the variable @var{cache-id}, see below.
9659 @end defmac
9661 @defmac AC_CACHE_CHECK (@var{message}, @var{cache-id}, @
9662   @var{commands-to-set-it})
9663 @acindex{CACHE_CHECK}
9664 A wrapper for @code{AC_CACHE_VAL} that takes care of printing the
9665 messages.  This macro provides a convenient shorthand for the most
9666 common way to use these macros.  It calls @code{AC_MSG_CHECKING} for
9667 @var{message}, then @code{AC_CACHE_VAL} with the @var{cache-id} and
9668 @var{commands} arguments, and @code{AC_MSG_RESULT} with @var{cache-id}.
9670 The @var{commands-to-set-it} @emph{must have no side effects} except for
9671 setting the variable @var{cache-id}, see below.
9672 @end defmac
9674 It is common to find buggy macros using @code{AC_CACHE_VAL} or
9675 @code{AC_CACHE_CHECK}, because people are tempted to call
9676 @code{AC_DEFINE} in the @var{commands-to-set-it}.  Instead, the code that
9677 @emph{follows} the call to @code{AC_CACHE_VAL} should call
9678 @code{AC_DEFINE}, by examining the value of the cache variable.  For
9679 instance, the following macro is broken:
9681 @example
9682 @c If you change this example, adjust tests/base.at:AC_CACHE_CHECK.
9683 @group
9684 AC_DEFUN([AC_SHELL_TRUE],
9685 [AC_CACHE_CHECK([whether true(1) works], [my_cv_shell_true_works],
9686                 [my_cv_shell_true_works=no
9687                  (true) 2>/dev/null && my_cv_shell_true_works=yes
9688                  if test "x$my_cv_shell_true_works" = xyes; then
9689                    AC_DEFINE([TRUE_WORKS], [1],
9690                              [Define if `true(1)' works properly.])
9691                  fi])
9693 @end group
9694 @end example
9696 @noindent
9697 This fails if the cache is enabled: the second time this macro is run,
9698 @code{TRUE_WORKS} @emph{will not be defined}.  The proper implementation
9701 @example
9702 @c If you change this example, adjust tests/base.at:AC_CACHE_CHECK.
9703 @group
9704 AC_DEFUN([AC_SHELL_TRUE],
9705 [AC_CACHE_CHECK([whether true(1) works], [my_cv_shell_true_works],
9706                 [my_cv_shell_true_works=no
9707                  (true) 2>/dev/null && my_cv_shell_true_works=yes])
9708  if test "x$my_cv_shell_true_works" = xyes; then
9709    AC_DEFINE([TRUE_WORKS], [1],
9710              [Define if `true(1)' works properly.])
9711  fi
9713 @end group
9714 @end example
9716 Also, @var{commands-to-set-it} should not print any messages, for
9717 example with @code{AC_MSG_CHECKING}; do that before calling
9718 @code{AC_CACHE_VAL}, so the messages are printed regardless of whether
9719 the results of the check are retrieved from the cache or determined by
9720 running the shell commands.
9722 @menu
9723 * Cache Variable Names::        Shell variables used in caches
9724 * Cache Files::                 Files @command{configure} uses for caching
9725 * Cache Checkpointing::         Loading and saving the cache file
9726 @end menu
9728 @node Cache Variable Names
9729 @subsection Cache Variable Names
9730 @cindex Cache variable
9732 The names of cache variables should have the following format:
9734 @example
9735 @var{package-prefix}_cv_@var{value-type}_@var{specific-value}_@ovar{additional-options}
9736 @end example
9738 @noindent
9739 for example, @samp{ac_cv_header_stat_broken} or
9740 @samp{ac_cv_prog_gcc_traditional}.  The parts of the variable name are:
9742 @table @asis
9743 @item @var{package-prefix}
9744 An abbreviation for your package or organization; the same prefix you
9745 begin local Autoconf macros with, except lowercase by convention.
9746 For cache values used by the distributed Autoconf macros, this value is
9747 @samp{ac}.
9749 @item @code{_cv_}
9750 Indicates that this shell variable is a cache value.  This string
9751 @emph{must} be present in the variable name, including the leading
9752 underscore.
9754 @item @var{value-type}
9755 A convention for classifying cache values, to produce a rational naming
9756 system.  The values used in Autoconf are listed in @ref{Macro Names}.
9758 @item @var{specific-value}
9759 Which member of the class of cache values this test applies to.
9760 For example, which function (@samp{alloca}), program (@samp{gcc}), or
9761 output variable (@samp{INSTALL}).
9763 @item @var{additional-options}
9764 Any particular behavior of the specific member that this test applies to.
9765 For example, @samp{broken} or @samp{set}.  This part of the name may
9766 be omitted if it does not apply.
9767 @end table
9769 The values assigned to cache variables may not contain newlines.
9770 Usually, their values are Boolean (@samp{yes} or @samp{no}) or the
9771 names of files or functions; so this is not an important restriction.
9772 @ref{Cache Variable Index} for an index of cache variables with
9773 documented semantics.
9776 @node Cache Files
9777 @subsection Cache Files
9779 A cache file is a shell script that caches the results of configure
9780 tests run on one system so they can be shared between configure scripts
9781 and configure runs.  It is not useful on other systems.  If its contents
9782 are invalid for some reason, the user may delete or edit it, or override
9783 documented cache variables on the @command{configure} command line.
9785 By default, @command{configure} uses no cache file,
9786 to avoid problems caused by accidental
9787 use of stale cache files.
9789 To enable caching, @command{configure} accepts @option{--config-cache} (or
9790 @option{-C}) to cache results in the file @file{config.cache}.
9791 Alternatively, @option{--cache-file=@var{file}} specifies that
9792 @var{file} be the cache file.  The cache file is created if it does not
9793 exist already.  When @command{configure} calls @command{configure} scripts in
9794 subdirectories, it uses the @option{--cache-file} argument so that they
9795 share the same cache.  @xref{Subdirectories}, for information on
9796 configuring subdirectories with the @code{AC_CONFIG_SUBDIRS} macro.
9798 @file{config.status} only pays attention to the cache file if it is
9799 given the @option{--recheck} option, which makes it rerun
9800 @command{configure}.
9802 It is wrong to try to distribute cache files for particular system types.
9803 There is too much room for error in doing that, and too much
9804 administrative overhead in maintaining them.  For any features that
9805 can't be guessed automatically, use the standard method of the canonical
9806 system type and linking files (@pxref{Manual Configuration}).
9808 The site initialization script can specify a site-wide cache file to
9809 use, instead of the usual per-program cache.  In this case, the cache
9810 file gradually accumulates information whenever someone runs a new
9811 @command{configure} script.  (Running @command{configure} merges the new cache
9812 results with the existing cache file.)  This may cause problems,
9813 however, if the system configuration (e.g., the installed libraries or
9814 compilers) changes and the stale cache file is not deleted.
9816 If @command{configure} is interrupted at the right time when it updates
9817 a cache file outside of the build directory where the @command{configure}
9818 script is run, it may leave behind a temporary file named after the
9819 cache file with digits following it.  You may safely delete such a file.
9822 @node Cache Checkpointing
9823 @subsection Cache Checkpointing
9825 If your configure script, or a macro called from @file{configure.ac}, happens
9826 to abort the configure process, it may be useful to checkpoint the cache
9827 a few times at key points using @code{AC_CACHE_SAVE}.  Doing so
9828 reduces the amount of time it takes to rerun the configure script with
9829 (hopefully) the error that caused the previous abort corrected.
9831 @c FIXME: Do we really want to document this guy?
9832 @defmac AC_CACHE_LOAD
9833 @acindex{CACHE_LOAD}
9834 Loads values from existing cache file, or creates a new cache file if a
9835 cache file is not found.  Called automatically from @code{AC_INIT}.
9836 @end defmac
9838 @defmac AC_CACHE_SAVE
9839 @acindex{CACHE_SAVE}
9840 Flushes all cached values to the cache file.  Called automatically from
9841 @code{AC_OUTPUT}, but it can be quite useful to call
9842 @code{AC_CACHE_SAVE} at key points in @file{configure.ac}.
9843 @end defmac
9845 For instance:
9847 @example
9848 @r{ @dots{} AC_INIT, etc. @dots{}}
9849 @group
9850 # Checks for programs.
9851 AC_PROG_CC
9852 AC_PROG_AWK
9853 @r{ @dots{} more program checks @dots{}}
9854 AC_CACHE_SAVE
9855 @end group
9857 @group
9858 # Checks for libraries.
9859 AC_CHECK_LIB([nsl], [gethostbyname])
9860 AC_CHECK_LIB([socket], [connect])
9861 @r{ @dots{} more lib checks @dots{}}
9862 AC_CACHE_SAVE
9863 @end group
9865 @group
9866 # Might abort@dots{}
9867 AM_PATH_GTK([1.0.2], [], [AC_MSG_ERROR([GTK not in path])])
9868 AM_PATH_GTKMM([0.9.5], [], [AC_MSG_ERROR([GTK not in path])])
9869 @end group
9870 @r{ @dots{} AC_OUTPUT, etc. @dots{}}
9871 @end example
9873 @node Printing Messages
9874 @section Printing Messages
9875 @cindex Messages, from @command{configure}
9877 @command{configure} scripts need to give users running them several kinds
9878 of information.  The following macros print messages in ways appropriate
9879 for each kind.  The arguments to all of them get enclosed in shell
9880 double quotes, so the shell performs variable and back-quote
9881 substitution on them.
9883 These macros are all wrappers around the @command{echo} shell command.
9884 They direct output to the appropriate file descriptor (@pxref{File
9885 Descriptor Macros}).
9886 @command{configure} scripts should rarely need to run @command{echo} directly
9887 to print messages for the user.  Using these macros makes it easy to
9888 change how and when each kind of message is printed; such changes need
9889 only be made to the macro definitions and all the callers change
9890 automatically.
9892 To diagnose static issues, i.e., when @command{autoconf} is run, see
9893 @ref{Diagnostic Macros}.
9895 @defmac AC_MSG_CHECKING (@var{feature-description})
9896 @acindex{MSG_CHECKING}
9897 Notify the user that @command{configure} is checking for a particular
9898 feature.  This macro prints a message that starts with @samp{checking }
9899 and ends with @samp{...} and no newline.  It must be followed by a call
9900 to @code{AC_MSG_RESULT} to print the result of the check and the
9901 newline.  The @var{feature-description} should be something like
9902 @samp{whether the Fortran compiler accepts C++ comments} or @samp{for
9903 c89}.
9905 This macro prints nothing if @command{configure} is run with the
9906 @option{--quiet} or @option{--silent} option.
9907 @end defmac
9909 @anchor{AC_MSG_RESULT}
9910 @defmac AC_MSG_RESULT (@var{result-description})
9911 @acindex{MSG_RESULT}
9912 Notify the user of the results of a check.  @var{result-description} is
9913 almost always the value of the cache variable for the check, typically
9914 @samp{yes}, @samp{no}, or a file name.  This macro should follow a call
9915 to @code{AC_MSG_CHECKING}, and the @var{result-description} should be
9916 the completion of the message printed by the call to
9917 @code{AC_MSG_CHECKING}.
9919 This macro prints nothing if @command{configure} is run with the
9920 @option{--quiet} or @option{--silent} option.
9921 @end defmac
9923 @anchor{AC_MSG_NOTICE}
9924 @defmac AC_MSG_NOTICE (@var{message})
9925 @acindex{MSG_NOTICE}
9926 Deliver the @var{message} to the user.  It is useful mainly to print a
9927 general description of the overall purpose of a group of feature checks,
9928 e.g.,
9930 @example
9931 AC_MSG_NOTICE([checking if stack overflow is detectable])
9932 @end example
9934 This macro prints nothing if @command{configure} is run with the
9935 @option{--quiet} or @option{--silent} option.
9936 @end defmac
9938 @anchor{AC_MSG_ERROR}
9939 @defmac AC_MSG_ERROR (@var{error-description}, @dvar{exit-status, $?/1})
9940 @acindex{MSG_ERROR}
9941 Notify the user of an error that prevents @command{configure} from
9942 completing.  This macro prints an error message to the standard error
9943 output and exits @command{configure} with @var{exit-status} (@samp{$?}
9944 by default, except that @samp{0} is converted to @samp{1}).
9945 @var{error-description} should be something like @samp{invalid value
9946 $HOME for \$HOME}.
9948 The @var{error-description} should start with a lower-case letter, and
9949 ``cannot'' is preferred to ``can't''.
9950 @end defmac
9952 @defmac AC_MSG_FAILURE (@var{error-description}, @ovar{exit-status})
9953 @acindex{MSG_FAILURE}
9954 This @code{AC_MSG_ERROR} wrapper notifies the user of an error that
9955 prevents @command{configure} from completing @emph{and} that additional
9956 details are provided in @file{config.log}.  This is typically used when
9957 abnormal results are found during a compilation.
9958 @end defmac
9960 @anchor{AC_MSG_WARN}
9961 @defmac AC_MSG_WARN (@var{problem-description})
9962 @acindex{MSG_WARN}
9963 Notify the @command{configure} user of a possible problem.  This macro
9964 prints the message to the standard error output; @command{configure}
9965 continues running afterward, so macros that call @code{AC_MSG_WARN} should
9966 provide a default (back-up) behavior for the situations they warn about.
9967 @var{problem-description} should be something like @samp{ln -s seems to
9968 make hard links}.
9969 @end defmac
9973 @c ====================================================== Programming in M4.
9975 @node Programming in M4
9976 @chapter Programming in M4
9977 @cindex M4
9979 Autoconf is written on top of two layers: @dfn{M4sugar}, which provides
9980 convenient macros for pure M4 programming, and @dfn{M4sh}, which
9981 provides macros dedicated to shell script generation.
9983 As of this version of Autoconf, these two layers still contain
9984 experimental macros, whose interface might change in the future.  As a
9985 matter of fact, @emph{anything that is not documented must not be used}.
9987 @menu
9988 * M4 Quotation::                Protecting macros from unwanted expansion
9989 * Using autom4te::              The Autoconf executables backbone
9990 * Programming in M4sugar::      Convenient pure M4 macros
9991 * Debugging via autom4te::      Figuring out what M4 was doing
9992 @end menu
9994 @node M4 Quotation
9995 @section M4 Quotation
9996 @cindex M4 quotation
9997 @cindex quotation
9999 The most common problem with existing macros is an improper quotation.
10000 This section, which users of Autoconf can skip, but which macro writers
10001 @emph{must} read, first justifies the quotation scheme that was chosen
10002 for Autoconf and then ends with a rule of thumb.  Understanding the
10003 former helps one to follow the latter.
10005 @menu
10006 * Active Characters::           Characters that change the behavior of M4
10007 * One Macro Call::              Quotation and one macro call
10008 * Quoting and Parameters::      M4 vs. shell parameters
10009 * Quotation and Nested Macros::  Macros calling macros
10010 * Changequote is Evil::         Worse than INTERCAL: M4 + changequote
10011 * Quadrigraphs::                Another way to escape special characters
10012 * Balancing Parentheses::       Dealing with unbalanced parentheses
10013 * Quotation Rule Of Thumb::     One parenthesis, one quote
10014 @end menu
10016 @node Active Characters
10017 @subsection Active Characters
10019 To fully understand where proper quotation is important, you first need
10020 to know what the special characters are in Autoconf: @samp{#} introduces
10021 a comment inside which no macro expansion is performed, @samp{,}
10022 separates arguments, @samp{[} and @samp{]} are the quotes
10023 themselves@footnote{By itself, M4 uses @samp{`} and @samp{'}; it is the
10024 M4sugar layer that sets up the preferred quotes of @samp{[} and @samp{]}.},
10025 @samp{(} and @samp{)} (which M4 tries to match by pairs), and finally
10026 @samp{$} inside a macro definition.
10028 In order to understand the delicate case of macro calls, we first have
10029 to present some obvious failures.  Below they are ``obvious-ified'',
10030 but when you find them in real life, they are usually in disguise.
10032 Comments, introduced by a hash and running up to the newline, are opaque
10033 tokens to the top level: active characters are turned off, and there is
10034 no macro expansion:
10036 @example
10037 # define([def], ine)
10038 @result{}# define([def], ine)
10039 @end example
10041 Each time there can be a macro expansion, there is a quotation
10042 expansion, i.e., one level of quotes is stripped:
10044 @example
10045 int tab[10];
10046 @result{}int tab10;
10047 [int tab[10];]
10048 @result{}int tab[10];
10049 @end example
10051 Without this in mind, the reader might try hopelessly to use her macro
10052 @code{array}:
10054 @example
10055 define([array], [int tab[10];])
10056 array
10057 @result{}int tab10;
10058 [array]
10059 @result{}array
10060 @end example
10062 @noindent
10063 How can you correctly output the intended results@footnote{Using
10064 @code{defn}.}?
10067 @node One Macro Call
10068 @subsection One Macro Call
10070 Let's proceed on the interaction between active characters and macros
10071 with this small macro, which just returns its first argument:
10073 @example
10074 define([car], [$1])
10075 @end example
10077 @noindent
10078 The two pairs of quotes above are not part of the arguments of
10079 @code{define}; rather, they are understood by the top level when it
10080 tries to find the arguments of @code{define}.  Therefore, assuming
10081 @code{car} is not already defined, it is equivalent to write:
10083 @example
10084 define(car, $1)
10085 @end example
10087 @noindent
10088 But, while it is acceptable for a @file{configure.ac} to avoid unnecessary
10089 quotes, it is bad practice for Autoconf macros which must both be more
10090 robust and also advocate perfect style.
10092 At the top level, there are only two possibilities: either you
10093 quote or you don't:
10095 @example
10096 car(foo, bar, baz)
10097 @result{}foo
10098 [car(foo, bar, baz)]
10099 @result{}car(foo, bar, baz)
10100 @end example
10102 Let's pay attention to the special characters:
10104 @example
10105 car(#)
10106 @error{}EOF in argument list
10107 @end example
10109 The closing parenthesis is hidden in the comment; with a hypothetical
10110 quoting, the top level understood it this way:
10112 @example
10113 car([#)]
10114 @end example
10116 @noindent
10117 Proper quotation, of course, fixes the problem:
10119 @example
10120 car([#])
10121 @result{}#
10122 @end example
10124 Here are more examples:
10126 @example
10127 car(foo, bar)
10128 @result{}foo
10129 car([foo, bar])
10130 @result{}foo, bar
10131 car((foo, bar))
10132 @result{}(foo, bar)
10133 car([(foo], [bar)])
10134 @result{}(foo
10135 define([a], [b])
10136 @result{}
10137 car(a)
10138 @result{}b
10139 car([a])
10140 @result{}b
10141 car([[a]])
10142 @result{}a
10143 car([[[a]]])
10144 @result{}[a]
10145 @end example
10147 @node Quoting and Parameters
10148 @subsection Quoting and Parameters
10150 When M4 encounters @samp{$} within a macro definition, followed
10151 immediately by a character it recognizes (@samp{0}@dots{}@samp{9},
10152 @samp{#}, @samp{@@}, or @samp{*}), it will perform M4 parameter
10153 expansion.  This happens regardless of how many layers of quotes the
10154 parameter expansion is nested within, or even if it occurs in text that
10155 will be rescanned as a comment.
10157 @example
10158 define([none], [$1])
10159 @result{}
10160 define([one], [[$1]])
10161 @result{}
10162 define([two], [[[$1]]])
10163 @result{}
10164 define([comment], [# $1])
10165 @result{}
10166 define([active], [ACTIVE])
10167 @result{}
10168 none([active])
10169 @result{}ACTIVE
10170 one([active])
10171 @result{}active
10172 two([active])
10173 @result{}[active]
10174 comment([active])
10175 @result{}# active
10176 @end example
10178 On the other hand, since autoconf generates shell code, you often want
10179 to output shell variable expansion, rather than performing M4 parameter
10180 expansion.  To do this, you must use M4 quoting to separate the @samp{$}
10181 from the next character in the definition of your macro.  If the macro
10182 definition occurs in single-quoted text, then insert another level of
10183 quoting; if the usage is already inside a double-quoted string, then
10184 split it into concatenated strings.
10186 @example
10187 define([single], [a single-quoted $[]1 definition])
10188 @result{}
10189 define([double], [[a double-quoted $][1 definition]])
10190 @result{}
10191 single
10192 @result{}a single-quoted $1 definition
10193 double
10194 @result{}a double-quoted $1 definition
10195 @end example
10197 Posix states that M4 implementations are free to provide implementation
10198 extensions when @samp{$@{} is encountered in a macro definition.
10199 Autoconf reserves the longer sequence @samp{$@{@{} for use with planned
10200 extensions that will be available in the future GNU M4 2.0,
10201 but guarantees that all other instances of @samp{$@{} will be output
10202 literally.  Therefore, this idiom can also be used to output shell code
10203 parameter references:
10205 @example
10206 define([first], [$@{1@}])first
10207 @result{}$@{1@}
10208 @end example
10210 Posix also states that @samp{$11} should expand to the first parameter
10211 concatenated with a literal @samp{1}, although some versions of
10212 GNU M4 expand the eleventh parameter instead.  For
10213 portability, you should only use single-digit M4 parameter expansion.
10215 With this in mind, we can explore the cases where macros invoke
10216 macros@enddots{}
10218 @node Quotation and Nested Macros
10219 @subsection Quotation and Nested Macros
10221 The examples below use the following macros:
10223 @example
10224 define([car], [$1])
10225 define([active], [ACT, IVE])
10226 define([array], [int tab[10]])
10227 @end example
10229 Each additional embedded macro call introduces other possible
10230 interesting quotations:
10232 @example
10233 car(active)
10234 @result{}ACT
10235 car([active])
10236 @result{}ACT, IVE
10237 car([[active]])
10238 @result{}active
10239 @end example
10241 In the first case, the top level looks for the arguments of @code{car},
10242 and finds @samp{active}.  Because M4 evaluates its arguments
10243 before applying the macro, @samp{active} is expanded, which results in:
10245 @example
10246 car(ACT, IVE)
10247 @result{}ACT
10248 @end example
10250 @noindent
10251 In the second case, the top level gives @samp{active} as first and only
10252 argument of @code{car}, which results in:
10254 @example
10255 active
10256 @result{}ACT, IVE
10257 @end example
10259 @noindent
10260 i.e., the argument is evaluated @emph{after} the macro that invokes it.
10261 In the third case, @code{car} receives @samp{[active]}, which results in:
10263 @example
10264 [active]
10265 @result{}active
10266 @end example
10268 @noindent
10269 exactly as we already saw above.
10271 The example above, applied to a more realistic example, gives:
10273 @example
10274 car(int tab[10];)
10275 @result{}int tab10;
10276 car([int tab[10];])
10277 @result{}int tab10;
10278 car([[int tab[10];]])
10279 @result{}int tab[10];
10280 @end example
10282 @noindent
10283 Huh?  The first case is easily understood, but why is the second wrong,
10284 and the third right?  To understand that, you must know that after
10285 M4 expands a macro, the resulting text is immediately subjected
10286 to macro expansion and quote removal.  This means that the quote removal
10287 occurs twice---first before the argument is passed to the @code{car}
10288 macro, and second after the @code{car} macro expands to the first
10289 argument.
10291 As the author of the Autoconf macro @code{car}, you then consider it to
10292 be incorrect that your users have to double-quote the arguments of
10293 @code{car}, so you ``fix'' your macro.  Let's call it @code{qar} for
10294 quoted car:
10296 @example
10297 define([qar], [[$1]])
10298 @end example
10300 @noindent
10301 and check that @code{qar} is properly fixed:
10303 @example
10304 qar([int tab[10];])
10305 @result{}int tab[10];
10306 @end example
10308 @noindent
10309 Ahhh!  That's much better.
10311 But note what you've done: now that the result of @code{qar} is always
10312 a literal string, the only time a user can use nested macros is if she
10313 relies on an @emph{unquoted} macro call:
10315 @example
10316 qar(active)
10317 @result{}ACT
10318 qar([active])
10319 @result{}active
10320 @end example
10322 @noindent
10323 leaving no way for her to reproduce what she used to do with @code{car}:
10325 @example
10326 car([active])
10327 @result{}ACT, IVE
10328 @end example
10330 @noindent
10331 Worse yet: she wants to use a macro that produces a set of @code{cpp}
10332 macros:
10334 @example
10335 define([my_includes], [#include <stdio.h>])
10336 car([my_includes])
10337 @result{}#include <stdio.h>
10338 qar(my_includes)
10339 @error{}EOF in argument list
10340 @end example
10342 This macro, @code{qar}, because it double quotes its arguments, forces
10343 its users to leave their macro calls unquoted, which is dangerous.
10344 Commas and other active symbols are interpreted by M4 before
10345 they are given to the macro, often not in the way the users expect.
10346 Also, because @code{qar} behaves differently from the other macros,
10347 it's an exception that should be avoided in Autoconf.
10349 @node Changequote is Evil
10350 @subsection @code{changequote} is Evil
10351 @cindex @code{changequote}
10353 The temptation is often high to bypass proper quotation, in particular
10354 when it's late at night.  Then, many experienced Autoconf hackers
10355 finally surrender to the dark side of the force and use the ultimate
10356 weapon: @code{changequote}.
10358 The M4 builtin @code{changequote} belongs to a set of primitives that
10359 allow one to adjust the syntax of the language to adjust it to one's
10360 needs.  For instance, by default M4 uses @samp{`} and @samp{'} as
10361 quotes, but in the context of shell programming (and actually of most
10362 programming languages), that's about the worst choice one can make:
10363 because of strings and back-quoted expressions in shell code (such as
10364 @samp{'this'} and @samp{`that`}), and because of literal characters in usual
10365 programming languages (as in @samp{'0'}), there are many unbalanced
10366 @samp{`} and @samp{'}.  Proper M4 quotation then becomes a nightmare, if
10367 not impossible.  In order to make M4 useful in such a context, its
10368 designers have equipped it with @code{changequote}, which makes it
10369 possible to choose another pair of quotes.  M4sugar, M4sh, Autoconf, and
10370 Autotest all have chosen to use @samp{[} and @samp{]}.  Not especially
10371 because they are unlikely characters, but @emph{because they are
10372 characters unlikely to be unbalanced}.
10374 There are other magic primitives, such as @code{changecom} to specify
10375 what syntactic forms are comments (it is common to see
10376 @samp{changecom(<!--, -->)} when M4 is used to produce HTML pages),
10377 @code{changeword} and @code{changesyntax} to change other syntactic
10378 details (such as the character to denote the @var{n}th argument, @samp{$} by
10379 default, the parentheses around arguments, etc.).
10381 These primitives are really meant to make M4 more useful for specific
10382 domains: they should be considered like command line options:
10383 @option{--quotes}, @option{--comments}, @option{--words}, and
10384 @option{--syntax}.  Nevertheless, they are implemented as M4 builtins, as
10385 it makes M4 libraries self contained (no need for additional options).
10387 There lies the problem@enddots{}
10389 @sp 1
10391 The problem is that it is then tempting to use them in the middle of an
10392 M4 script, as opposed to its initialization.  This, if not carefully
10393 thought out, can lead to disastrous effects: @emph{you are changing the
10394 language in the middle of the execution}.  Changing and restoring the
10395 syntax is often not enough: if you happened to invoke macros in between,
10396 these macros are lost, as the current syntax is probably not
10397 the one they were implemented with.
10399 @c FIXME: I've been looking for a short, real case example, but I
10400 @c lost them all :(
10403 @node Quadrigraphs
10404 @subsection Quadrigraphs
10405 @cindex quadrigraphs
10406 @cindex @samp{@@S|@@}
10407 @cindex @samp{@@&t@@}
10408 @c Info cannot handle `:' in index entries.
10409 @ifnotinfo
10410 @cindex @samp{@@<:@@}
10411 @cindex @samp{@@:>@@}
10412 @cindex @samp{@@%:@@}
10413 @cindex @samp{@@@{:@@}
10414 @cindex @samp{@@:@}@@}
10415 @end ifnotinfo
10417 When writing an Autoconf macro you may occasionally need to generate
10418 special characters that are difficult to express with the standard
10419 Autoconf quoting rules.  For example, you may need to output the regular
10420 expression @samp{[^[]}, which matches any character other than @samp{[}.
10421 This expression contains unbalanced brackets so it cannot be put easily
10422 into an M4 macro.
10424 Additionally, there are a few m4sugar macros (such as @code{m4_split}
10425 and @code{m4_expand}) which internally use special markers in addition
10426 to the regular quoting characters.  If the arguments to these macros
10427 contain the literal strings @samp{-=<@{(} or @samp{)@}>=-}, the macros
10428 might behave incorrectly.
10430 You can work around these problems by using one of the following
10431 @dfn{quadrigraphs}:
10433 @table @samp
10434 @item @@<:@@
10435 @samp{[}
10436 @item @@:>@@
10437 @samp{]}
10438 @item @@S|@@
10439 @samp{$}
10440 @item @@%:@@
10441 @samp{#}
10442 @item @@@{:@@
10443 @samp{(}
10444 @item @@:@}@@
10445 @samp{)}
10446 @item @@&t@@
10447 Expands to nothing.
10448 @end table
10450 Quadrigraphs are replaced at a late stage of the translation process,
10451 after @command{m4} is run, so they do not get in the way of M4 quoting.
10452 For example, the string @samp{^@@<:@@}, independently of its quotation,
10453 appears as @samp{^[} in the output.
10455 The empty quadrigraph can be used:
10457 @itemize @minus
10458 @item to mark trailing spaces explicitly
10460 Trailing spaces are smashed by @command{autom4te}.  This is a feature.
10462 @item to produce quadrigraphs and other strings reserved by m4sugar
10464 For instance @samp{@@<@@&t@@:@@} produces @samp{@@<:@@}.  For a more
10465 contrived example:
10467 @example
10468 m4_define([a], [A])m4_define([b], [B])m4_define([c], [C])dnl
10469 m4_split([a )@}>=- b -=<@{( c])
10470 @result{}[a], [], [B], [], [c]
10471 m4_split([a )@}@@&t@@>=- b -=<@@&t@@@{( c])
10472 @result{}[a], [)@}>=-], [b], [-=<@{(], [c]
10473 @end example
10475 @item to escape @emph{occurrences} of forbidden patterns
10477 For instance you might want to mention @code{AC_FOO} in a comment, while
10478 still being sure that @command{autom4te} still catches unexpanded
10479 @samp{AC_*}.  Then write @samp{AC@@&t@@_FOO}.
10480 @end itemize
10482 The name @samp{@@&t@@} was suggested by Paul Eggert:
10484 @quotation
10485 I should give some credit to the @samp{@@&t@@} pun.  The @samp{&} is my
10486 own invention, but the @samp{t} came from the source code of the
10487 ALGOL68C compiler, written by Steve Bourne (of Bourne shell fame),
10488 and which used @samp{mt} to denote the empty string.  In C, it would
10489 have looked like something like:
10491 @example
10492 char const mt[] = "";
10493 @end example
10495 @noindent
10496 but of course the source code was written in Algol 68.
10498 I don't know where he got @samp{mt} from: it could have been his own
10499 invention, and I suppose it could have been a common pun around the
10500 Cambridge University computer lab at the time.
10501 @end quotation
10504 @node Balancing Parentheses
10505 @subsection Dealing with unbalanced parentheses
10506 @cindex balancing parentheses
10507 @cindex parentheses, balancing
10508 @cindex unbalanced parentheses, managing
10510 One of the pitfalls of portable shell programming is that @command{case}
10511 statements require unbalanced parentheses (@pxref{case, , Limitations of
10512 Shell Builtins}).  With syntax highlighting
10513 editors, the presence of unbalanced @samp{)} can interfere with editors
10514 that perform syntax highlighting of macro contents based on finding the
10515 matching @samp{(}.  Another concern is how much editing must be done
10516 when transferring code snippets between shell scripts and macro
10517 definitions.  But most importantly, the presence of unbalanced
10518 parentheses can introduce expansion bugs.
10520 For an example, here is an underquoted attempt to use the macro
10521 @code{my_case}, which happens to expand to a portable @command{case}
10522 statement:
10524 @example
10525 AC_DEFUN([my_case],
10526 [case $file_name in
10527   *.c) echo "C source code";;
10528 esac])
10529 AS_IF(:, my_case)
10530 @end example
10532 @noindent
10533 In the above example, the @code{AS_IF} call underquotes its arguments.
10534 As a result, the unbalanced @samp{)} generated by the premature
10535 expansion of @code{my_case} results in expanding @code{AS_IF} with a
10536 truncated parameter, and the expansion is syntactically invalid:
10538 @example
10539 if :; then
10540   case $file_name in
10541   *.c
10542 fi echo "C source code";;
10543 esac)
10544 @end example
10546 If nothing else, this should emphasize the importance of the quoting
10547 arguments to macro calls.  On the other hand, there are several
10548 variations for defining @code{my_case} to be more robust, even when used
10549 without proper quoting, each with some benefits and some drawbacks.
10551 @itemize @w{}
10552 @item Creative literal shell comment
10553 @example
10554 AC_DEFUN([my_case],
10555 [case $file_name in #(
10556   *.c) echo "C source code";;
10557 esac])
10558 @end example
10559 @noindent
10560 This version provides balanced parentheses to several editors, and can
10561 be copied and pasted into a terminal as is.  Unfortunately, it is still
10562 unbalanced as an Autoconf argument, since @samp{#(} is an M4 comment
10563 that masks the normal properties of @samp{(}.
10565 @item Quadrigraph shell comment
10566 @example
10567 AC_DEFUN([my_case],
10568 [case $file_name in @@%:@@(
10569   *.c) echo "C source code";;
10570 esac])
10571 @end example
10572 @noindent
10573 This version provides balanced parentheses to even more editors, and can
10574 be used as a balanced Autoconf argument.  Unfortunately, it requires
10575 some editing before it can be copied and pasted into a terminal, and the
10576 use of the quadrigraph @samp{@@%:@@} for @samp{#} reduces readability.
10578 @item Quoting just the parenthesis
10579 @example
10580 AC_DEFUN([my_case],
10581 [case $file_name in
10582   *.c[)] echo "C source code";;
10583 esac])
10584 @end example
10585 @noindent
10586 This version quotes the @samp{)}, so that it can be used as a balanced
10587 Autoconf argument.  As written, this is not balanced to an editor, but
10588 it can be coupled with @samp{[#(]} to meet that need, too.  However, it
10589 still requires some edits before it can be copied and pasted into a
10590 terminal.
10592 @item Double-quoting the entire statement
10593 @example
10594 AC_DEFUN([my_case],
10595 [[case $file_name in #(
10596   *.c) echo "C source code";;
10597 esac]])
10598 @end example
10599 @noindent
10600 Since the entire macro is double-quoted, there is no problem with using
10601 this as an Autoconf argument; and since the double-quoting is over the
10602 entire statement, this code can be easily copied and pasted into a
10603 terminal.  However, the double quoting prevents the expansion of any
10604 macros inside the case statement, which may cause its own set of
10605 problems.
10607 @item Using @code{AS_CASE}
10608 @example
10609 AC_DEFUN([my_case],
10610 [AS_CASE([$file_name],
10611   [*.c], [echo "C source code"])])
10612 @end example
10613 @noindent
10614 This version avoids the balancing issue altogether, by relying on
10615 @code{AS_CASE} (@pxref{Common Shell Constructs}); it also allows for the
10616 expansion of @code{AC_REQUIRE} to occur prior to the entire case
10617 statement, rather than within a branch of the case statement that might
10618 not be taken.  However, the abstraction comes with a penalty that it is
10619 no longer a quick copy, paste, and edit to get back to shell code.
10620 @end itemize
10623 @node Quotation Rule Of Thumb
10624 @subsection Quotation Rule Of Thumb
10626 To conclude, the quotation rule of thumb is:
10628 @center @emph{One pair of quotes per pair of parentheses.}
10630 Never over-quote, never under-quote, in particular in the definition of
10631 macros.  In the few places where the macros need to use brackets
10632 (usually in C program text or regular expressions), properly quote
10633 @emph{the arguments}!
10635 It is common to read Autoconf programs with snippets like:
10637 @example
10638 AC_TRY_LINK(
10639 changequote(<<, >>)dnl
10640 <<#include <time.h>
10641 #ifndef tzname /* For SGI.  */
10642 extern char *tzname[]; /* RS6000 and others reject char **tzname.  */
10643 #endif>>,
10644 changequote([, ])dnl
10645 [atoi (*tzname);], ac_cv_var_tzname=yes, ac_cv_var_tzname=no)
10646 @end example
10648 @noindent
10649 which is incredibly useless since @code{AC_TRY_LINK} is @emph{already}
10650 double quoting, so you just need:
10652 @example
10653 AC_TRY_LINK(
10654 [#include <time.h>
10655 #ifndef tzname /* For SGI.  */
10656 extern char *tzname[]; /* RS6000 and others reject char **tzname.  */
10657 #endif],
10658             [atoi (*tzname);],
10659             [ac_cv_var_tzname=yes],
10660             [ac_cv_var_tzname=no])
10661 @end example
10663 @noindent
10664 The M4-fluent reader might note that these two examples are rigorously
10665 equivalent, since M4 swallows both the @samp{changequote(<<, >>)}
10666 and @samp{<<} @samp{>>} when it @dfn{collects} the arguments: these
10667 quotes are not part of the arguments!
10669 Simplified, the example above is just doing this:
10671 @example
10672 changequote(<<, >>)dnl
10673 <<[]>>
10674 changequote([, ])dnl
10675 @end example
10677 @noindent
10678 instead of simply:
10680 @example
10681 [[]]
10682 @end example
10684 With macros that do not double quote their arguments (which is the
10685 rule), double-quote the (risky) literals:
10687 @example
10688 AC_LINK_IFELSE([AC_LANG_PROGRAM(
10689 [[#include <time.h>
10690 #ifndef tzname /* For SGI.  */
10691 extern char *tzname[]; /* RS6000 and others reject char **tzname.  */
10692 #endif]],
10693                                 [atoi (*tzname);])],
10694                [ac_cv_var_tzname=yes],
10695                [ac_cv_var_tzname=no])
10696 @end example
10698 Please note that the macro @code{AC_TRY_LINK} is obsolete, so you really
10699 should be using @code{AC_LINK_IFELSE} instead.
10701 @xref{Quadrigraphs}, for what to do if you run into a hopeless case
10702 where quoting does not suffice.
10704 When you create a @command{configure} script using newly written macros,
10705 examine it carefully to check whether you need to add more quotes in
10706 your macros.  If one or more words have disappeared in the M4
10707 output, you need more quotes.  When in doubt, quote.
10709 However, it's also possible to put on too many layers of quotes.  If
10710 this happens, the resulting @command{configure} script may contain
10711 unexpanded macros.  The @command{autoconf} program checks for this problem
10712 by looking for the string @samp{AC_} in @file{configure}.  However, this
10713 heuristic does not work in general: for example, it does not catch
10714 overquoting in @code{AC_DEFINE} descriptions.
10717 @c ---------------------------------------- Using autom4te
10719 @node Using autom4te
10720 @section Using @command{autom4te}
10722 The Autoconf suite, including M4sugar, M4sh, and Autotest, in addition
10723 to Autoconf per se, heavily rely on M4.  All these different uses
10724 revealed common needs factored into a layer over M4:
10725 @command{autom4te}@footnote{
10727 Yet another great name from Lars J. Aas.
10731 @command{autom4te} is a preprocessor that is like @command{m4}.
10732 It supports M4 extensions designed for use in tools like Autoconf.
10734 @menu
10735 * autom4te Invocation::         A GNU M4 wrapper
10736 * Customizing autom4te::        Customizing the Autoconf package
10737 @end menu
10739 @node autom4te Invocation
10740 @subsection Invoking @command{autom4te}
10742 The command line arguments are modeled after M4's:
10744 @example
10745 autom4te @var{options} @var{files}
10746 @end example
10748 @noindent
10749 @evindex M4
10750 where the @var{files} are directly passed to @command{m4}.  By default,
10751 GNU M4 is found during configuration, but the environment
10752 variable
10753 @env{M4} can be set to tell @command{autom4te} where to look.  In addition
10754 to the regular expansion, it handles the replacement of the quadrigraphs
10755 (@pxref{Quadrigraphs}), and of @samp{__oline__}, the current line in the
10756 output.  It supports an extended syntax for the @var{files}:
10758 @table @file
10759 @item @var{file}.m4f
10760 This file is an M4 frozen file.  Note that @emph{all the previous files
10761 are ignored}.  See the option @option{--melt} for the rationale.
10763 @item @var{file}?
10764 If found in the library path, the @var{file} is included for expansion,
10765 otherwise it is ignored instead of triggering a failure.
10766 @end table
10768 @sp 1
10770 Of course, it supports the Autoconf common subset of options:
10772 @table @option
10773 @item --help
10774 @itemx -h
10775 Print a summary of the command line options and exit.
10777 @item --version
10778 @itemx -V
10779 Print the version number of Autoconf and exit.
10781 @item --verbose
10782 @itemx -v
10783 Report processing steps.
10785 @item --debug
10786 @itemx -d
10787 Don't remove the temporary files and be even more verbose.
10789 @item --include=@var{dir}
10790 @itemx -I @var{dir}
10791 Also look for input files in @var{dir}.  Multiple invocations
10792 accumulate.
10794 @item --output=@var{file}
10795 @itemx -o @var{file}
10796 Save output (script or trace) to @var{file}.  The file @option{-} stands
10797 for the standard output.
10798 @end table
10800 @sp 1
10802 As an extension of @command{m4}, it includes the following options:
10804 @table @option
10805 @item --warnings=@var{category}
10806 @itemx -W @var{category}
10807 @evindex WARNINGS
10808 @c FIXME: Point to the M4sugar macros, not Autoconf's.
10809 Report the warnings related to @var{category} (which can actually be a
10810 comma separated list).  @xref{Reporting Messages}, macro
10811 @code{AC_DIAGNOSE}, for a comprehensive list of categories.  Special
10812 values include:
10814 @table @samp
10815 @item all
10816 report all the warnings
10818 @item none
10819 report none
10821 @item error
10822 treats warnings as errors
10824 @item no-@var{category}
10825 disable warnings falling into @var{category}
10826 @end table
10828 Warnings about @samp{syntax} are enabled by default, and the environment
10829 variable @env{WARNINGS}, a comma separated list of categories, is
10830 honored.  @samp{autom4te -W @var{category}} actually
10831 behaves as if you had run:
10833 @example
10834 autom4te --warnings=syntax,$WARNINGS,@var{category}
10835 @end example
10837 @noindent
10838 For example, if you want to disable defaults and @env{WARNINGS}
10839 of @command{autom4te}, but enable the warnings about obsolete
10840 constructs, you would use @option{-W none,obsolete}.
10842 @cindex Back trace
10843 @cindex Macro invocation stack
10844 @command{autom4te} displays a back trace for errors, but not for
10845 warnings; if you want them, just pass @option{-W error}.
10847 @item --melt
10848 @itemx -M
10849 Do not use frozen files.  Any argument @code{@var{file}.m4f} is
10850 replaced by @code{@var{file}.m4}.  This helps tracing the macros which
10851 are executed only when the files are frozen, typically
10852 @code{m4_define}.  For instance, running:
10854 @example
10855 autom4te --melt 1.m4 2.m4f 3.m4 4.m4f input.m4
10856 @end example
10858 @noindent
10859 is roughly equivalent to running:
10861 @example
10862 m4 1.m4 2.m4 3.m4 4.m4 input.m4
10863 @end example
10865 @noindent
10866 while
10868 @example
10869 autom4te 1.m4 2.m4f 3.m4 4.m4f input.m4
10870 @end example
10872 @noindent
10873 is equivalent to:
10875 @example
10876 m4 --reload-state=4.m4f input.m4
10877 @end example
10879 @item --freeze
10880 @itemx -F
10881 Produce a frozen state file.  @command{autom4te} freezing is stricter
10882 than M4's: it must produce no warnings, and no output other than empty
10883 lines (a line with white space is @emph{not} empty) and comments
10884 (starting with @samp{#}).  Unlike @command{m4}'s similarly-named option,
10885 this option takes no argument:
10887 @example
10888 autom4te 1.m4 2.m4 3.m4 --freeze --output=3.m4f
10889 @end example
10891 @noindent
10892 corresponds to
10894 @example
10895 m4 1.m4 2.m4 3.m4 --freeze-state=3.m4f
10896 @end example
10898 @item --mode=@var{octal-mode}
10899 @itemx -m @var{octal-mode}
10900 Set the mode of the non-traces output to @var{octal-mode}; by default
10901 @samp{0666}.
10902 @end table
10904 @sp 1
10906 @cindex @file{autom4te.cache}
10907 As another additional feature over @command{m4}, @command{autom4te}
10908 caches its results.  GNU M4 is able to produce a regular
10909 output and traces at the same time.  Traces are heavily used in the
10910 GNU Build System: @command{autoheader} uses them to build
10911 @file{config.h.in}, @command{autoreconf} to determine what
10912 GNU Build System components are used, @command{automake} to
10913 ``parse'' @file{configure.ac} etc.  To avoid recomputation,
10914 traces are cached while performing regular expansion,
10915 and conversely.  This cache is (actually, the caches are) stored in
10916 the directory @file{autom4te.cache}.  @emph{It can safely be removed}
10917 at any moment (especially if for some reason @command{autom4te}
10918 considers it trashed).
10920 @table @option
10921 @item --cache=@var{directory}
10922 @itemx -C @var{directory}
10923 Specify the name of the directory where the result should be cached.
10924 Passing an empty value disables caching.  Be sure to pass a relative
10925 file name, as for the time being, global caches are not supported.
10927 @item --no-cache
10928 Don't cache the results.
10930 @item --force
10931 @itemx -f
10932 If a cache is used, consider it obsolete (but update it anyway).
10933 @end table
10935 @sp 1
10937 Because traces are so important to the GNU Build System,
10938 @command{autom4te} provides high level tracing features as compared to
10939 M4, and helps exploiting the cache:
10941 @table @option
10942 @item --trace=@var{macro}[:@var{format}]
10943 @itemx -t @var{macro}[:@var{format}]
10944 Trace the invocations of @var{macro} according to the @var{format}.
10945 Multiple @option{--trace} arguments can be used to list several macros.
10946 Multiple @option{--trace} arguments for a single macro are not
10947 cumulative; instead, you should just make @var{format} as long as
10948 needed.
10950 The @var{format} is a regular string, with newlines if desired, and
10951 several special escape codes.  It defaults to @samp{$f:$l:$n:$%}.  It can
10952 use the following special escapes:
10954 @table @samp
10955 @item $$
10956 @c $$ restore font-lock
10957 The character @samp{$}.
10959 @item $f
10960 The file name from which @var{macro} is called.
10962 @item $l
10963 The line number from which @var{macro} is called.
10965 @item $d
10966 The depth of the @var{macro} call.  This is an M4 technical detail that
10967 you probably don't want to know about.
10969 @item $n
10970 The name of the @var{macro}.
10972 @item $@var{num}
10973 The @var{num}th argument of the call to @var{macro}.
10975 @item $@@
10976 @itemx $@var{sep}@@
10977 @itemx $@{@var{separator}@}@@
10978 All the arguments passed to @var{macro}, separated by the character
10979 @var{sep} or the string @var{separator} (@samp{,} by default).  Each
10980 argument is quoted, i.e., enclosed in a pair of square brackets.
10982 @item $*
10983 @itemx $@var{sep}*
10984 @itemx $@{@var{separator}@}*
10985 As above, but the arguments are not quoted.
10987 @item $%
10988 @itemx $@var{sep}%
10989 @itemx $@{@var{separator}@}%
10990 As above, but the arguments are not quoted, all new line characters in
10991 the arguments are smashed, and the default separator is @samp{:}.
10993 The escape @samp{$%} produces single-line trace outputs (unless you put
10994 newlines in the @samp{separator}), while @samp{$@@} and @samp{$*} do
10995 not.
10996 @end table
10998 @xref{autoconf Invocation}, for examples of trace uses.
11000 @item --preselect=@var{macro}
11001 @itemx -p @var{macro}
11002 Cache the traces of @var{macro}, but do not enable traces.  This is
11003 especially important to save CPU cycles in the future.  For instance,
11004 when invoked, @command{autoconf} preselects all the macros that
11005 @command{autoheader}, @command{automake}, @command{autoreconf}, etc.,
11006 trace, so that running @command{m4} is not needed to trace them: the
11007 cache suffices.  This results in a huge speed-up.
11008 @end table
11010 @sp 1
11012 @cindex Autom4te Library
11013 Finally, @command{autom4te} introduces the concept of @dfn{Autom4te
11014 libraries}.  They consists in a powerful yet extremely simple feature:
11015 sets of combined command line arguments:
11017 @table @option
11018 @item --language=@var{language}
11019 @itemx -l @var{language}
11020 Use the @var{language} Autom4te library.  Current languages include:
11022 @table @code
11023 @item M4sugar
11024 create M4sugar output.
11026 @item M4sh
11027 create M4sh executable shell scripts.
11029 @item Autotest
11030 create Autotest executable test suites.
11032 @item Autoconf-without-aclocal-m4
11033 create Autoconf executable configure scripts without
11034 reading @file{aclocal.m4}.
11036 @item Autoconf
11037 create Autoconf executable configure scripts.  This language inherits
11038 all the characteristics of @code{Autoconf-without-aclocal-m4} and
11039 additionally reads @file{aclocal.m4}.
11040 @end table
11042 @item --prepend-include=@var{dir}
11043 @itemx -B @var{dir}
11044 Prepend directory @var{dir} to the search path.  This is used to include
11045 the language-specific files before any third-party macros.
11047 @end table
11049 @cindex @file{autom4te.cfg}
11050 As an example, if Autoconf is installed in its default location,
11051 @file{/usr/local}, the command @samp{autom4te -l m4sugar foo.m4} is
11052 strictly equivalent to the command:
11054 @example
11055 autom4te --prepend-include /usr/local/share/autoconf \
11056   m4sugar/m4sugar.m4f --warnings syntax foo.m4
11057 @end example
11059 @noindent
11060 Recursive expansion applies here: the command @samp{autom4te -l m4sh foo.m4}
11061 is the same as @samp{autom4te --language M4sugar m4sugar/m4sh.m4f
11062 foo.m4}, i.e.:
11064 @example
11065 autom4te --prepend-include /usr/local/share/autoconf \
11066   m4sugar/m4sugar.m4f m4sugar/m4sh.m4f --mode 777 foo.m4
11067 @end example
11069 @noindent
11070 The definition of the languages is stored in @file{autom4te.cfg}.
11072 @node Customizing autom4te
11073 @subsection Customizing @command{autom4te}
11075 One can customize @command{autom4te} via @file{~/.autom4te.cfg} (i.e.,
11076 as found in the user home directory), and @file{./.autom4te.cfg} (i.e.,
11077 as found in the directory from which @command{autom4te} is run).  The
11078 order is first reading @file{autom4te.cfg}, then @file{~/.autom4te.cfg},
11079 then @file{./.autom4te.cfg}, and finally the command line arguments.
11081 In these text files, comments are introduced with @code{#}, and empty
11082 lines are ignored.  Customization is performed on a per-language basis,
11083 wrapped in between a @samp{begin-language: "@var{language}"},
11084 @samp{end-language: "@var{language}"} pair.
11086 Customizing a language stands for appending options (@pxref{autom4te
11087 Invocation}) to the current definition of the language.  Options, and
11088 more generally arguments, are introduced by @samp{args:
11089 @var{arguments}}.  You may use the traditional shell syntax to quote the
11090 @var{arguments}.
11092 As an example, to disable Autoconf caches (@file{autom4te.cache})
11093 globally, include the following lines in @file{~/.autom4te.cfg}:
11095 @verbatim
11096 ## ------------------ ##
11097 ## User Preferences.  ##
11098 ## ------------------ ##
11100 begin-language: "Autoconf-without-aclocal-m4"
11101 args: --no-cache
11102 end-language: "Autoconf-without-aclocal-m4"
11103 @end verbatim
11106 @node Programming in M4sugar
11107 @section Programming in M4sugar
11109 @cindex M4sugar
11110 M4 by itself provides only a small, but sufficient, set of all-purpose
11111 macros.  M4sugar introduces additional generic macros.  Its name was
11112 coined by Lars J. Aas: ``Readability And Greater Understanding Stands 4
11113 M4sugar''.
11115 M4sugar reserves the macro namespace @samp{^_m4_} for internal use, and
11116 the macro namespace @samp{^m4_} for M4sugar macros.  You should not
11117 define your own macros into these namespaces.
11119 @menu
11120 * Redefined M4 Macros::         M4 builtins changed in M4sugar
11121 * Diagnostic Macros::           Diagnostic messages from M4sugar
11122 * Diversion support::           Diversions in M4sugar
11123 * Conditional constructs::      Conditions in M4
11124 * Looping constructs::          Iteration in M4
11125 * Evaluation Macros::           More quotation and evaluation control
11126 * Text processing Macros::      String manipulation in M4
11127 * Number processing Macros::    Arithmetic computation in M4
11128 * Set manipulation Macros::     Set manipulation in M4
11129 * Forbidden Patterns::          Catching unexpanded macros
11130 @end menu
11132 @node Redefined M4 Macros
11133 @subsection Redefined M4 Macros
11135 @msindex{builtin}
11136 @msindex{changecom}
11137 @msindex{changequote}
11138 @msindex{debugfile}
11139 @msindex{debugmode}
11140 @msindex{decr}
11141 @msindex{define}
11142 @msindex{divnum}
11143 @msindex{errprint}
11144 @msindex{esyscmd}
11145 @msindex{eval}
11146 @msindex{format}
11147 @msindex{ifdef}
11148 @msindex{incr}
11149 @msindex{index}
11150 @msindex{indir}
11151 @msindex{len}
11152 @msindex{pushdef}
11153 @msindex{shift}
11154 @msindex{substr}
11155 @msindex{syscmd}
11156 @msindex{sysval}
11157 @msindex{traceoff}
11158 @msindex{traceon}
11159 @msindex{translit}
11160 With a few exceptions, all the M4 native macros are moved in the
11161 @samp{m4_} pseudo-namespace, e.g., M4sugar renames @code{define} as
11162 @code{m4_define} etc.
11164 The list of macros unchanged from M4, except for their name, is:
11165 @itemize @minus
11166 @item m4_builtin
11167 @item m4_changecom
11168 @item m4_changequote
11169 @item m4_debugfile
11170 @item m4_debugmode
11171 @item m4_decr
11172 @item m4_define
11173 @item m4_divnum
11174 @item m4_errprint
11175 @item m4_esyscmd
11176 @item m4_eval
11177 @item m4_format
11178 @item m4_ifdef
11179 @item m4_incr
11180 @item m4_index
11181 @item m4_indir
11182 @item m4_len
11183 @item m4_pushdef
11184 @item m4_shift
11185 @item m4_substr
11186 @item m4_syscmd
11187 @item m4_sysval
11188 @item m4_traceoff
11189 @item m4_traceon
11190 @item m4_translit
11191 @end itemize
11193 Some M4 macros are redefined, and are slightly incompatible with their
11194 native equivalent.
11196 @defmac __file__
11197 @defmacx __line__
11198 @MSindex __file__
11199 @MSindex __line__
11200 All M4 macros starting with @samp{__} retain their original name: for
11201 example, no @code{m4__file__} is defined.
11202 @end defmac
11204 @defmac __oline__
11205 @MSindex __oline__
11206 This is not technically a macro, but a feature of Autom4te.  The
11207 sequence @code{__oline__} can be used similarly to the other m4sugar
11208 location macros, but rather than expanding to the location of the input
11209 file, it is translated to the line number where it appears in the output
11210 file after all other M4 expansions.
11211 @end defmac
11213 @defmac dnl
11214 @MSindex dnl
11215 This macro kept its original name: no @code{m4_dnl} is defined.
11216 @end defmac
11218 @defmac m4_bpatsubst (@var{string}, @var{regexp}, @ovar{replacement})
11219 @msindex{bpatsubst}
11220 This macro corresponds to @code{patsubst}.  The name @code{m4_patsubst}
11221 is kept for future versions of M4sugar, once GNU M4 2.0 is
11222 released and supports extended regular expression syntax.
11223 @end defmac
11225 @defmac m4_bregexp (@var{string}, @var{regexp}, @ovar{replacement})
11226 @msindex{bregexp}
11227 This macro corresponds to @code{regexp}.  The name @code{m4_regexp}
11228 is kept for future versions of M4sugar, once GNU M4 2.0 is
11229 released and supports extended regular expression syntax.
11230 @end defmac
11232 @defmac m4_copy (@var{source}, @var{dest})
11233 @defmacx m4_copy_force (@var{source}, @var{dest})
11234 @defmacx m4_rename (@var{source}, @var{dest})
11235 @defmacx m4_rename_force (@var{source}, @var{dest})
11236 @msindex{copy}
11237 @msindex{copy_force}
11238 @msindex{rename}
11239 @msindex{rename_force}
11240 These macros aren't directly builtins, but are closely related to
11241 @code{m4_pushdef} and @code{m4_defn}.  @code{m4_copy} and
11242 @code{m4_rename} ensure that @var{dest} is undefined, while
11243 @code{m4_copy_force} and @code{m4_rename_force} overwrite any existing
11244 definition.  All four macros then proceed to copy the entire pushdef
11245 stack of definitions of @var{source} over to @var{dest}.  @code{m4_copy}
11246 and @code{m4_copy_force} preserve the source (including in the special
11247 case where @var{source} is undefined), while @code{m4_rename} and
11248 @code{m4_rename_force} undefine the original macro name (making it an
11249 error to rename an undefined @var{source}).
11251 Note that attempting to invoke a renamed macro might not work, since the
11252 macro may have a dependence on helper macros accessed via composition of
11253 @samp{$0} but that were not also renamed; likewise, other macros may
11254 have a hard-coded dependence on @var{source} and could break if
11255 @var{source} has been deleted.  On the other hand, it is always safe to
11256 rename a macro to temporarily move it out of the way, then rename it
11257 back later to restore original semantics.
11258 @end defmac
11260 @defmac m4_defn (@var{macro}@dots{})
11261 @msindex{defn}
11262 This macro fails if @var{macro} is not defined, even when using older
11263 versions of M4 that did not warn.  See @code{m4_undefine}.
11264 Unfortunately, in order to support these older versions of M4, there are
11265 some situations involving unbalanced quotes where concatenating multiple
11266 macros together will work in newer M4 but not in m4sugar; use
11267 quadrigraphs to work around this.
11268 @end defmac
11270 @defmac m4_divert (@var{diversion})
11271 @msindex{divert}
11272 M4sugar relies heavily on diversions, so rather than behaving as a
11273 primitive, @code{m4_divert} behaves like:
11274 @example
11275 m4_divert_pop()m4_divert_push([@var{diversion}])
11276 @end example
11277 @noindent
11278 @xref{Diversion support}, for more details about the use of the
11279 diversion stack.  In particular, this implies that @var{diversion}
11280 should be a named diversion rather than a raw number.  But be aware that
11281 it is seldom necessary to explicitly change the diversion stack, and
11282 that when done incorrectly, it can lead to syntactically invalid
11283 scripts.
11284 @end defmac
11286 @defmac m4_dumpdef (@var{name}@dots{})
11287 @defmacx m4_dumpdefs (@var{name}@dots{})
11288 @msindex{dumpdef}
11289 @msindex{dumpdefs}
11290 @code{m4_dumpdef} is like the M4 builtin, except that this version
11291 requires at least one argument, output always goes to standard error
11292 rather than the current debug file, no sorting is done on multiple
11293 arguments, and an error is issued if any
11294 @var{name} is undefined.  @code{m4_dumpdefs} is a convenience macro that
11295 calls @code{m4_dumpdef} for all of the
11296 @code{m4_pushdef} stack of definitions, starting with the current, and
11297 silently does nothing if @var{name} is undefined.
11299 Unfortunately, due to a limitation in M4 1.4.x, any macro defined as a
11300 builtin is output as the empty string.  This behavior is rectified by
11301 using M4 1.6 or newer.  However, this behavior difference means that
11302 @code{m4_dumpdef} should only be used while developing m4sugar macros,
11303 and never in the final published form of a macro.
11304 @end defmac
11306 @defmac m4_esyscmd_s (@var{command})
11307 @msindex{esyscmd_s}
11308 Like @code{m4_esyscmd}, this macro expands to the result of running
11309 @var{command} in a shell.  The difference is that any trailing newlines
11310 are removed, so that the output behaves more like shell command
11311 substitution.
11312 @end defmac
11314 @defmac m4_exit (@var{exit-status})
11315 @msindex{exit}
11316 This macro corresponds to @code{m4exit}.
11317 @end defmac
11319 @defmac m4_if (@var{comment})
11320 @defmacx m4_if (@var{string-1}, @var{string-2}, @var{equal}, @ovar{not-equal})
11321 @defmacx m4_if (@var{string-1}, @var{string-2}, @var{equal-1}, @
11322   @var{string-3}, @var{string-4}, @var{equal-2}, @dots{}, @ovar{not-equal})
11323 @msindex{if}
11324 This macro corresponds to @code{ifelse}.  @var{string-1} and
11325 @var{string-2} are compared literally, so usually one of the two
11326 arguments is passed unquoted.  @xref{Conditional constructs}, for more
11327 conditional idioms.
11328 @end defmac
11330 @defmac m4_include (@var{file})
11331 @defmacx m4_sinclude (@var{file})
11332 @msindex{include}
11333 @msindex{sinclude}
11334 Like the M4 builtins, but warn against multiple inclusions of @var{file}.
11335 @end defmac
11337 @defmac m4_mkstemp (@var{template})
11338 @defmacx m4_maketemp (@var{template})
11339 @msindex{maketemp}
11340 @msindex{mkstemp}
11341 Posix requires @code{maketemp} to replace the trailing @samp{X}
11342 characters in @var{template} with the process id, without regards to the
11343 existence of a file by that name, but this a security hole.  When this
11344 was pointed out to the Posix folks, they agreed to invent a new macro
11345 @code{mkstemp} that always creates a uniquely named file, but not all
11346 versions of GNU M4 support the new macro.  In M4sugar,
11347 @code{m4_maketemp} and @code{m4_mkstemp} are synonyms for each other,
11348 and both have the secure semantics regardless of which macro the
11349 underlying M4 provides.
11350 @end defmac
11352 @defmac m4_popdef (@var{macro}@dots{})
11353 @msindex{popdef}
11354 This macro fails if @var{macro} is not defined, even when using older
11355 versions of M4 that did not warn.  See @code{m4_undefine}.
11356 @end defmac
11358 @defmac m4_undefine (@var{macro}@dots{})
11359 @msindex{undefine}
11360 This macro fails if @var{macro} is not defined, even when using older
11361 versions of M4 that did not warn.  Use
11363 @example
11364 m4_ifdef([@var{macro}], [m4_undefine([@var{macro}])])
11365 @end example
11367 @noindent
11368 if you are not sure whether @var{macro} is defined.
11369 @end defmac
11371 @defmac m4_undivert (@var{diversion}@dots{})
11372 @msindex{undivert}
11373 Unlike the M4 builtin, at least one @var{diversion} must be specified.
11374 Also, since the M4sugar diversion stack prefers named
11375 diversions, the use of @code{m4_undivert} to include files is risky.
11376 @xref{Diversion support}, for more details about the use of the
11377 diversion stack.  But be aware that it is seldom necessary to explicitly
11378 change the diversion stack, and that when done incorrectly, it can lead
11379 to syntactically invalid scripts.
11380 @end defmac
11382 @defmac m4_wrap (@var{text})
11383 @defmacx m4_wrap_lifo (@var{text})
11384 @msindex{wrap}
11385 @msindex{wrap_lifo}
11386 These macros correspond to @code{m4wrap}.  Posix requires arguments of
11387 multiple wrap calls to be reprocessed at EOF in the same order
11388 as the original calls (first-in, first-out).  GNU M4 versions
11389 through 1.4.10, however, reprocess them in reverse order (last-in,
11390 first-out).  Both orders are useful, therefore, you can rely on
11391 @code{m4_wrap} to provide FIFO semantics and @code{m4_wrap_lifo} for
11392 LIFO semantics, regardless of the underlying GNU M4 version.
11394 Unlike the GNU M4 builtin, these macros only recognize one
11395 argument, and avoid token pasting between consecutive invocations.  On
11396 the other hand, nested calls to @code{m4_wrap} from within wrapped text
11397 work just as in the builtin.
11398 @end defmac
11401 @node Diagnostic Macros
11402 @subsection Diagnostic messages from M4sugar
11403 @cindex Messages, from @command{M4sugar}
11405 When macros statically diagnose abnormal situations, benign or fatal,
11406 they should report them using these macros.  For issuing dynamic issues,
11407 i.e., when @command{configure} is run, see @ref{Printing Messages}.
11409 @defmac m4_assert (@var{expression}, @dvar{exit-status, 1})
11410 @msindex{assert}
11411 Assert that the arithmetic @var{expression} evaluates to non-zero.
11412 Otherwise, issue a fatal error, and exit @command{autom4te} with
11413 @var{exit-status}.
11414 @end defmac
11416 @defmac m4_errprintn (@var{message})
11417 @msindex{errprintn}
11418 Similar to the builtin @code{m4_errprint}, except that a newline is
11419 guaranteed after @var{message}.
11420 @end defmac
11422 @anchor{m4_fatal}
11423 @defmac m4_fatal (@var{message})
11424 @msindex{fatal}
11425 Report a severe error @var{message} prefixed with the current location,
11426 and have @command{autom4te} die.
11427 @end defmac
11429 @defmac m4_location
11430 @msindex{location}
11431 Useful as a prefix in a message line.  Short for:
11432 @example
11433 __file__:__line__
11434 @end example
11435 @end defmac
11437 @anchor{m4_warn}
11438 @defmac m4_warn (@var{category}, @var{message})
11439 @msindex{warn}
11440 Report @var{message} as a warning (or as an error if requested by the
11441 user) if warnings of the @var{category} are turned on.  If the message
11442 is emitted, it is prefixed with the current location, and followed by a
11443 call trace of all macros defined via @code{AC_DEFUN} used to get to the
11444 current expansion.  You are encouraged to use standard categories, which
11445 currently include:
11447 @table @samp
11448 @item all
11449 messages that don't fall into one of the following categories.  Use of an
11450 empty @var{category} is equivalent.
11452 @item cross
11453 related to cross compilation issues.
11455 @item obsolete
11456 use of an obsolete construct.
11458 @item syntax
11459 dubious syntactic constructs, incorrectly ordered macro calls.
11460 @end table
11461 @end defmac
11464 @node Diversion support
11465 @subsection Diversion support
11467 M4sugar makes heavy use of diversions under the hood, because it is
11468 often the case that
11469 text that must appear early in the output is not discovered until late
11470 in the input.  Additionally, some of the topological sorting algorithms
11471 used in resolving macro dependencies use diversions.  However, most
11472 macros should not need to change diversions directly, but rather rely on
11473 higher-level M4sugar macros to manage diversions transparently.  If you
11474 change diversions improperly, you risk generating a syntactically
11475 invalid script, because an incorrect diversion will violate assumptions
11476 made by many macros about whether prerequisite text has been previously
11477 output.  In short, if you manually change the diversion, you should not
11478 expect any macros provided by the Autoconf package to work until you
11479 have restored the diversion stack back to its original state.
11481 In the rare case that it is necessary to write a macro that explicitly
11482 outputs text to a different diversion, it is important to be aware of an
11483 M4 limitation regarding diversions: text only goes to a diversion if it
11484 is not part of argument collection.  Therefore, any macro that changes
11485 the current diversion cannot be used as an unquoted argument to another
11486 macro, but must be expanded at the top level.  The macro
11487 @code{m4_expand} will diagnose any attempt to change diversions, since
11488 it is generally useful only as an argument to another macro.  The
11489 following example shows what happens when diversion manipulation is
11490 attempted within macro arguments:
11492 @example
11493 m4_do([normal text]
11494 m4_divert_push([KILL])unwanted[]m4_divert_pop([KILL])
11495 [m4_divert_push([KILL])discarded[]m4_divert_pop([KILL])])dnl
11496 @result{}normal text
11497 @result{}unwanted
11498 @end example
11500 @noindent
11501 Notice that the unquoted text @code{unwanted} is output, even though it
11502 was processed while the current diversion was @code{KILL}, because it
11503 was collected as part of the argument to @code{m4_do}.  However, the
11504 text @code{discarded} disappeared as desired, because the diversion
11505 changes were single-quoted, and were not expanded until the top-level
11506 rescan of the output of @code{m4_do}.
11508 To make diversion management easier, M4sugar uses the concept of named
11509 diversions.  Rather than using diversion numbers directly, it is nicer
11510 to associate a name with each diversion.  The diversion number associated
11511 with a particular diversion name is an implementation detail, and a
11512 syntax warning is issued if a diversion number is used instead of a
11513 name.  In general, you should not output text
11514 to a named diversion until after calling the appropriate initialization
11515 routine for your language (@code{m4_init}, @code{AS_INIT},
11516 @code{AT_INIT}, @dots{}), although there are some exceptions documented
11517 below.
11519 M4sugar defines two named diversions.
11520 @table @code
11521 @item KILL
11522 Text written to this diversion is discarded.  This is the default
11523 diversion once M4sugar is initialized.
11524 @item GROW
11525 This diversion is used behind the scenes by topological sorting macros,
11526 such as @code{AC_REQUIRE}.
11527 @end table
11529 M4sh adds several more named diversions.
11530 @table @code
11531 @item BINSH
11532 This diversion is reserved for the @samp{#!} interpreter line.
11533 @item HEADER-REVISION
11534 This diversion holds text from @code{AC_REVISION}.
11535 @item HEADER-COMMENT
11536 This diversion holds comments about the purpose of a file.
11537 @item HEADER-COPYRIGHT
11538 This diversion is managed by @code{AC_COPYRIGHT}.
11539 @item M4SH-SANITIZE
11540 This diversion contains M4sh sanitization code, used to ensure M4sh is
11541 executing in a reasonable shell environment.
11542 @item M4SH-INIT
11543 This diversion contains M4sh initialization code, initializing variables
11544 that are required by other M4sh macros.
11545 @item BODY
11546 This diversion contains the body of the shell code, and is the default
11547 diversion once M4sh is initialized.
11548 @end table
11550 Autotest inherits diversions from M4sh, and changes the default
11551 diversion from @code{BODY} back to @code{KILL}.  It also adds several
11552 more named diversions, with the following subset designed for developer
11553 use.
11554 @table @code
11555 @item PREPARE_TESTS
11556 This diversion contains initialization sequences which are executed
11557 after @file{atconfig} and @file{atlocal}, and after all command line
11558 arguments have been parsed, but prior to running any tests.  It can be
11559 used to set up state that is required across all tests.  This diversion
11560 will work even before @code{AT_INIT}.
11561 @end table
11563 Autoconf inherits diversions from M4sh, and adds the following named
11564 diversions which developers can utilize.
11565 @table @code
11566 @item DEFAULTS
11567 This diversion contains shell variable assignments to set defaults that
11568 must be in place before arguments are parsed.  This diversion is placed
11569 early enough in @file{configure} that it is unsafe to expand any
11570 autoconf macros into this diversion.
11571 @item HELP_ENABLE
11572 If @code{AC_PRESERVE_HELP_ORDER} was used, then text placed in this
11573 diversion will be included as part of a quoted here-doc providing all of
11574 the @option{--help} output of @file{configure} related to options
11575 created by @code{AC_ARG_WITH} and @code{AC_ARG_ENABLE}.
11576 @item INIT_PREPARE
11577 This diversion occurs after all command line options have been parsed,
11578 but prior to the main body of the @file{configure} script.  This
11579 diversion is the last chance to insert shell code such as variable
11580 assignments or shell function declarations that will used by the
11581 expansion of other macros.
11582 @end table
11584 For now, the remaining named diversions of Autoconf, Autoheader, and
11585 Autotest are not documented.  In other words,
11586 intentionally outputting text into an undocumented diversion is subject
11587 to breakage in a future release of Autoconf.
11589 @defmac m4_cleardivert (@var{diversion}@dots{})
11590 @msindex{cleardivert}
11591 Permanently discard any text that has been diverted into
11592 @var{diversion}.
11593 @end defmac
11595 @defmac m4_divert_once (@var{diversion}, @ovar{content})
11596 @msindex{divert_once}
11597 Similar to @code{m4_divert_text}, except that @var{content} is only
11598 output to @var{diversion} if this is the first time that
11599 @code{m4_divert_once} has been called with its particular arguments.
11600 @end defmac
11602 @defmac m4_divert_pop (@ovar{diversion})
11603 @msindex{divert_pop}
11604 If provided, check that the current diversion is indeed @var{diversion}.
11605 Then change to the diversion located earlier on the stack, giving an
11606 error if an attempt is made to pop beyond the initial m4sugar diversion
11607 of @code{KILL}.
11608 @end defmac
11610 @defmac m4_divert_push (@var{diversion})
11611 @msindex{divert_push}
11612 Remember the former diversion on the diversion stack, and output
11613 subsequent text into @var{diversion}.  M4sugar maintains a diversion
11614 stack, and issues an error if there is not a matching pop for every
11615 push.
11616 @end defmac
11618 @defmac m4_divert_text (@var{diversion}, @ovar{content})
11619 @msindex{divert_text}
11620 Output @var{content} and a newline into @var{diversion}, without
11621 affecting the current diversion.  Shorthand for:
11622 @example
11623 m4_divert_push([@var{diversion}])@var{content}
11624 m4_divert_pop([@var{diversion}])dnl
11625 @end example
11627 One use of @code{m4_divert_text} is to develop two related macros, where
11628 macro @samp{MY_A} does the work, but adjusts what work is performed
11629 based on whether the optional macro @samp{MY_B} has also been expanded.
11630 Of course, it is possible to use @code{AC_BEFORE} within @code{MY_A} to
11631 require that @samp{MY_B} occurs first, if it occurs at all.  But this
11632 imposes an ordering restriction on the user; it would be nicer if macros
11633 @samp{MY_A} and @samp{MY_B} can be invoked in either order.  The trick
11634 is to let @samp{MY_B} leave a breadcrumb in an early diversion, which
11635 @samp{MY_A} can then use to determine whether @samp{MY_B} has been
11636 expanded.
11638 @example
11639 AC_DEFUN([MY_A],
11640 [# various actions
11641 if test -n "$b_was_used"; then
11642   # extra action
11643 fi])
11644 AC_DEFUN([MY_B],
11645 [AC_REQUIRE([MY_A])dnl
11646 m4_divert_text([INIT_PREPARE], [b_was_used=true])])
11647 @end example
11649 @end defmac
11651 @defmac m4_init
11652 @msindex{init}
11653 Initialize the M4sugar environment, setting up the default named
11654 diversion to be @code{KILL}.
11655 @end defmac
11657 @node Conditional constructs
11658 @subsection Conditional constructs
11660 The following macros provide additional conditional constructs as
11661 convenience wrappers around @code{m4_if}.
11663 @defmac m4_bmatch (@var{string}, @var{regex-1}, @var{value-1}, @
11664   @ovar{regex-2}, @ovar{value-2}, @dots{}, @ovar{default})
11665 @msindex{bmatch}
11666 The string @var{string} is repeatedly compared against a series of
11667 @var{regex} arguments; if a match is found, the expansion is the
11668 corresponding @var{value}, otherwise, the macro moves on to the next
11669 @var{regex}.  If no @var{regex} match, then the result is the optional
11670 @var{default}, or nothing.
11671 @end defmac
11673 @defmac m4_bpatsubsts (@var{string}, @var{regex-1}, @var{subst-1}, @
11674   @ovar{regex-2}, @ovar{subst-2}, @dots{})
11675 @msindex{bpatsubsts}
11676 The string @var{string} is altered by @var{regex-1} and @var{subst-1},
11677 as if by:
11678 @example
11679 m4_bpatsubst([[@var{string}]], [@var{regex}], [@var{subst}])
11680 @end example
11682 @noindent
11683 The result of the substitution is then passed through the next set of
11684 @var{regex} and @var{subst}, and so forth.  An empty @var{subst} implies
11685 deletion of any matched portions in the current string.  Note that this
11686 macro over-quotes @var{string}; this behavior is intentional, so that
11687 the result of each step of the recursion remains as a quoted string.
11688 However, it means that anchors (@samp{^} and @samp{$} in the @var{regex}
11689 will line up with the extra quotations, and not the characters of the
11690 original string.  The overquoting is removed after the final
11691 substitution.
11692 @end defmac
11694 @defmac m4_case (@var{string}, @var{value-1}, @var{if-value-1}, @
11695   @ovar{value-2}, @ovar{if-value-2}, @dots{}, @ovar{default})
11696 @msindex{case}
11697 Test @var{string} against multiple @var{value} possibilities, resulting
11698 in the first @var{if-value} for a match, or in the optional
11699 @var{default}.  This is shorthand for:
11700 @example
11701 m4_if([@var{string}], [@var{value-1}], [@var{if-value-1}],
11702       [@var{string}], [@var{value-2}], [@var{if-value-2}], @dots{},
11703       [@var{default}])
11704 @end example
11705 @end defmac
11707 @defmac m4_cond (@var{test-1}, @var{value-1}, @var{if-value-1}, @
11708   @ovar{test-2}, @ovar{value-2}, @ovar{if-value-2}, @dots{}, @ovar{default})
11709 @msindex{cond}
11710 This macro was introduced in Autoconf 2.62.  Similar to @code{m4_if},
11711 except that each @var{test} is expanded only when it is encountered.
11712 This is useful for short-circuiting expensive tests; while @code{m4_if}
11713 requires all its strings to be expanded up front before doing
11714 comparisons, @code{m4_cond} only expands a @var{test} when all earlier
11715 tests have failed.
11717 For an example, these two sequences give the same result, but in the
11718 case where @samp{$1} does not contain a backslash, the @code{m4_cond}
11719 version only expands @code{m4_index} once, instead of five times, for
11720 faster computation if this is a common case for @samp{$1}.  Notice that
11721 every third argument is unquoted for @code{m4_if}, and quoted for
11722 @code{m4_cond}:
11724 @example
11725 m4_if(m4_index([$1], [\]), [-1], [$2],
11726       m4_eval(m4_index([$1], [\\]) >= 0), [1], [$2],
11727       m4_eval(m4_index([$1], [\$]) >= 0), [1], [$2],
11728       m4_eval(m4_index([$1], [\`]) >= 0), [1], [$3],
11729       m4_eval(m4_index([$1], [\"]) >= 0), [1], [$3],
11730       [$2])
11731 m4_cond([m4_index([$1], [\])], [-1], [$2],
11732         [m4_eval(m4_index([$1], [\\]) >= 0)], [1], [$2],
11733         [m4_eval(m4_index([$1], [\$]) >= 0)], [1], [$2],
11734         [m4_eval(m4_index([$1], [\`]) >= 0)], [1], [$3],
11735         [m4_eval(m4_index([$1], [\"]) >= 0)], [1], [$3],
11736         [$2])
11737 @end example
11738 @end defmac
11740 @defmac m4_default (@var{expr-1}, @var{expr-2})
11741 @defmacx m4_default_quoted (@var{expr-1}, @var{expr-2})
11742 @defmacx m4_default_nblank (@var{expr-1}, @ovar{expr-2})
11743 @defmacx m4_default_nblank_quoted (@var{expr-1}, @ovar{expr-2})
11744 @msindex{default}
11745 @msindex{default_quoted}
11746 @msindex{default_nblank}
11747 @msindex{default_nblank_quoted}
11748 If @var{expr-1} contains text, use it.  Otherwise, select @var{expr-2}.
11749 @code{m4_default} expands the result, while @code{m4_default_quoted}
11750 does not.  Useful for providing a fixed default if the expression that
11751 results in @var{expr-1} would otherwise be empty.  The difference
11752 between @code{m4_default} and @code{m4_default_nblank} is whether an
11753 argument consisting of just blanks (space, tab, newline) is
11754 significant.  When using the expanding versions, note that an argument
11755 may contain text but still expand to an empty string.
11757 @example
11758 m4_define([active], [ACTIVE])dnl
11759 m4_define([empty], [])dnl
11760 m4_define([demo1], [m4_default([$1], [$2])])dnl
11761 m4_define([demo2], [m4_default_quoted([$1], [$2])])dnl
11762 m4_define([demo3], [m4_default_nblank([$1], [$2])])dnl
11763 m4_define([demo4], [m4_default_nblank_quoted([$1], [$2])])dnl
11764 demo1([active], [default])
11765 @result{}ACTIVE
11766 demo1([], [active])
11767 @result{}ACTIVE
11768 demo1([empty], [text])
11769 @result{}
11770 -demo1([ ], [active])-
11771 @result{}- -
11772 demo2([active], [default])
11773 @result{}active
11774 demo2([], [active])
11775 @result{}active
11776 demo2([empty], [text])
11777 @result{}empty
11778 -demo2([ ], [active])-
11779 @result{}- -
11780 demo3([active], [default])
11781 @result{}ACTIVE
11782 demo3([], [active])
11783 @result{}ACTIVE
11784 demo3([empty], [text])
11785 @result{}
11786 -demo3([ ], [active])-
11787 @result{}-ACTIVE-
11788 demo4([active], [default])
11789 @result{}active
11790 demo4([], [active])
11791 @result{}active
11792 demo4([empty], [text])
11793 @result{}empty
11794 -demo4([ ], [active])-
11795 @result{}-active-
11796 @end example
11797 @end defmac
11799 @defmac m4_define_default (@var{macro}, @ovar{default-definition})
11800 @msindex{define_default}
11801 If @var{macro} does not already have a definition, then define it to
11802 @var{default-definition}.
11803 @end defmac
11805 @defmac m4_ifblank (@var{cond}, @ovar{if-blank}, @ovar{if-text})
11806 @defmacx m4_ifnblank (@var{cond}, @ovar{if-text}, @ovar{if-blank})
11807 @msindex{ifblank}
11808 @msindex{ifnblank}
11809 If @var{cond} is empty or consists only of blanks (space, tab, newline),
11810 then expand @var{if-blank}; otherwise, expand @var{if-text}.  Two
11811 variants exist, in order to make it easier to select the correct logical
11812 sense when using only two parameters.  Note that this is more efficient
11813 than the equivalent behavior of:
11814 @example
11815 m4_ifval(m4_normalize([@var{cond}]), @var{if-text}, @var{if-blank})
11816 @end example
11817 @end defmac
11819 @defmac m4_ifndef (@var{macro}, @var{if-not-defined}, @ovar{if-defined})
11820 @msindex{ifndef}
11821 This is shorthand for:
11822 @example
11823 m4_ifdef([@var{macro}], [@var{if-defined}], [@var{if-not-defined}])
11824 @end example
11825 @end defmac
11827 @defmac m4_ifset (@var{macro}, @ovar{if-true}, @ovar{if-false})
11828 @msindex{ifset}
11829 If @var{macro} is undefined, or is defined as the empty string, expand
11830 to @var{if-false}.  Otherwise, expands to @var{if-true}.  Similar to:
11831 @example
11832 m4_ifval(m4_defn([@var{macro}]), [@var{if-true}], [@var{if-false}])
11833 @end example
11834 @noindent
11835 except that it is not an error if @var{macro} is undefined.
11836 @end defmac
11838 @defmac m4_ifval (@var{cond}, @ovar{if-true}, @ovar{if-false})
11839 @msindex{ifval}
11840 Expands to @var{if-true} if @var{cond} is not empty, otherwise to
11841 @var{if-false}.  This is shorthand for:
11842 @example
11843 m4_if([@var{cond}], [], [@var{if-true}], [@var{if-false}])
11844 @end example
11845 @end defmac
11847 @defmac m4_ifvaln (@var{cond}, @ovar{if-true}, @ovar{if-false})
11848 @msindex{ifvaln}
11849 Similar to @code{m4_ifval}, except guarantee that a newline is present
11850 after any non-empty expansion.  Often followed by @code{dnl}.
11851 @end defmac
11853 @defmac m4_n (@var{text})
11854 @msindex{n}
11855 Expand to @var{text}, and add a newline if @var{text} is not empty.
11856 Often followed by @code{dnl}.
11857 @end defmac
11860 @node Looping constructs
11861 @subsection Looping constructs
11863 The following macros are useful in implementing recursive algorithms in
11864 M4, including loop operations.  An M4 list is formed by quoting a list
11865 of quoted elements; generally the lists are comma-separated, although
11866 @code{m4_foreach_w} is whitespace-separated.  For example, the list
11867 @samp{[[a], [b,c]]} contains two elements: @samp{[a]} and @samp{[b,c]}.
11868 It is common to see lists with unquoted elements when those elements are
11869 not likely to be macro names, as in @samp{[fputc_unlocked,
11870 fgetc_unlocked]}.
11872 Although not generally recommended, it is possible for quoted lists to
11873 have side effects; all side effects are expanded only once, and prior to
11874 visiting any list element.  On the other hand, the fact that unquoted
11875 macros are expanded exactly once means that macros without side effects
11876 can be used to generate lists.  For example,
11878 @example
11879 m4_foreach([i], [[1], [2], [3]m4_errprintn([hi])], [i])
11880 @error{}hi
11881 @result{}123
11882 m4_define([list], [[1], [2], [3]])
11883 @result{}
11884 m4_foreach([i], [list], [i])
11885 @result{}123
11886 @end example
11888 @defmac m4_argn (@var{n}, @ovar{arg}@dots{})
11889 @msindex{argn}
11890 Extracts argument @var{n} (larger than 0) from the remaining arguments.
11891 If there are too few arguments, the empty string is used.  For any
11892 @var{n} besides 1, this is more efficient than the similar
11893 @samp{m4_car(m4_shiftn([@var{n}], [], [@var{arg}@dots{}]))}.
11894 @end defmac
11896 @defmac m4_car (@var{arg}@dots{})
11897 @msindex{car}
11898 Expands to the quoted first @var{arg}.  Can be used with @code{m4_cdr}
11899 to recursively iterate
11900 through a list.  Generally, when using quoted lists of quoted elements,
11901 @code{m4_car} should be called without any extra quotes.
11902 @end defmac
11904 @defmac m4_cdr (@var{arg}@dots{})
11905 @msindex{cdr}
11906 Expands to a quoted list of all but the first @var{arg}, or the empty
11907 string if there was only one argument.  Generally, when using quoted
11908 lists of quoted elements, @code{m4_cdr} should be called without any
11909 extra quotes.
11911 For example, this is a simple implementation of @code{m4_map}; note how
11912 each iteration checks for the end of recursion, then merely applies the
11913 first argument to the first element of the list, then repeats with the
11914 rest of the list.  (The actual implementation in M4sugar is a bit more
11915 involved, to gain some speed and share code with @code{m4_map_sep}, and
11916 also to avoid expanding side effects in @samp{$2} twice).
11917 @example
11918 m4_define([m4_map], [m4_ifval([$2],
11919   [m4_apply([$1], m4_car($2))[]$0([$1], m4_cdr($2))])])dnl
11920 m4_map([ m4_eval], [[[1]], [[1+1]], [[10],[16]]])
11921 @result{} 1 2 a
11922 @end example
11923 @end defmac
11925 @defmac m4_for (@var{var}, @var{first}, @var{last}, @ovar{step}, @
11926   @var{expression})
11927 @msindex{for}
11928 Loop over the numeric values between @var{first} and @var{last}
11929 including bounds by increments of @var{step}.  For each iteration,
11930 expand @var{expression} with the numeric value assigned to @var{var}.
11931 If @var{step} is omitted, it defaults to @samp{1} or @samp{-1} depending
11932 on the order of the limits.  If given, @var{step} has to match this
11933 order.  The number of iterations is determined independently from
11934 definition of @var{var}; iteration cannot be short-circuited or
11935 lengthened by modifying @var{var} from within @var{expression}.
11936 @end defmac
11938 @defmac m4_foreach (@var{var}, @var{list}, @var{expression})
11939 @msindex{foreach}
11940 Loop over the comma-separated M4 list @var{list}, assigning each value
11941 to @var{var}, and expand @var{expression}.  The following example
11942 outputs two lines:
11944 @example
11945 m4_foreach([myvar], [[foo], [bar, baz]],
11946            [echo myvar
11947 ])dnl
11948 @result{}echo foo
11949 @result{}echo bar, baz
11950 @end example
11952 Note that for some forms of @var{expression}, it may be faster to use
11953 @code{m4_map_args}.
11954 @end defmac
11956 @anchor{m4_foreach_w}
11957 @defmac m4_foreach_w (@var{var}, @var{list}, @var{expression})
11958 @msindex{foreach_w}
11959 Loop over the white-space-separated list @var{list}, assigning each value
11960 to @var{var}, and expand @var{expression}.  If @var{var} is only
11961 referenced once in @var{expression}, it is more efficient to use
11962 @code{m4_map_args_w}.
11964 The deprecated macro @code{AC_FOREACH} is an alias of
11965 @code{m4_foreach_w}.
11966 @end defmac
11968 @defmac m4_map (@var{macro}, @var{list})
11969 @defmacx m4_mapall (@var{macro}, @var{list})
11970 @defmacx m4_map_sep (@var{macro}, @var{separator}, @var{list})
11971 @defmacx m4_mapall_sep (@var{macro}, @var{separator}, @var{list})
11972 @msindex{map}
11973 @msindex{mapall}
11974 @msindex{map_sep}
11975 @msindex{mapall_sep}
11976 Loop over the comma separated quoted list of argument descriptions in
11977 @var{list}, and invoke @var{macro} with the arguments.  An argument
11978 description is in turn a comma-separated quoted list of quoted elements,
11979 suitable for @code{m4_apply}.  The macros @code{m4_map} and
11980 @code{m4_map_sep} ignore empty argument descriptions, while
11981 @code{m4_mapall} and @code{m4_mapall_sep} invoke @var{macro} with no
11982 arguments.  The macros @code{m4_map_sep} and @code{m4_mapall_sep}
11983 additionally expand @var{separator} between invocations of @var{macro}.
11985 Note that @var{separator} is expanded, unlike in @code{m4_join}.  When
11986 separating output with commas, this means that the map result can be
11987 used as a series of arguments, by using a single-quoted comma as
11988 @var{separator}, or as a single string, by using a double-quoted comma.
11990 @example
11991 m4_map([m4_count], [])
11992 @result{}
11993 m4_map([ m4_count], [[],
11994                      [[1]],
11995                      [[1], [2]]])
11996 @result{} 1 2
11997 m4_mapall([ m4_count], [[],
11998                         [[1]],
11999                         [[1], [2]]])
12000 @result{} 0 1 2
12001 m4_map_sep([m4_eval], [,], [[[1+2]],
12002                             [[10], [16]]])
12003 @result{}3,a
12004 m4_map_sep([m4_echo], [,], [[[a]], [[b]]])
12005 @result{}a,b
12006 m4_count(m4_map_sep([m4_echo], [,], [[[a]], [[b]]]))
12007 @result{}2
12008 m4_map_sep([m4_echo], [[,]], [[[a]], [[b]]])
12009 @result{}a,b
12010 m4_count(m4_map_sep([m4_echo], [[,]], [[[a]], [[b]]]))
12011 @result{}1
12012 @end example
12013 @end defmac
12015 @defmac m4_map_args (@var{macro}, @var{arg}@dots{})
12016 @msindex{map_args}
12017 Repeatedly invoke @var{macro} with each successive @var{arg} as its only
12018 argument.  In the following example, three solutions are presented with
12019 the same expansion; the solution using @code{m4_map_args} is the most
12020 efficient.
12021 @example
12022 m4_define([active], [ACTIVE])dnl
12023 m4_foreach([var], [[plain], [active]], [ m4_echo(m4_defn([var]))])
12024 @result{} plain active
12025 m4_map([ m4_echo], [[[plain]], [[active]]])
12026 @result{} plain active
12027 m4_map_args([ m4_echo], [plain], [active])
12028 @result{} plain active
12029 @end example
12031 In cases where it is useful to operate on additional parameters besides
12032 the list elements, the macro @code{m4_curry} can be used in @var{macro}
12033 to supply the argument currying necessary to generate the desired
12034 argument list.  In the following example, @code{list_add_n} is more
12035 efficient than @code{list_add_x}.  On the other hand, using
12036 @code{m4_map_args_sep} can be even more efficient.
12038 @example
12039 m4_define([list], [[1], [2], [3]])dnl
12040 m4_define([add], [m4_eval(([$1]) + ([$2]))])dnl
12041 dnl list_add_n(N, ARG...)
12042 dnl Output a list consisting of each ARG added to N
12043 m4_define([list_add_n],
12044 [m4_shift(m4_map_args([,m4_curry([add], [$1])], m4_shift($@@)))])dnl
12045 list_add_n([1], list)
12046 @result{}2,3,4
12047 list_add_n([2], list)
12048 @result{}3,4,5
12049 m4_define([list_add_x],
12050 [m4_shift(m4_foreach([var], m4_dquote(m4_shift($@@)),
12051   [,add([$1],m4_defn([var]))]))])dnl
12052 list_add_x([1], list)
12053 @result{}2,3,4
12054 @end example
12055 @end defmac
12057 @defmac m4_map_args_pair (@var{macro}, @dvar{macro-end, macro}, @
12058   @var{arg}@dots{})
12059 @msindex{map_args_pair}
12060 For every pair of arguments @var{arg}, invoke @var{macro} with two
12061 arguments.  If there is an odd number of arguments, invoke
12062 @var{macro-end}, which defaults to @var{macro}, with the remaining
12063 argument.
12065 @example
12066 m4_map_args_pair([, m4_reverse], [], [1], [2], [3])
12067 @result{}, 2, 1, 3
12068 m4_map_args_pair([, m4_reverse], [, m4_dquote], [1], [2], [3])
12069 @result{}, 2, 1, [3]
12070 m4_map_args_pair([, m4_reverse], [, m4_dquote], [1], [2], [3], [4])
12071 @result{}, 2, 1, 4, 3
12072 @end example
12073 @end defmac
12075 @defmac m4_map_args_sep (@ovar{pre}, @ovar{post}, @ovar{sep}, @var{arg}@dots{})
12076 @msindex{map_args_sep}
12077 Expand the sequence @code{@var{pre}[@var{arg}]@var{post}} for each
12078 argument, additionally expanding @var{sep} between arguments.  One
12079 common use of this macro is constructing a macro call, where the opening
12080 and closing parentheses are split between @var{pre} and @var{post}; in
12081 particular, @code{m4_map_args([@var{macro}], [@var{arg}])} is equivalent
12082 to @code{m4_map_args_sep([@var{macro}(], [)], [], [@var{arg}])}.  This
12083 macro provides the most efficient means for iterating over an arbitrary
12084 list of arguments, particularly when repeatedly constructing a macro
12085 call with more arguments than @var{arg}.
12086 @end defmac
12088 @defmac m4_map_args_w (@var{string}, @ovar{pre}, @ovar{post}, @ovar{sep})
12089 @msindex{map_args_w}
12090 Expand the sequence @code{@var{pre}[word]@var{post}} for each word in
12091 the whitespace-separated @var{string}, additionally expanding @var{sep}
12092 between words.  This macro provides the most efficient means for
12093 iterating over a whitespace-separated string.  In particular,
12094 @code{m4_map_args_w([@var{string}], [@var{action}(], [)])} is more
12095 efficient than @code{m4_foreach_w([var], [@var{string}],
12096 [@var{action}(m4_defn([var]))])}.
12097 @end defmac
12099 @defmac m4_shiftn (@var{count}, @dots{})
12100 @defmacx m4_shift2 (@dots{})
12101 @defmacx m4_shift3 (@dots{})
12102 @msindex{shift2}
12103 @msindex{shift3}
12104 @msindex{shiftn}
12105 @code{m4_shiftn} performs @var{count} iterations of @code{m4_shift},
12106 along with validation that enough arguments were passed in to match the
12107 shift count, and that the count is positive.  @code{m4_shift2} and
12108 @code{m4_shift3} are specializations
12109 of @code{m4_shiftn}, introduced in Autoconf 2.62, and are more efficient
12110 for two and three shifts, respectively.
12111 @end defmac
12113 @defmac m4_stack_foreach (@var{macro}, @var{action})
12114 @defmacx m4_stack_foreach_lifo (@var{macro}, @var{action})
12115 @msindex{stack_foreach}
12116 @msindex{stack_foreach_lifo}
12117 For each of the @code{m4_pushdef} definitions of @var{macro}, expand
12118 @var{action} with the single argument of a definition of @var{macro}.
12119 @code{m4_stack_foreach} starts with the oldest definition, while
12120 @code{m4_stack_foreach_lifo} starts with the current definition.
12121 @var{action} should not push or pop definitions of @var{macro}, nor is
12122 there any guarantee that the current definition of @var{macro} matches
12123 the argument that was passed to @var{action}.  The macro @code{m4_curry}
12124 can be used if @var{action} needs more than one argument, although in
12125 that case it is more efficient to use @var{m4_stack_foreach_sep}.
12127 Due to technical limitations, there are a few low-level m4sugar
12128 functions, such as @code{m4_pushdef}, that cannot be used as the
12129 @var{macro} argument.
12131 @example
12132 m4_pushdef([a], [1])m4_pushdef([a], [2])dnl
12133 m4_stack_foreach([a], [ m4_incr])
12134 @result{} 2 3
12135 m4_stack_foreach_lifo([a], [ m4_curry([m4_substr], [abcd])])
12136 @result{} cd bcd
12137 @end example
12138 @end defmac
12140 @defmac m4_stack_foreach_sep (@var{macro}, @ovar{pre}, @ovar{post}, @ovar{sep})
12141 @defmacx m4_stack_foreach_sep_lifo (@var{macro}, @ovar{pre}, @ovar{post}, @
12142   @ovar{sep})
12143 @msindex{stack_foreach_sep}
12144 @msindex{stack_foreach_sep_lifo}
12145 Expand the sequence @code{@var{pre}[definition]@var{post}} for each
12146 @code{m4_pushdef} definition of @var{macro}, additionally expanding
12147 @var{sep} between definitions.  @code{m4_stack_foreach_sep} visits the
12148 oldest definition first, while @code{m4_stack_foreach_sep_lifo} visits
12149 the current definition first.  This macro provides the most efficient
12150 means for iterating over a pushdef stack.  In particular,
12151 @code{m4_stack_foreach([@var{macro}], [@var{action}])} is short for
12152 @code{m4_stack_foreach_sep([@var{macro}], [@var{action}(], [)])}.
12153 @end defmac
12155 @node Evaluation Macros
12156 @subsection Evaluation Macros
12158 The following macros give some control over the order of the evaluation
12159 by adding or removing levels of quotes.
12161 @defmac m4_apply (@var{macro}, @var{list})
12162 @msindex{apply}
12163 Apply the elements of the quoted, comma-separated @var{list} as the
12164 arguments to @var{macro}.  If @var{list} is empty, invoke @var{macro}
12165 without arguments.  Note the difference between @code{m4_indir}, which
12166 expects its first argument to be a macro name but can use names that are
12167 otherwise invalid, and @code{m4_apply}, where @var{macro} can contain
12168 other text, but must end in a valid macro name.
12169 @example
12170 m4_apply([m4_count], [])
12171 @result{}0
12172 m4_apply([m4_count], [[]])
12173 @result{}1
12174 m4_apply([m4_count], [[1], [2]])
12175 @result{}2
12176 m4_apply([m4_join], [[|], [1], [2]])
12177 @result{}1|2
12178 @end example
12179 @end defmac
12181 @defmac m4_count (@var{arg}, @dots{})
12182 @msindex{count}
12183 This macro returns the decimal count of the number of arguments it was
12184 passed.
12185 @end defmac
12187 @defmac m4_curry (@var{macro}, @var{arg}@dots{})
12188 @msindex{curry}
12189 This macro performs argument currying.  The expansion of this macro is
12190 another macro name that expects exactly one argument; that argument is
12191 then appended to the @var{arg} list, and then @var{macro} is expanded
12192 with the resulting argument list.
12194 @example
12195 m4_curry([m4_curry], [m4_reverse], [1])([2])([3])
12196 @result{}3, 2, 1
12197 @end example
12199 Unfortunately, due to a limitation in M4 1.4.x, it is not possible to
12200 pass the definition of a builtin macro as the argument to the output of
12201 @code{m4_curry}; the empty string is used instead of the builtin token.
12202 This behavior is rectified by using M4 1.6 or newer.
12203 @end defmac
12205 @defmac m4_do (@var{arg}, @dots{})
12206 @msindex{do}
12207 This macro loops over its arguments and expands each @var{arg} in
12208 sequence.  Its main use is for readability; it allows the use of
12209 indentation and fewer @code{dnl} to result in the same expansion.  This
12210 macro guarantees that no expansion will be concatenated with subsequent
12211 text; to achieve full concatenation, use @code{m4_unquote(m4_join([],
12212 @var{arg@dots{}}))}.
12214 @example
12215 m4_define([ab],[1])m4_define([bc],[2])m4_define([abc],[3])dnl
12216 m4_do([a],[b])c
12217 @result{}abc
12218 m4_unquote(m4_join([],[a],[b]))c
12219 @result{}3
12220 m4_define([a],[A])m4_define([b],[B])m4_define([c],[C])dnl
12221 m4_define([AB],[4])m4_define([BC],[5])m4_define([ABC],[6])dnl
12222 m4_do([a],[b])c
12223 @result{}ABC
12224 m4_unquote(m4_join([],[a],[b]))c
12225 @result{}3
12226 @end example
12227 @end defmac
12229 @defmac m4_dquote (@var{arg}, @dots{})
12230 @msindex{dquote}
12231 Return the arguments as a quoted list of quoted arguments.
12232 Conveniently, if there is just one @var{arg}, this effectively adds a
12233 level of quoting.
12234 @end defmac
12236 @defmac m4_dquote_elt (@var{arg}, @dots{})
12237 @msindex{dquote_elt}
12238 Return the arguments as a series of double-quoted arguments.  Whereas
12239 @code{m4_dquote} returns a single argument, @code{m4_dquote_elt} returns
12240 as many arguments as it was passed.
12241 @end defmac
12243 @defmac m4_echo (@var{arg}, @dots{})
12244 @msindex{echo}
12245 Return the arguments, with the same level of quoting.  Other than
12246 discarding whitespace after unquoted commas, this macro is a no-op.
12247 @end defmac
12249 @defmac m4_expand (@var{arg})
12250 @msindex{expand}
12251 Return the expansion of @var{arg} as a quoted string.  Whereas
12252 @code{m4_quote} is designed to collect expanded text into a single
12253 argument, @code{m4_expand} is designed to perform one level of expansion
12254 on quoted text.  One distinction is in the treatment of whitespace
12255 following a comma in the original @var{arg}.  Any time multiple
12256 arguments are collected into one with @code{m4_quote}, the M4 argument
12257 collection rules discard the whitespace.  However, with @code{m4_expand},
12258 whitespace is preserved, even after the expansion of macros contained in
12259 @var{arg}.  Additionally, @code{m4_expand} is able to expand text that
12260 would involve an unterminated comment, whereas expanding that same text
12261 as the argument to @code{m4_quote} runs into difficulty in finding the
12262 end of the argument.  Since manipulating diversions during argument
12263 collection is inherently unsafe, @code{m4_expand} issues an error if
12264 @var{arg} attempts to change the current diversion (@pxref{Diversion
12265 support}).
12267 @example
12268 m4_define([active], [ACT, IVE])dnl
12269 m4_define([active2], [[ACT, IVE]])dnl
12270 m4_quote(active, active)
12271 @result{}ACT,IVE,ACT,IVE
12272 m4_expand([active, active])
12273 @result{}ACT, IVE, ACT, IVE
12274 m4_quote(active2, active2)
12275 @result{}ACT, IVE,ACT, IVE
12276 m4_expand([active2, active2])
12277 @result{}ACT, IVE, ACT, IVE
12278 m4_expand([# m4_echo])
12279 @result{}# m4_echo
12280 m4_quote(# m4_echo)
12282 @result{}# m4_echo)
12283 @result{}
12284 @end example
12286 Note that @code{m4_expand} cannot handle an @var{arg} that expands to
12287 literal unbalanced quotes, but that quadrigraphs can be used when
12288 unbalanced output is necessary.  Likewise, unbalanced parentheses should
12289 be supplied with double quoting or a quadrigraph.
12291 @example
12292 m4_define([pattern], [[!@@<:@@]])dnl
12293 m4_define([bar], [BAR])dnl
12294 m4_expand([case $foo in
12295   m4_defn([pattern])@@:@}@@ bar ;;
12296   *[)] blah ;;
12297 esac])
12298 @result{}case $foo in
12299 @result{}  [![]) BAR ;;
12300 @result{}  *) blah ;;
12301 @result{}esac
12302 @end example
12303 @end defmac
12305 @defmac m4_ignore (@dots{})
12306 @msindex{ignore}
12307 This macro was introduced in Autoconf 2.62.  Expands to nothing,
12308 ignoring all of its arguments.  By itself, this isn't very useful.
12309 However, it can be used to conditionally ignore an arbitrary number of
12310 arguments, by deciding which macro name to apply to a list of arguments.
12311 @example
12312 dnl foo outputs a message only if [debug] is defined.
12313 m4_define([foo],
12314 [m4_ifdef([debug],[AC_MSG_NOTICE],[m4_ignore])([debug message])])
12315 @end example
12317 Note that for earlier versions of Autoconf, the macro @code{__gnu__} can
12318 serve the same purpose, although it is less readable.
12319 @end defmac
12321 @defmac m4_make_list (@var{arg}, @dots{})
12322 @msindex{make_list}
12323 This macro exists to aid debugging of M4sugar algorithms.  Its net
12324 effect is similar to @code{m4_dquote}---it produces a quoted list of
12325 quoted arguments, for each @var{arg}.  The difference is that this
12326 version uses a comma-newline separator instead of just comma, to improve
12327 readability of the list; with the result that it is less efficient than
12328 @code{m4_dquote}.
12329 @example
12330 m4_define([zero],[0])m4_define([one],[1])m4_define([two],[2])dnl
12331 m4_dquote(zero, [one], [[two]])
12332 @result{}[0],[one],[[two]]
12333 m4_make_list(zero, [one], [[two]])
12334 @result{}[0],
12335 @result{}[one],
12336 @result{}[[two]]
12337 m4_foreach([number], m4_dquote(zero, [one], [[two]]), [ number])
12338 @result{} 0 1 two
12339 m4_foreach([number], m4_make_list(zero, [one], [[two]]), [ number])
12340 @result{} 0 1 two
12341 @end example
12342 @end defmac
12344 @c m4_noquote is too dangerous to document - it invokes macros that
12345 @c probably rely on @samp{[]} nested quoting for proper operation.  The
12346 @c user should generally prefer m4_unquote instead.
12348 @defmac m4_quote (@var{arg}, @dots{})
12349 @msindex{quote}
12350 Return the arguments as a single entity, i.e., wrap them into a pair of
12351 quotes.  This effectively collapses multiple arguments into one,
12352 although it loses whitespace after unquoted commas in the process.
12353 @end defmac
12355 @defmac m4_reverse (@var{arg}, @dots{})
12356 @msindex{reverse}
12357 Outputs each argument with the same level of quoting, but in reverse
12358 order, and with space following each comma for readability.
12360 @example
12361 m4_define([active], [ACT,IVE])
12362 @result{}
12363 m4_reverse(active, [active])
12364 @result{}active, IVE, ACT
12365 @end example
12366 @end defmac
12368 @defmac m4_unquote (@var{arg}, @dots{})
12369 @msindex{unquote}
12370 This macro was introduced in Autoconf 2.62.  Expand each argument,
12371 separated by commas.  For a single @var{arg}, this effectively removes a
12372 layer of quoting, and @code{m4_unquote([@var{arg}])} is more efficient
12373 than the equivalent @code{m4_do([@var{arg}])}.  For multiple arguments,
12374 this results in an unquoted list of expansions.  This is commonly used
12375 with @code{m4_split}, in order to convert a single quoted list into a
12376 series of quoted elements.
12377 @end defmac
12379 The following example aims at emphasizing the difference between several
12380 scenarios: not using these macros, using @code{m4_defn}, using
12381 @code{m4_quote}, using @code{m4_dquote}, and using @code{m4_expand}.
12383 @example
12384 $ @kbd{cat example.m4}
12385 dnl Overquote, so that quotes are visible.
12386 m4_define([show], [$[]1 = [$1], $[]@@ = [$@@]])
12387 m4_define([a], [A])
12388 m4_define([mkargs], [1, 2[,] 3])
12389 m4_define([arg1], [[$1]])
12390 m4_divert([0])dnl
12391 show(a, b)
12392 show([a, b])
12393 show(m4_quote(a, b))
12394 show(m4_dquote(a, b))
12395 show(m4_expand([a, b]))
12397 arg1(mkargs)
12398 arg1([mkargs])
12399 arg1(m4_defn([mkargs]))
12400 arg1(m4_quote(mkargs))
12401 arg1(m4_dquote(mkargs))
12402 arg1(m4_expand([mkargs]))
12403 $ @kbd{autom4te -l m4sugar example.m4}
12404 $1 = A, $@@ = [A],[b]
12405 $1 = a, b, $@@ = [a, b]
12406 $1 = A,b, $@@ = [A,b]
12407 $1 = [A],[b], $@@ = [[A],[b]]
12408 $1 = A, b, $@@ = [A, b]
12411 mkargs
12412 1, 2[,] 3
12413 1,2, 3
12414 [1],[2, 3]
12415 1, 2, 3
12416 @end example
12419 @node Text processing Macros
12420 @subsection String manipulation in M4
12422 The following macros may be used to manipulate strings in M4.  Many of
12423 the macros in this section intentionally result in quoted strings as
12424 output, rather than subjecting the arguments to further expansions.  As
12425 a result, if you are manipulating text that contains active M4
12426 characters, the arguments are passed with single quoting rather than
12427 double.
12429 @defmac m4_append (@var{macro-name}, @var{string}, @ovar{separator})
12430 @defmacx m4_append_uniq (@var{macro-name}, @var{string}, @ovar{separator} @
12431   @ovar{if-uniq}, @ovar{if-duplicate})
12432 @msindex{append}
12433 @msindex{append_uniq}
12434 Redefine @var{macro-name} to its former contents with @var{separator}
12435 and @var{string} added at the end.  If @var{macro-name} was undefined
12436 before (but not if it was defined but empty), then no @var{separator} is
12437 added.  As of Autoconf 2.62, neither @var{string} nor @var{separator}
12438 are expanded during this macro; instead, they are expanded when
12439 @var{macro-name} is invoked.
12441 @code{m4_append} can be used to grow strings, and @code{m4_append_uniq}
12442 to grow strings without duplicating substrings.  Additionally,
12443 @code{m4_append_uniq} takes two optional parameters as of Autoconf 2.62;
12444 @var{if-uniq} is expanded if @var{string} was appended, and
12445 @var{if-duplicate} is expanded if @var{string} was already present.
12446 Also, @code{m4_append_uniq} warns if @var{separator} is not empty, but
12447 occurs within @var{string}, since that can lead to duplicates.
12449 Note that @code{m4_append} can scale linearly in the length of the final
12450 string, depending on the quality of the underlying M4 implementation,
12451 while @code{m4_append_uniq} has an inherent quadratic scaling factor.
12452 If an algorithm can tolerate duplicates in the final string, use the
12453 former for speed.  If duplicates must be avoided, consider using
12454 @code{m4_set_add} instead (@pxref{Set manipulation Macros}).
12456 @example
12457 m4_define([active], [ACTIVE])dnl
12458 m4_append([sentence], [This is an])dnl
12459 m4_append([sentence], [ active ])dnl
12460 m4_append([sentence], [symbol.])dnl
12461 sentence
12462 @result{}This is an ACTIVE symbol.
12463 m4_undefine([active])dnl
12464 @result{}This is an active symbol.
12465 m4_append_uniq([list], [one], [, ], [new], [existing])
12466 @result{}new
12467 m4_append_uniq([list], [one], [, ], [new], [existing])
12468 @result{}existing
12469 m4_append_uniq([list], [two], [, ], [new], [existing])
12470 @result{}new
12471 m4_append_uniq([list], [three], [, ], [new], [existing])
12472 @result{}new
12473 m4_append_uniq([list], [two], [, ], [new], [existing])
12474 @result{}existing
12475 list
12476 @result{}one, two, three
12477 m4_dquote(list)
12478 @result{}[one],[two],[three]
12479 m4_append([list2], [one], [[, ]])dnl
12480 m4_append_uniq([list2], [two], [[, ]])dnl
12481 m4_append([list2], [three], [[, ]])dnl
12482 list2
12483 @result{}one, two, three
12484 m4_dquote(list2)
12485 @result{}[one, two, three]
12486 @end example
12487 @end defmac
12489 @defmac m4_append_uniq_w (@var{macro-name}, @var{strings})
12490 @msindex{append_uniq_w}
12491 This macro was introduced in Autoconf 2.62.  It is similar to
12492 @code{m4_append_uniq}, but treats @var{strings} as a whitespace
12493 separated list of words to append, and only appends unique words.
12494 @var{macro-name} is updated with a single space between new words.
12495 @example
12496 m4_append_uniq_w([numbers], [1 1 2])dnl
12497 m4_append_uniq_w([numbers], [ 2 3 ])dnl
12498 numbers
12499 @result{}1 2 3
12500 @end example
12501 @end defmac
12503 @defmac m4_chomp (@var{string})
12504 @defmacx m4_chomp_all (@var{string})
12505 @msindex{chomp}
12506 @msindex{chomp_all}
12507 Output @var{string} in quotes, but without a trailing newline.  The
12508 macro @code{m4_chomp} is slightly faster, and removes at most one
12509 newline; the macro @code{m4_chomp_all} removes all consecutive trailing
12510 newlines.  Unlike @code{m4_flatten}, embedded newlines are left intact,
12511 and backslash does not influence the result.
12512 @end defmac
12514 @defmac m4_combine (@ovar{separator}, @var{prefix-list}, @ovar{infix}, @
12515   @var{suffix-1}, @ovar{suffix-2}, @dots{})
12516 @msindex{combine}
12517 This macro produces a quoted string containing the pairwise combination
12518 of every element of the quoted, comma-separated @var{prefix-list}, and
12519 every element from the @var{suffix} arguments.  Each pairwise
12520 combination is joined with @var{infix} in the middle, and successive
12521 pairs are joined by @var{separator}.  No expansion occurs on any of the
12522 arguments.  No output occurs if either the @var{prefix} or @var{suffix}
12523 list is empty, but the lists can contain empty elements.
12524 @example
12525 m4_define([a], [oops])dnl
12526 m4_combine([, ], [[a], [b], [c]], [-], [1], [2], [3])
12527 @result{}a-1, a-2, a-3, b-1, b-2, b-3, c-1, c-2, c-3
12528 m4_combine([, ], [[a], [b]], [-])
12529 @result{}
12530 m4_combine([, ], [[a], [b]], [-], [])
12531 @result{}a-, b-
12532 m4_combine([, ], [], [-], [1], [2])
12533 @result{}
12534 m4_combine([, ], [[]], [-], [1], [2])
12535 @result{}-1, -2
12536 @end example
12537 @end defmac
12539 @defmac m4_escape (@var{string})
12540 @msindex{escape}
12541 Convert all instances of @samp{[}, @samp{]}, @samp{#}, and @samp{$}
12542 within @var{string} into their respective quadrigraphs.  The result is
12543 still a quoted string.
12544 @end defmac
12546 @defmac m4_flatten (@var{string})
12547 @msindex{flatten}
12548 Flatten @var{string} into a single line.  Delete all backslash-newline
12549 pairs, and replace all remaining newlines with a space.  The result is
12550 still a quoted string.
12551 @end defmac
12553 @defmac m4_join (@ovar{separator}, @var{args}@dots{})
12554 @defmacx m4_joinall (@ovar{separator}, @var{args}@dots{})
12555 @msindex{join}
12556 @msindex{joinall}
12557 Concatenate each @var{arg}, separated by @var{separator}.
12558 @code{joinall} uses every argument, while @code{join} omits empty
12559 arguments so that there are no back-to-back separators in the output.
12560 The result is a quoted string.
12561 @example
12562 m4_define([active], [ACTIVE])dnl
12563 m4_join([|], [one], [], [active], [two])
12564 @result{}one|active|two
12565 m4_joinall([|], [one], [], [active], [two])
12566 @result{}one||active|two
12567 @end example
12569 Note that if all you intend to do is join @var{args} with commas between
12570 them, to form a quoted list suitable for @code{m4_foreach}, it is more
12571 efficient to use @code{m4_dquote}.
12572 @end defmac
12574 @defmac m4_newline (@ovar{text})
12575 @msindex{newline}
12576 This macro was introduced in Autoconf 2.62, and expands to a newline,
12577 followed by any @var{text}.
12578 It is primarily useful for maintaining macro formatting, and ensuring
12579 that M4 does not discard leading whitespace during argument collection.
12580 @end defmac
12582 @defmac m4_normalize (@var{string})
12583 @msindex{normalize}
12584 Remove leading and trailing spaces and tabs, sequences of
12585 backslash-then-newline, and replace multiple spaces, tabs, and newlines
12586 with a single space.  This is a combination of @code{m4_flatten} and
12587 @code{m4_strip}.  To determine if @var{string} consists only of bytes
12588 that would be removed by @code{m4_normalize}, you can use
12589 @code{m4_ifblank}.
12590 @end defmac
12592 @defmac m4_re_escape (@var{string})
12593 @msindex{re_escape}
12594 Backslash-escape all characters in @var{string} that are active in
12595 regexps.
12596 @end defmac
12598 @c We cannot use @dvar because the macro expansion mistreats backslashes.
12599 @defmac m4_split (@var{string}, @r{[}@var{regexp} = @samp{[\t ]+}@r{]})
12600 @msindex{split}
12601 Split @var{string} into an M4 list of elements quoted by @samp{[} and
12602 @samp{]}, while keeping white space at the beginning and at the end.
12603 If @var{regexp} is given, use it instead of @samp{[\t ]+} for splitting.
12604 If @var{string} is empty, the result is an empty list.
12605 @end defmac
12607 @defmac m4_strip (@var{string})
12608 @msindex{strip}
12609 Strip whitespace from @var{string}.  Sequences of spaces and tabs are
12610 reduced to a single space, then leading and trailing spaces are removed.
12611 The result is still a quoted string.  Note that this does not interfere
12612 with newlines; if you want newlines stripped as well, consider
12613 @code{m4_flatten}, or do it all at once with @code{m4_normalize}.  To
12614 quickly test if @var{string} has only whitespace, use @code{m4_ifblank}.
12615 @end defmac
12617 @defmac m4_text_box (@var{message}, @dvar{frame, -})
12618 @msindex{text_box}
12619 Add a text box around @var{message}, using @var{frame} as the border
12620 character above and below the message.  The @var{frame} argument must be
12621 a single byte, and does not support quadrigraphs.
12622 The frame correctly accounts for
12623 the subsequent expansion of @var{message}.  For example:
12624 @example
12625 m4_define([macro], [abc])dnl
12626 m4_text_box([macro])
12627 @result{}## --- ##
12628 @result{}## abc ##
12629 @result{}## --- ##
12630 @end example
12632 The @var{message} must contain balanced quotes and parentheses, although
12633 quadrigraphs can be used to work around this.
12634 @end defmac
12636 @defmac m4_text_wrap (@var{string}, @ovar{prefix}, @
12637   @dvar{prefix1, @var{prefix}}, @dvar{width, 79})
12638 @msindex{text_wrap}
12639 Break @var{string} into a series of whitespace-separated words, then
12640 output those words separated by spaces, and wrapping lines any time the
12641 output would exceed @var{width} columns.  If given, @var{prefix1} begins
12642 the first line, and @var{prefix} begins all wrapped lines.  If
12643 @var{prefix1} is longer than @var{prefix}, then the first line consists
12644 of just @var{prefix1}.  If @var{prefix} is longer than @var{prefix1},
12645 padding is inserted so that the first word of @var{string} begins at the
12646 same indentation as all wrapped lines.  Note that using literal tab
12647 characters in any of the arguments will interfere with the calculation
12648 of width.  No expansions occur on @var{prefix}, @var{prefix1}, or the
12649 words of @var{string}, although quadrigraphs are recognized.
12651 For some examples:
12652 @example
12653 m4_text_wrap([Short string */], [   ], [/* ], [20])
12654 @result{}/* Short string */
12655 m4_text_wrap([Much longer string */], [   ], [/* ], [20])
12656 @result{}/* Much longer
12657 @result{}   string */
12658 m4_text_wrap([Short doc.], [          ], [  --short ], [30])
12659 @result{}  --short Short doc.
12660 m4_text_wrap([Short doc.], [          ], [  --too-wide ], [30])
12661 @result{}  --too-wide
12662 @result{}          Short doc.
12663 m4_text_wrap([Super long documentation.], [     ],
12664              [  --too-wide ], 30)
12665 @result{}  --too-wide
12666 @result{}     Super long
12667 @result{}     documentation.
12668 @end example
12669 @end defmac
12671 @defmac m4_tolower (@var{string})
12672 @defmacx m4_toupper (@var{string})
12673 @msindex{tolower}
12674 @msindex{toupper}
12675 Return @var{string} with letters converted to upper or lower case,
12676 respectively.
12677 @end defmac
12679 @node Number processing Macros
12680 @subsection Arithmetic computation in M4
12682 The following macros facilitate integer arithmetic operations.
12683 Where a parameter is documented as taking an arithmetic expression, you
12684 can use anything that can be parsed by @code{m4_eval}.
12686 @defmac m4_cmp (@var{expr-1}, @var{expr-2})
12687 @msindex{cmp}
12688 Compare the arithmetic expressions @var{expr-1} and @var{expr-2}, and
12689 expand to @samp{-1} if @var{expr-1} is smaller, @samp{0} if they are
12690 equal, and @samp{1} if @var{expr-1} is larger.
12691 @end defmac
12693 @defmac m4_list_cmp (@var{list-1}, @var{list-2})
12694 @msindex{list_cmp}
12695 Compare the two M4 lists consisting of comma-separated arithmetic
12696 expressions, left to right.  Expand to @samp{-1} for the first element
12697 pairing where the value from @var{list-1} is smaller, @samp{1} where the
12698 value from @var{list-2} is smaller, or @samp{0} if both lists have the
12699 same values.  If one list is shorter than the other, the remaining
12700 elements of the longer list are compared against zero.
12701 @example
12702 m4_list_cmp([1, 0],       [1])
12703 @result{}0
12704 m4_list_cmp([1, [1 * 0]], [1, 0])
12705 @result{}0
12706 m4_list_cmp([1, 2],       [1, 0])
12707 @result{}1
12708 m4_list_cmp([1, [1+1], 3],[1, 2])
12709 @result{}1
12710 m4_list_cmp([1, 2, -3],   [1, 2])
12711 @result{}-1
12712 m4_list_cmp([1, 0],       [1, 2])
12713 @result{}-1
12714 m4_list_cmp([1],          [1, 2])
12715 @result{}-1
12716 @end example
12717 @end defmac
12719 @defmac m4_max (@var{arg}, @dots{})
12720 @msindex{max}
12721 This macro was introduced in Autoconf 2.62.  Expand to the decimal value
12722 of the maximum arithmetic expression among all the arguments.
12723 @end defmac
12725 @defmac m4_min (@var{arg}, @dots{})
12726 @msindex{min}
12727 This macro was introduced in Autoconf 2.62.  Expand to the decimal value
12728 of the minimum arithmetic expression among all the arguments.
12729 @end defmac
12731 @defmac m4_sign (@var{expr})
12732 @msindex{sign}
12733 Expand to @samp{-1} if the arithmetic expression @var{expr} is negative,
12734 @samp{1} if it is positive, and @samp{0} if it is zero.
12735 @end defmac
12737 @anchor{m4_version_compare}
12738 @defmac m4_version_compare (@var{version-1}, @var{version-2})
12739 @msindex{version_compare}
12740 This macro was introduced in Autoconf 2.53, but had a number of
12741 usability limitations that were not lifted until Autoconf 2.62.  Compare
12742 the version strings @var{version-1} and @var{version-2}, and expand to
12743 @samp{-1} if @var{version-1} is smaller, @samp{0} if they are the same,
12744 or @samp{1} @var{version-2} is smaller.  Version strings must be a list
12745 of elements separated by @samp{.}, @samp{,} or @samp{-}, where each
12746 element is a number along with optional case-insensitive letters
12747 designating beta releases.  The comparison stops at the leftmost element
12748 that contains a difference, although a 0 element compares equal to a
12749 missing element.
12751 It is permissible to include commit identifiers in @var{version}, such
12752 as an abbreviated SHA1 of the commit, provided there is still a
12753 monotonically increasing prefix to allow for accurate version-based
12754 comparisons.  For example, this paragraph was written when the
12755 development snapshot of autoconf claimed to be at version
12756 @samp{2.61a-248-dc51}, or 248 commits after the 2.61a release, with an
12757 abbreviated commit identification of @samp{dc51}.
12759 @example
12760 m4_version_compare([1.1], [2.0])
12761 @result{}-1
12762 m4_version_compare([2.0b], [2.0a])
12763 @result{}1
12764 m4_version_compare([1.1.1], [1.1.1a])
12765 @result{}-1
12766 m4_version_compare([1.2], [1.1.1a])
12767 @result{}1
12768 m4_version_compare([1.0], [1])
12769 @result{}0
12770 m4_version_compare([1.1pre], [1.1PRE])
12771 @result{}0
12772 m4_version_compare([1.1a], [1,10])
12773 @result{}-1
12774 m4_version_compare([2.61a], [2.61a-248-dc51])
12775 @result{}-1
12776 m4_version_compare([2.61b], [2.61a-248-dc51])
12777 @result{}1
12778 @end example
12779 @end defmac
12781 @defmac m4_version_prereq (@var{version}, @ovar{if-new-enough}, @
12782   @dvar{if-old, m4_fatal})
12783 @msindex{version_prereq}
12784 Compares @var{version} against the version of Autoconf currently
12785 running.  If the running version is at @var{version} or newer, expand
12786 @var{if-new-enough}, but if @var{version} is larger than the version
12787 currently executing, expand @var{if-old}, which defaults to printing an
12788 error message and exiting m4sugar with status 63.  When given only one
12789 argument, this behaves like @code{AC_PREREQ} (@pxref{Versioning}).
12790 Remember that the autoconf philosophy favors feature checks over version
12791 checks.
12792 @end defmac
12794 @node Set manipulation Macros
12795 @subsection Set manipulation in M4
12796 @cindex Set manipulation
12797 @cindex Data structure, set
12798 @cindex Unordered set manipulation
12800 Sometimes, it is necessary to track a set of data, where the order does
12801 not matter and where there are no duplicates in the set.  The following
12802 macros facilitate set manipulations.  Each set is an opaque object,
12803 which can only be accessed via these basic operations.  The underlying
12804 implementation guarantees linear scaling for set creation, which is more
12805 efficient than using the quadratic @code{m4_append_uniq}.  Both set
12806 names and values can be arbitrary strings, except for unbalanced quotes.
12807 This implementation ties up memory for removed elements until the next
12808 operation that must traverse all the elements of a set; and although
12809 that may slow down some operations until the memory for removed elements
12810 is pruned, it still guarantees linear performance.
12812 @defmac m4_set_add (@var{set}, @var{value}, @ovar{if-uniq}, @ovar{if-dup})
12813 @msindex{set_add}
12814 Adds the string @var{value} as a member of set @var{set}.  Expand
12815 @var{if-uniq} if the element was added, or @var{if-dup} if it was
12816 previously in the set.  Operates in amortized constant time, so that set
12817 creation scales linearly.
12818 @end defmac
12820 @defmac m4_set_add_all (@var{set}, @var{value}@dots{})
12821 @msindex{set_add_all}
12822 Adds each @var{value} to the set @var{set}.  This is slightly more
12823 efficient than repeatedly invoking @code{m4_set_add}.
12824 @end defmac
12826 @defmac m4_set_contains (@var{set}, @var{value}, @ovar{if-present}, @
12827  @ovar{if-absent})
12828 @msindex{set_contains}
12829 Expands @var{if-present} if the string @var{value} is a member of
12830 @var{set}, otherwise @var{if-absent}.
12832 @example
12833 m4_set_contains([a], [1], [yes], [no])
12834 @result{}no
12835 m4_set_add([a], [1], [added], [dup])
12836 @result{}added
12837 m4_set_add([a], [1], [added], [dup])
12838 @result{}dup
12839 m4_set_contains([a], [1], [yes], [no])
12840 @result{}yes
12841 m4_set_remove([a], [1], [removed], [missing])
12842 @result{}removed
12843 m4_set_contains([a], [1], [yes], [no])
12844 @result{}no
12845 m4_set_remove([a], [1], [removed], [missing])
12846 @result{}missing
12847 @end example
12848 @end defmac
12850 @defmac m4_set_contents (@var{set}, @ovar{sep})
12851 @defmacx m4_set_dump (@var{set}, @ovar{sep})
12852 @msindex{set_contents}
12853 @msindex{set_dump}
12854 Expands to a single string consisting of all the members of the set
12855 @var{set}, each separated by @var{sep}, which is not expanded.
12856 @code{m4_set_contents} leaves the elements in @var{set} but reclaims any
12857 memory occupied by removed elements, while @code{m4_set_dump} is a
12858 faster one-shot action that also deletes the set.  No provision is made
12859 for disambiguating members that contain a non-empty @var{sep} as a
12860 substring; use @code{m4_set_empty} to distinguish between an empty set
12861 and the set containing only the empty string.  The order of the output
12862 is unspecified; in the current implementation, part of the speed of
12863 @code{m4_set_dump} results from using a different output order than
12864 @code{m4_set_contents}.  These macros scale linearly in the size of the
12865 set before memory pruning, and @code{m4_set_contents([@var{set}],
12866 [@var{sep}])} is faster than
12867 @code{m4_joinall([@var{sep}]m4_set_listc([@var{set}]))}.
12869 @example
12870 m4_set_add_all([a], [1], [2], [3])
12871 @result{}
12872 m4_set_contents([a], [-])
12873 @result{}1-2-3
12874 m4_joinall([-]m4_set_listc([a]))
12875 @result{}1-2-3
12876 m4_set_dump([a], [-])
12877 @result{}3-2-1
12878 m4_set_contents([a])
12879 @result{}
12880 m4_set_add([a], [])
12881 @result{}
12882 m4_set_contents([a], [-])
12883 @result{}
12884 @end example
12885 @end defmac
12887 @defmac m4_set_delete (@var{set})
12888 @msindex{set_delete}
12889 Delete all elements and memory associated with @var{set}.  This is
12890 linear in the set size, and faster than removing one element at a time.
12891 @end defmac
12893 @defmac m4_set_difference (@var{seta}, @var{setb})
12894 @defmacx m4_set_intersection (@var{seta}, @var{setb})
12895 @defmacx m4_set_union (@var{seta}, @var{setb})
12896 @msindex{set_difference}
12897 @msindex{set_intersection}
12898 @msindex{set_union}
12899 Compute the relation between @var{seta} and @var{setb}, and output the
12900 result as a list of quoted arguments without duplicates and with a
12901 leading comma.  Set difference selects the elements in @var{seta} but
12902 not @var{setb}, intersection selects only elements in both sets, and
12903 union selects elements in either set.  These actions are linear in the
12904 sum of the set sizes.  The leading comma is necessary to distinguish
12905 between no elements and the empty string as the only element.
12907 @example
12908 m4_set_add_all([a], [1], [2], [3])
12909 @result{}
12910 m4_set_add_all([b], [3], [], [4])
12911 @result{}
12912 m4_set_difference([a], [b])
12913 @result{},1,2
12914 m4_set_difference([b], [a])
12915 @result{},,4
12916 m4_set_intersection([a], [b])
12917 @result{},3
12918 m4_set_union([a], [b])
12919 @result{},1,2,3,,4
12920 @end example
12921 @end defmac
12923 @defmac m4_set_empty (@var{set}, @ovar{if-empty}, @ovar{if-elements})
12924 @msindex{set_empty}
12925 Expand @var{if-empty} if the set @var{set} has no elements, otherwise
12926 expand @var{if-elements}.  This macro operates in constant time.  Using
12927 this macro can help disambiguate output from @code{m4_set_contents} or
12928 @code{m4_set_list}.
12929 @end defmac
12931 @defmac m4_set_foreach (@var{set}, @var{variable}, @var{action})
12932 @msindex{set_foreach}
12933 For each element in the set @var{set}, expand @var{action} with the
12934 macro @var{variable} defined as the set element.  Behavior is
12935 unspecified if @var{action} recursively lists the contents of @var{set}
12936 (although listing other sets is acceptable), or if it modifies the set
12937 in any way other than removing the element currently contained in
12938 @var{variable}.  This macro is faster than the corresponding
12939 @code{m4_foreach([@var{variable}],
12940 m4_indir([m4_dquote]m4_set_listc([@var{set}])), [@var{action}])},
12941 although @code{m4_set_map} might be faster still.
12943 @example
12944 m4_set_add_all([a]m4_for([i], [1], [5], [], [,i]))
12945 @result{}
12946 m4_set_contents([a])
12947 @result{}12345
12948 m4_set_foreach([a], [i],
12949   [m4_if(m4_eval(i&1), [0], [m4_set_remove([a], i, [i])])])
12950 @result{}24
12951 m4_set_contents([a])
12952 @result{}135
12953 @end example
12954 @end defmac
12956 @defmac m4_set_list (@var{set})
12957 @defmacx m4_set_listc (@var{set})
12958 @msindex{set_list}
12959 @msindex{set_listc}
12960 Produce a list of arguments, where each argument is a quoted element
12961 from the set @var{set}.  The variant @code{m4_set_listc} is unambiguous,
12962 by adding a leading comma if there are any set elements, whereas the
12963 variant @code{m4_set_list} cannot distinguish between an empty set and a
12964 set containing only the empty string.  These can be directly used in
12965 macros that take multiple arguments, such as @code{m4_join} or
12966 @code{m4_set_add_all}, or wrapped by @code{m4_dquote} for macros that
12967 take a quoted list, such as @code{m4_map} or @code{m4_foreach}.  Any
12968 memory occupied by removed elements is reclaimed during these macros.
12970 @example
12971 m4_set_add_all([a], [1], [2], [3])
12972 @result{}
12973 m4_set_list([a])
12974 @result{}1,2,3
12975 m4_set_list([b])
12976 @result{}
12977 m4_set_listc([b])
12978 @result{}
12979 m4_count(m4_set_list([b]))
12980 @result{}1
12981 m4_set_empty([b], [0], [m4_count(m4_set_list([b]))])
12982 @result{}0
12983 m4_set_add([b], [])
12984 @result{}
12985 m4_set_list([b])
12986 @result{}
12987 m4_set_listc([b])
12988 @result{},
12989 m4_count(m4_set_list([b]))
12990 @result{}1
12991 m4_set_empty([b], [0], [m4_count(m4_set_list([b]))])
12992 @result{}1
12993 @end example
12994 @end defmac
12996 @defmac m4_set_map (@var{set}, @var{action})
12997 @msindex{set_map}
12998 For each element in the set @var{set}, expand @var{action} with a single
12999 argument of the set element.  Behavior is unspecified if @var{action}
13000 recursively lists the contents of @var{set} (although listing other sets
13001 is acceptable), or if it modifies the set in any way other than removing
13002 the element passed as an argument.  This macro is faster than either
13003 corresponding counterpart of
13004 @code{m4_map_args([@var{action}]m4_set_listc([@var{set}]))} or
13005 @code{m4_set_foreach([@var{set}], [var],
13006 [@var{action}(m4_defn([var]))])}.  It is possible to use @code{m4_curry}
13007 if more than one argument is needed for @var{action}, although it is
13008 more efficient to use @code{m4_set_map_sep} in that case.
13009 @end defmac
13011 @defmac m4_set_map_sep (@var{set}, @ovar{pre}, @ovar{post}, @ovar{sep})
13012 @msindex{set_map_sep}
13013 For each element in the set @var{set}, expand
13014 @code{@var{pre}[element]@var{post}}, additionally expanding @var{sep}
13015 between elements.  Behavior is unspecified if the expansion recursively
13016 lists the contents of @var{set} (although listing other sets
13017 is acceptable), or if it modifies the set in any way other than removing
13018 the element visited by the expansion.  This macro provides the most
13019 efficient means for non-destructively visiting the elements of a set; in
13020 particular, @code{m4_set_map([@var{set}], [@var{action}])} is equivalent
13021 to @code{m4_set_map_sep([@var{set}], [@var{action}(], [)])}.
13022 @end defmac
13024 @defmac m4_set_remove (@var{set}, @var{value}, @ovar{if-present}, @
13025  @ovar{if-absent})
13026 @msindex{set_remove}
13027 If @var{value} is an element in the set @var{set}, then remove it and
13028 expand @var{if-present}.  Otherwise expand @var{if-absent}.  This macro
13029 operates in constant time so that multiple removals will scale linearly
13030 rather than quadratically; but when used outside of
13031 @code{m4_set_foreach} or @code{m4_set_map}, it leaves memory occupied
13032 until the set is later
13033 compacted by @code{m4_set_contents} or @code{m4_set_list}.  Several
13034 other set operations are then less efficient between the time of element
13035 removal and subsequent memory compaction, but still maintain their
13036 guaranteed scaling performance.
13037 @end defmac
13039 @defmac m4_set_size (@var{set})
13040 @msindex{set_size}
13041 Expand to the size of the set @var{set}.  This implementation operates
13042 in constant time, and is thus more efficient than
13043 @code{m4_eval(m4_count(m4_set_listc([set])) - 1)}.
13044 @end defmac
13047 @node Forbidden Patterns
13048 @subsection Forbidden Patterns
13049 @cindex Forbidden patterns
13050 @cindex Patterns, forbidden
13052 M4sugar provides a means to define suspicious patterns, patterns
13053 describing tokens which should not be found in the output.  For
13054 instance, if an Autoconf @file{configure} script includes tokens such as
13055 @samp{AC_DEFINE}, or @samp{dnl}, then most probably something went
13056 wrong (typically a macro was not evaluated because of overquotation).
13058 M4sugar forbids all the tokens matching @samp{^_?m4_} and @samp{^dnl$}.
13059 Additional layers, such as M4sh and Autoconf, add additional forbidden
13060 patterns to the list.
13062 @defmac m4_pattern_forbid (@var{pattern})
13063 @msindex{pattern_forbid}
13064 Declare that no token matching @var{pattern} must be found in the output.
13065 Comments are not checked; this can be a problem if, for instance, you
13066 have some macro left unexpanded after an @samp{#include}.  No consensus
13067 is currently found in the Autoconf community, as some people consider it
13068 should be valid to name macros in comments (which doesn't make sense to
13069 the authors of this documentation: input, such as macros, should be
13070 documented by @samp{dnl} comments; reserving @samp{#}-comments to
13071 document the output).
13072 @end defmac
13074 Of course, you might encounter exceptions to these generic rules, for
13075 instance you might have to refer to @samp{$m4_flags}.
13077 @defmac m4_pattern_allow (@var{pattern})
13078 @msindex{pattern_allow}
13079 Any token matching @var{pattern} is allowed, including if it matches an
13080 @code{m4_pattern_forbid} pattern.
13081 @end defmac
13083 @node Debugging via autom4te
13084 @section Debugging via autom4te
13085 @cindex debugging tips
13086 @cindex autom4te debugging tips
13087 @cindex m4sugar debugging tips
13088 At times, it is desirable to see what was happening inside m4, to see
13089 why output was not matching expectations.  However, post-processing done
13090 by @command{autom4te} means that directly using the m4 builtin
13091 @code{m4_traceon} is likely to interfere with operation.  Also, frequent
13092 diversion changes and the concept of forbidden tokens make it difficult
13093 to use @code{m4_defn} to generate inline comments in the final output.
13095 There are a couple of tools to help with this.  One is the use of the
13096 @option{--trace} option provided by @command{autom4te} (as well as each
13097 of the programs that wrap @command{autom4te}, such as
13098 @command{autoconf}), in order to inspect when a macro is called and with
13099 which arguments.  For example, when this paragraph was written, the
13100 autoconf version could be found by:
13102 @example
13103 $ @kbd{autoconf --trace=AC_INIT}
13104 configure.ac:23:AC_INIT:GNU Autoconf:2.63b.95-3963:bug-autoconf@@gnu.org
13105 $ @kbd{autoconf --trace='AC_INIT:version is $2'}
13106 version is 2.63b.95-3963
13107 @end example
13109 Another trick is to print out the expansion of various m4 expressions to
13110 standard error or to an independent file, with no further m4 expansion,
13111 and without interfering with diversion changes or the post-processing
13112 done to standard output.  @code{m4_errprintn} shows a given expression
13113 on standard error.  For example, if you want to see the expansion of an
13114 autoconf primitive or of one of your autoconf macros, you can do it like
13115 this:
13117 @example
13118 $ @kbd{cat <<\EOF > configure.ac}
13119 AC_INIT
13120 m4_errprintn([The definition of AC_DEFINE_UNQUOTED:])
13121 m4_errprintn(m4_defn([AC_DEFINE_UNQUOTED]))
13122 AC_OUTPUT
13124 $ @kbd{autoconf}
13125 @error{}The definition of AC_DEFINE_UNQUOTED:
13126 @error{}_AC_DEFINE_Q([], $@@)
13127 @end example
13129 @node Programming in M4sh
13130 @chapter Programming in M4sh
13132 M4sh, pronounced ``mash'', is aiming at producing portable Bourne shell
13133 scripts.  This name was coined by Lars J. Aas, who notes that,
13134 according to the Webster's Revised Unabridged Dictionary (1913):
13136 @quotation
13137 Mash \Mash\, n.  [Akin to G. meisch, maisch, meische, maische, mash,
13138 wash, and prob.@: to AS. miscian to mix.  See ``Mix''.]
13140 @enumerate 1
13141 @item
13142 A mass of mixed ingredients reduced to a soft pulpy state by beating or
13143 pressure@enddots{}
13145 @item
13146 A mixture of meal or bran and water fed to animals.
13148 @item
13149 A mess; trouble.  [Obs.] --Beau.@: & Fl.
13150 @end enumerate
13151 @end quotation
13153 M4sh reserves the M4 macro namespace @samp{^_AS_} for internal use, and
13154 the namespace @samp{^AS_} for M4sh macros.  It also reserves the shell
13155 and environment variable namespace @samp{^as_}, and the here-document
13156 delimiter namespace @samp{^_AS[A-Z]} in the output file.  You should not
13157 define your own macros or output shell code that conflicts with these
13158 namespaces.
13160 @menu
13161 * Common Shell Constructs::     Portability layer for common shell constructs
13162 * Polymorphic Variables::       Support for indirect variable names
13163 * Initialization Macros::       Macros to establish a sane shell environment
13164 * File Descriptor Macros::      File descriptor macros for input and output
13165 @end menu
13167 @node Common Shell Constructs
13168 @section Common Shell Constructs
13170 M4sh provides portable alternatives for some common shell constructs
13171 that unfortunately are not portable in practice.
13173 @c Deprecated, to be replaced by a better API
13174 @ignore
13175 @defmac AS_BASENAME (@var{file-name})
13176 @asindex{BASENAME}
13177 Output the non-directory portion of @var{file-name}.  For example,
13178 if @code{$file} is @samp{/one/two/three}, the command
13179 @code{base=`AS_BASENAME(["$file"])`} sets @code{base} to @samp{three}.
13180 @end defmac
13181 @end ignore
13183 @defmac AS_BOX (@var{text}, @dvar{char, -})
13184 @asindex{BOX}
13185 Expand into shell code that will output @var{text} surrounded by a box
13186 with @var{char} in the top and bottom border.  @var{text} should not
13187 contain a newline, but may contain shell expansions valid for unquoted
13188 here-documents.  @var{char} defaults to @samp{-}, but can be any
13189 character except @samp{/}, @samp{'}, @samp{"}, @samp{\},
13190 @samp{&}, or @samp{`}.  This is useful for outputting a comment box into
13191 log files to separate distinct phases of script operation.
13192 @end defmac
13194 @defmac AS_CASE (@var{word}, @ovar{pattern1}, @ovar{if-matched1}, @
13195   @dots{}, @ovar{default})
13196 @asindex{CASE}
13197 Expand into a shell @samp{case} statement, where @var{word} is matched
13198 against one or more patterns.  @var{if-matched} is run if the
13199 corresponding pattern matched @var{word}, else @var{default} is run.
13200 Avoids several portability issues (@pxref{case, , Limitations of Shell
13201 Builtins}).
13202 @end defmac
13204 @c Deprecated, to be replaced by a better API
13205 @defmac AS_DIRNAME (@var{file-name})
13206 @asindex{DIRNAME}
13207 Output the directory portion of @var{file-name}.  For example,
13208 if @code{$file} is @samp{/one/two/three}, the command
13209 @code{dir=`AS_DIRNAME(["$file"])`} sets @code{dir} to @samp{/one/two}.
13211 This interface may be improved in the future to avoid forks and losing
13212 trailing newlines.
13213 @end defmac
13215 @defmac AS_ECHO (@var{word})
13216 @asindex{ECHO}
13217 Emits @var{word} to the standard output, followed by a newline.  @var{word}
13218 must be a single shell word (typically a quoted string).  The bytes of
13219 @var{word} are output as-is, even if it starts with "-" or contains "\".
13220 Redirections can be placed outside the macro invocation.  This is much
13221 more portable than using @command{echo} (@pxref{echo, , Limitations of
13222 Shell Builtins}).
13223 @end defmac
13225 @defmac AS_ECHO_N (@var{word})
13226 @asindex{ECHO_N}
13227 Emits @var{word} to the standard output, without a following newline.
13228 @var{word} must be a single shell word (typically a quoted string) and,
13229 for portability, should not include more than one newline.  The bytes of
13230 @var{word} are output as-is, even if it starts with "-" or contains "\".
13231 Redirections can be placed outside the macro invocation.
13232 @end defmac
13234 @c We cannot use @dvar because the macro expansion mistreats backslashes.
13235 @defmac AS_ESCAPE (@var{string}, @r{[}@var{chars} = @samp{`\"$}@r{]})
13236 @asindex{ESCAPE}
13237 Expands to @var{string}, with any characters in @var{chars} escaped with
13238 a backslash (@samp{\}).  @var{chars} should be at most four bytes long,
13239 and only contain characters from the set @samp{`\"$}; however,
13240 characters may be safely listed more than once in @var{chars} for the
13241 sake of syntax highlighting editors.  The current implementation expands
13242 @var{string} after adding escapes; if @var{string} contains macro calls
13243 that in turn expand to text needing shell quoting, you can use
13244 @code{AS_ESCAPE(m4_dquote(m4_expand([string])))}.
13246 The default for @var{chars} (@samp{\"$`}) is the set of characters
13247 needing escapes when @var{string} will be used literally within double
13248 quotes.  One common variant is the set of characters to protect when
13249 @var{string} will be used literally within back-ticks or an unquoted
13250 here-document (@samp{\$`}).  Another common variant is @samp{""}, which can
13251 be used to form a double-quoted string containing the same expansions
13252 that would have occurred if @var{string} were expanded in an unquoted
13253 here-document; however, when using this variant, care must be taken that
13254 @var{string} does not use double quotes within complex variable
13255 expansions (such as @samp{$@{foo-`echo "hi"`@}}) that would be broken
13256 with improper escapes.
13258 This macro is often used with @code{AS_ECHO}.  For an example, observe
13259 the output generated by the shell code generated from this snippet:
13261 @example
13262 foo=bar
13263 AS_ECHO(["AS_ESCAPE(["$foo" = ])AS_ESCAPE(["$foo"], [""])"])
13264 @result{}"$foo" = "bar"
13265 m4_define([macro], [a, [\b]])
13266 AS_ECHO(["AS_ESCAPE([[macro]])"])
13267 @result{}macro
13268 AS_ECHO(["AS_ESCAPE([macro])"])
13269 @result{}a, b
13270 AS_ECHO(["AS_ESCAPE(m4_dquote(m4_expand([macro])))"])
13271 @result{}a, \b
13272 @end example
13274 @comment Should we add AS_ESCAPE_SINGLE? If we do, we can optimize in
13275 @comment the case of @var{string} that does not contain '.
13276 To escape a string that will be placed within single quotes, use:
13278 @example
13279 m4_bpatsubst([[@var{string}]], ['], ['\\''])
13280 @end example
13281 @end defmac
13283 @defmac AS_EXIT (@dvar{status, $?})
13284 @asindex{EXIT}
13285 Emit code to exit the shell with @var{status}, defaulting to @samp{$?}.
13286 This macro
13287 works around shells that see the exit status of the command prior to
13288 @code{exit} inside a @samp{trap 0} handler (@pxref{trap, , Limitations
13289 of Shell Builtins}).
13290 @end defmac
13292 @defmac AS_IF (@var{test1}, @ovar{run-if-true1}, @dots{}, @ovar{run-if-false})
13293 @asindex{IF}
13294 Run shell code @var{test1}.  If @var{test1} exits with a zero status then
13295 run shell code @var{run-if-true1}, else examine further tests.  If no test
13296 exits with a zero status, run shell code @var{run-if-false}, with
13297 simplifications if either @var{run-if-true1} or @var{run-if-false}
13298 is empty.  For example,
13300 @example
13301 AS_IF([test "x$foo" = xyes], [HANDLE_FOO([yes])],
13302       [test "x$foo" != xno], [HANDLE_FOO([maybe])],
13303       [echo foo not specified])
13304 @end example
13306 @noindent
13307 ensures any required macros of @code{HANDLE_FOO}
13308 are expanded before the first test.
13309 @end defmac
13311 @defmac AS_MKDIR_P (@var{file-name})
13312 @asindex{MKDIR_P}
13313 Make the directory @var{file-name}, including intervening directories
13314 as necessary.  This is equivalent to @samp{mkdir -p -- @var{file-name}},
13315 except that it is portable to older versions of @command{mkdir} that
13316 lack support for the @option{-p} option or for the @option{--}
13317 delimiter (@pxref{mkdir, , Limitations of Usual Tools}).  Also,
13318 @code{AS_MKDIR_P}
13319 succeeds if @var{file-name} is a symbolic link to an existing directory,
13320 even though Posix is unclear whether @samp{mkdir -p} should
13321 succeed in that case.  If creation of @var{file-name} fails, exit the
13322 script.
13324 Also see the @code{AC_PROG_MKDIR_P} macro (@pxref{Particular Programs}).
13325 @end defmac
13327 @defmac AS_SET_STATUS (@var{status})
13328 @asindex{SET_STATUS}
13329 Emit shell code to set the value of @samp{$?} to @var{status}, as
13330 efficiently as possible.  However, this is not guaranteed to abort a
13331 shell running with @code{set -e} (@pxref{set, , Limitations of Shell
13332 Builtins}).  This should also be used at the end of a complex shell
13333 function instead of @samp{return} (@pxref{Shell Functions}) to avoid
13334 a DJGPP shell bug.
13335 @end defmac
13337 @defmac AS_TR_CPP (@var{expression})
13338 @asindex{TR_CPP}
13339 Transform @var{expression} into a valid right-hand side for a C @code{#define}.
13340 For example:
13342 @example
13343 # This outputs "#define HAVE_CHAR_P 1".
13344 # Notice the m4 quoting around #, to prevent an m4 comment
13345 type="char *"
13346 echo "[#]define AS_TR_CPP([HAVE_$type]) 1"
13347 @end example
13348 @end defmac
13350 @defmac AS_TR_SH (@var{expression})
13351 @asindex{TR_SH}
13352 Transform @var{expression} into shell code that generates a valid shell
13353 variable name.  The result is literal when possible at m4 time, but must
13354 be used with @code{eval} if @var{expression} causes shell indirections.
13355 For example:
13357 @example
13358 # This outputs "Have it!".
13359 header="sys/some file.h"
13360 eval AS_TR_SH([HAVE_$header])=yes
13361 if test "x$HAVE_sys_some_file_h" = xyes; then echo "Have it!"; fi
13362 @end example
13363 @end defmac
13365 @defmac AS_SET_CATFILE (@var{var}, @var{dir}, @var{file})
13366 @asindex{SET_CATFILE}
13367 Set the polymorphic shell variable @var{var} to @var{dir}/@var{file},
13368 but optimizing the common cases (@var{dir} or @var{file} is @samp{.},
13369 @var{file} is absolute, etc.).
13370 @end defmac
13372 @defmac AS_UNSET (@var{var})
13373 @asindex{UNSET}
13374 Unsets the shell variable @var{var}, working around bugs in older
13375 shells (@pxref{unset, , Limitations of Shell
13376 Builtins}).  @var{var} can be a literal or indirect variable name.
13377 @end defmac
13379 @defmac AS_VERSION_COMPARE (@var{version-1}, @var{version-2}, @
13380   @ovar{action-if-less}, @ovar{action-if-equal}, @ovar{action-if-greater})
13381 @asindex{VERSION_COMPARE}
13382 Compare two strings @var{version-1} and @var{version-2}, possibly
13383 containing shell variables, as version strings, and expand
13384 @var{action-if-less}, @var{action-if-equal}, or @var{action-if-greater}
13385 depending upon the result.
13386 The algorithm to compare is similar to the one used by strverscmp in
13387 glibc (@pxref{String/Array Comparison, , String/Array Comparison, libc,
13388 The GNU C Library}).
13389 @end defmac
13391 @node Polymorphic Variables
13392 @section Support for indirect variable names
13393 @cindex variable name indirection
13394 @cindex polymorphic variable name
13395 @cindex indirection, variable name
13397 Often, it is convenient to write a macro that will emit shell code
13398 operating on a shell variable.  The simplest case is when the variable
13399 name is known.  But a more powerful idiom is writing shell code that can
13400 work through an indirection, where another variable or command
13401 substitution produces the name of the variable to actually manipulate.
13402 M4sh supports the notion of polymorphic shell variables, making it easy
13403 to write a macro that can deal with either literal or indirect variable
13404 names and output shell code appropriate for both use cases.  Behavior is
13405 undefined if expansion of an indirect variable does not result in a
13406 literal variable name.
13408 @defmac AS_LITERAL_IF (@var{expression}, @ovar{if-literal}, @ovar{if-not}, @
13409   @dvar{if-simple-ref, @var{if-not}})
13410 @defmacx AS_LITERAL_WORD_IF (@var{expression}, @ovar{if-literal}, @
13411   @ovar{if-not}, @dvar{if-simple-ref, @var{if-not}})
13412 @asindex{LITERAL_IF}
13413 @asindex{LITERAL_WORD_IF}
13414 If the expansion of @var{expression} is definitely a shell literal,
13415 expand @var{if-literal}.  If the expansion of @var{expression} looks
13416 like it might contain shell indirections (such as @code{$var} or
13417 @code{`expr`}), then @var{if-not} is expanded.  Sometimes, it is
13418 possible to output optimized code if @var{expression} consists only of
13419 shell variable expansions (such as @code{$@{var@}}), in which case
13420 @var{if-simple-ref} can be provided; but defaulting to @var{if-not}
13421 should always be safe.  @code{AS_LITERAL_WORD_IF} only expands
13422 @var{if-literal} if @var{expression} looks like a single shell word,
13423 containing no whitespace; while @code{AS_LITERAL_IF} allows whitespace
13424 in @var{expression}.
13426 In order to reduce the time spent recognizing whether an
13427 @var{expression} qualifies as a literal or a simple indirection, the
13428 implementation is somewhat conservative: @var{expression} must be a
13429 single shell word (possibly after stripping whitespace), consisting only
13430 of bytes that would have the same meaning whether unquoted or enclosed
13431 in double quotes (for example, @samp{a.b} results in @var{if-literal},
13432 even though it is not a valid shell variable name; while both @samp{'a'}
13433 and @samp{[$]} result in @var{if-not}, because they behave differently
13434 than @samp{"'a'"} and @samp{"[$]"}).  This macro can be used in contexts
13435 for recognizing portable file names (such as in the implementation of
13436 @code{AC_LIBSOURCE}), or coupled with some transliterations for forming
13437 valid variable names (such as in the implementation of @code{AS_TR_SH},
13438 which uses an additional @code{m4_translit} to convert @samp{.} to
13439 @samp{_}).
13441 This example shows how to read the contents of the shell variable
13442 @code{bar}, exercising all three arguments to @code{AS_LITERAL_IF}.  It
13443 results in a script that will output the line @samp{hello} three times.
13445 @example
13446 AC_DEFUN([MY_ACTION],
13447 [AS_LITERAL_IF([$1],
13448   [echo "$$1"],
13449   [AS_VAR_COPY([var], [$1])
13450    echo "$var"],
13451   [eval 'echo "$'"$1"\"])])
13452 foo=bar bar=hello
13453 MY_ACTION([bar])
13454 MY_ACTION([`echo bar`])
13455 MY_ACTION([$foo])
13456 @end example
13457 @end defmac
13459 @defmac AS_VAR_APPEND (@var{var}, @var{text})
13460 @asindex{VAR_APPEND}
13461 Emit shell code to append the shell expansion of @var{text} to the end
13462 of the current contents of the polymorphic shell variable @var{var},
13463 taking advantage of shells that provide the @samp{+=} extension for more
13464 efficient scaling.
13466 For situations where the final contents of @var{var} are relatively
13467 short (less than 256 bytes), it is more efficient to use the simpler
13468 code sequence of @code{@var{var}=$@{@var{var}@}@var{text}} (or its
13469 polymorphic equivalent of @code{AS_VAR_COPY([t], [@var{var}])} and
13470 @code{AS_VAR_SET([@var{var}], ["$t"@var{text}])}).  But in the case
13471 when the script will be repeatedly appending text into @code{var},
13472 issues of scaling start to become apparent.  A naive implementation
13473 requires execution time linear to the length of the current contents of
13474 @var{var} as well as the length of @var{text} for a single append, for
13475 an overall quadratic scaling with multiple appends.  This macro takes
13476 advantage of shells which provide the extension
13477 @code{@var{var}+=@var{text}}, which can provide amortized constant time
13478 for a single append, for an overall linear scaling with multiple
13479 appends.  Note that unlike @code{AS_VAR_SET}, this macro requires that
13480 @var{text} be quoted properly to avoid field splitting and file name
13481 expansion.
13482 @end defmac
13484 @defmac AS_VAR_ARITH (@var{var}, @var{expression})
13485 @asindex{VAR_ARITH}
13486 Emit shell code to compute the arithmetic expansion of @var{expression},
13487 assigning the result as the contents of the polymorphic shell variable
13488 @var{var}.  The code takes advantage of shells that provide @samp{$(())}
13489 for fewer forks, but uses @command{expr} as a fallback.  Therefore, the
13490 syntax for a valid @var{expression} is rather limited: all operators
13491 must occur as separate shell arguments and with proper quoting, there is
13492 no portable equality operator, all variables containing numeric values
13493 must be expanded prior to the computation, all numeric values must be
13494 provided in decimal without leading zeroes, and the first shell argument
13495 should not be a negative number.  In the following example, this snippet
13496 will print @samp{(2+3)*4 == 20}.
13498 @example
13499 bar=3
13500 AS_VAR_ARITH([foo], [\( 2 + $bar \) \* 4])
13501 echo "(2+$bar)*4 == $foo"
13502 @end example
13503 @end defmac
13505 @defmac AS_VAR_COPY (@var{dest}, @var{source})
13506 @asindex{VAR_COPY}
13507 Emit shell code to assign the contents of the polymorphic shell variable
13508 @var{source} to the polymorphic shell variable @var{dest}.  For example,
13509 executing this M4sh snippet will output @samp{bar hi}:
13511 @example
13512 foo=bar bar=hi
13513 AS_VAR_COPY([a], [foo])
13514 AS_VAR_COPY([b], [$foo])
13515 echo "$a $b"
13516 @end example
13518 When it is necessary to access the contents of an indirect variable
13519 inside a shell double-quoted context, the recommended idiom is to first
13520 copy the contents into a temporary literal shell variable.
13522 @smallexample
13523 for header in stdint_h inttypes_h ; do
13524   AS_VAR_COPY([var], [ac_cv_header_$header])
13525   echo "$header detected: $var"
13526 done
13527 @end smallexample
13528 @end defmac
13530 @comment AS_VAR_GET is intentionally undocumented; it can't handle
13531 @comment trailing newlines uniformly, and forks too much.
13533 @defmac AS_VAR_IF (@var{var}, @ovar{word}, @ovar{if-equal}, @
13534   @ovar{if-not-equal})
13535 @asindex{VAR_IF}
13536 Output a shell conditional statement.  If the contents of the
13537 polymorphic shell variable @var{var} match the string @var{word},
13538 execute @var{if-equal}; otherwise execute @var{if-not-equal}.  @var{word}
13539 must be a single shell word (typically a quoted string).  Avoids
13540 shell bugs if an interrupt signal arrives while a command substitution
13541 in @var{var} is being expanded.
13542 @end defmac
13544 @defmac AS_VAR_PUSHDEF (@var{m4-name}, @var{value})
13545 @defmacx AS_VAR_POPDEF (@var{m4-name})
13546 @asindex{VAR_PUSHDEF}
13547 @asindex{VAR_POPDEF}
13548 @cindex composing variable names
13549 @cindex variable names, composing
13550 A common M4sh idiom involves composing shell variable names from an m4
13551 argument (for example, writing a macro that uses a cache variable).
13552 @var{value} can be an arbitrary string, which will be transliterated
13553 into a valid shell name by @code{AS_TR_SH}.  In order to access the
13554 composed variable name based on @var{value}, it is easier to declare a
13555 temporary m4 macro @var{m4-name} with @code{AS_VAR_PUSHDEF}, then use
13556 that macro as the argument to subsequent @code{AS_VAR} macros as a
13557 polymorphic variable name, and finally free the temporary macro with
13558 @code{AS_VAR_POPDEF}.  These macros are often followed with @code{dnl},
13559 to avoid excess newlines in the output.
13561 Here is an involved example, that shows the power of writing macros that
13562 can handle composed shell variable names:
13564 @example
13565 m4_define([MY_CHECK_HEADER],
13566 [AS_VAR_PUSHDEF([my_Header], [ac_cv_header_$1])dnl
13567 AS_VAR_IF([my_Header], [yes], [echo "header $1 detected"])dnl
13568 AS_VAR_POPDEF([my_Header])dnl
13570 MY_CHECK_HEADER([stdint.h])
13571 for header in inttypes.h stdlib.h ; do
13572   MY_CHECK_HEADER([$header])
13573 done
13574 @end example
13576 @noindent
13577 In the above example, @code{MY_CHECK_HEADER} can operate on polymorphic
13578 variable names.  In the first invocation, the m4 argument is
13579 @code{stdint.h}, which transliterates into a literal @code{stdint_h}.
13580 As a result, the temporary macro @code{my_Header} expands to the literal
13581 shell name @samp{ac_cv_header_stdint_h}.  In the second invocation, the
13582 m4 argument to @code{MY_CHECK_HEADER} is @code{$header}, and the
13583 temporary macro @code{my_Header} expands to the indirect shell name
13584 @samp{$as_my_Header}.  During the shell execution of the for loop, when
13585 @samp{$header} contains @samp{inttypes.h}, then @samp{$as_my_Header}
13586 contains @samp{ac_cv_header_inttypes_h}.  If this script is then run on a
13587 platform where all three headers have been previously detected, the
13588 output of the script will include:
13590 @smallexample
13591 header stdint.h detected
13592 header inttypes.h detected
13593 header stdlib.h detected
13594 @end smallexample
13595 @end defmac
13597 @defmac AS_VAR_SET (@var{var}, @ovar{value})
13598 @asindex{VAR_SET}
13599 Emit shell code to assign the contents of the polymorphic shell variable
13600 @var{var} to the shell expansion of @var{value}.  @var{value} is not
13601 subject to field splitting or file name expansion, so if command
13602 substitution is used, it may be done with @samp{`""`} rather than using
13603 an intermediate variable (@pxref{Shell Substitutions}).  However,
13604 @var{value} does undergo rescanning for additional macro names; behavior
13605 is unspecified if late expansion results in any shell meta-characters.
13606 @end defmac
13608 @defmac AS_VAR_SET_IF (@var{var}, @ovar{if-set}, @ovar{if-undef})
13609 @asindex{VAR_SET_IF}
13610 Emit a shell conditional statement, which executes @var{if-set} if the
13611 polymorphic shell variable @code{var} is set to any value, and
13612 @var{if-undef} otherwise.
13613 @end defmac
13615 @defmac AS_VAR_TEST_SET (@var{var})
13616 @asindex{VAR_TEST_SET}
13617 Emit a shell statement that results in a successful exit status only if
13618 the polymorphic shell variable @code{var} is set.
13619 @end defmac
13621 @node Initialization Macros
13622 @section Initialization Macros
13624 @defmac AS_BOURNE_COMPATIBLE
13625 @asindex{BOURNE_COMPATIBLE}
13626 Set up the shell to be more compatible with the Bourne shell as
13627 standardized by Posix, if possible.  This may involve setting
13628 environment variables, or setting options, or similar
13629 implementation-specific actions.  This macro is deprecated, since
13630 @code{AS_INIT} already invokes it.
13631 @end defmac
13633 @defmac AS_INIT
13634 @asindex{INIT}
13635 @evindex LC_ALL
13636 @evindex SHELL
13637 Initialize the M4sh environment.  This macro calls @code{m4_init}, then
13638 outputs the @code{#! /bin/sh} line, a notice about where the output was
13639 generated from, and code to sanitize the environment for the rest of the
13640 script.  Among other initializations, this sets @env{SHELL} to the shell
13641 chosen to run the script (@pxref{CONFIG_SHELL}), and @env{LC_ALL} to
13642 ensure the C locale.  Finally, it changes the current diversion to
13643 @code{BODY}.  @code{AS_INIT} is called automatically by @code{AC_INIT}
13644 and @code{AT_INIT}, so shell code in @file{configure},
13645 @file{config.status}, and @file{testsuite} all benefit from a sanitized
13646 shell environment.
13647 @end defmac
13649 @defmac AS_INIT_GENERATED (@var{file}, @ovar{comment})
13650 @asindex{INIT_GENERATED}
13651 Emit shell code to start the creation of a subsidiary shell script in
13652 @var{file}, including changing @var{file} to be executable.  This macro
13653 populates the child script with information learned from the parent
13654 (thus, the emitted code is equivalent in effect, but more efficient,
13655 than the code output by @code{AS_INIT}, @code{AS_BOURNE_COMPATIBLE}, and
13656 @code{AS_SHELL_SANITIZE}).  If present, @var{comment} is output near the
13657 beginning of the child, prior to the shell initialization code, and is
13658 subject to parameter expansion, command substitution, and backslash
13659 quote removal.  The
13660 parent script should check the exit status after this macro, in case
13661 @var{file} could not be properly created (for example, if the disk was
13662 full).  If successfully created, the parent script can then proceed to
13663 append additional M4sh constructs into the child script.
13665 Note that the child script starts life without a log file open, so if
13666 the parent script uses logging (@pxref{AS_MESSAGE_LOG_FD}), you
13667 must temporarily disable any attempts to use the log file until after
13668 emitting code to open a log within the child.  On the other hand, if the
13669 parent script has @code{AS_MESSAGE_FD} redirected somewhere besides
13670 @samp{1}, then the child script already has code that copies stdout to
13671 that descriptor.  Currently, the suggested
13672 idiom for writing a M4sh shell script from within another script is:
13674 @example
13675 AS_INIT_GENERATED([@var{file}], [[# My child script.
13676 ]]) || @{ AS_ECHO(["Failed to create child script"]); AS_EXIT; @}
13677 m4_pushdef([AS_MESSAGE_LOG_FD])dnl
13678 cat >> "@var{file}" <<\__EOF__
13679 # Code to initialize AS_MESSAGE_LOG_FD
13680 m4_popdef([AS_MESSAGE_LOG_FD])dnl
13681 # Additional code
13682 __EOF__
13683 @end example
13685 This, however, may change in the future as the M4sh interface is
13686 stabilized further.
13688 Also, be aware that use of @env{LINENO} within the child script may
13689 report line numbers relative to their location in the parent script,
13690 even when using @code{AS_LINENO_PREPARE}, if the parent script was
13691 unable to locate a shell with working @env{LINENO} support.
13692 @end defmac
13694 @defmac AS_LINENO_PREPARE
13695 @asindex{LINENO_PREPARE}
13696 @evindex LINENO
13697 Find a shell that supports the special variable @env{LINENO}, which
13698 contains the number of the currently executing line.  This macro is
13699 automatically invoked by @code{AC_INIT} in configure scripts.
13700 @end defmac
13702 @defmac AS_ME_PREPARE
13703 @asindex{ME_PREPARE}
13704 Set up variable @env{as_me} to be the basename of the currently executing
13705 script.  This macro is automatically invoked by @code{AC_INIT} in
13706 configure scripts.
13707 @end defmac
13709 @defmac AS_TMPDIR (@var{prefix}, @dvar{dir, $@{TMPDIR:=/tmp@}})
13710 @asindex{TMPDIR}
13711 @evindex TMPDIR
13712 @ovindex tmp
13713 Create, as safely as possible, a temporary sub-directory within
13714 @var{dir} with a name starting with @var{prefix}.  @var{prefix} should
13715 be 2-4 characters, to make it slightly easier to identify the owner of
13716 the directory.  If @var{dir} is omitted, then the value of @env{TMPDIR}
13717 will be used (defaulting to @samp{/tmp}).  On success, the name of the
13718 newly created directory is stored in the shell variable @code{tmp}.  On
13719 error, the script is aborted.
13721 Typically, this macro is coupled with some exit traps to delete the created
13722 directory and its contents on exit or interrupt.  However, there is a
13723 slight window between when the directory is created and when the name is
13724 actually known to the shell, so an interrupt at the right moment might
13725 leave the temporary directory behind.  Hence it is important to use a
13726 @var{prefix} that makes it easier to determine if a leftover temporary
13727 directory from an interrupted script is safe to delete.
13729 The use of the output variable @samp{$tmp} rather than something in the
13730 @samp{as_} namespace is historical; it has the unfortunate consequence
13731 that reusing this otherwise common name for any other purpose inside
13732 your script has the potential to break any cleanup traps designed to
13733 remove the temporary directory.
13734 @end defmac
13736 @defmac AS_SHELL_SANITIZE
13737 @asindex{SHELL_SANITIZE}
13738 Initialize the shell suitably for @command{configure} scripts.  This has
13739 the effect of @code{AS_BOURNE_COMPATIBLE}, and sets some other
13740 environment variables for predictable results from configuration tests.
13741 For example, it sets @env{LC_ALL} to change to the default C locale.
13742 @xref{Special Shell Variables}.  This macro is deprecated, since
13743 @code{AS_INIT} already invokes it.
13744 @end defmac
13747 @node File Descriptor Macros
13748 @section File Descriptor Macros
13749 @cindex input
13750 @cindex standard input
13751 @cindex file descriptors
13752 @cindex descriptors
13753 @cindex low-level output
13754 @cindex output, low-level
13756 The following macros define file descriptors used to output messages
13757 (or input values) from @file{configure} scripts.
13758 For example:
13760 @example
13761 echo "$wombats found" >&AS_MESSAGE_LOG_FD
13762 echo 'Enter desired kangaroo count:' >&AS_MESSAGE_FD
13763 read kangaroos <&AS_ORIGINAL_STDIN_FD`
13764 @end example
13766 @noindent
13767 However doing so is seldom needed, because Autoconf provides higher
13768 level macros as described below.
13770 @defmac AS_MESSAGE_FD
13771 @asindex{MESSAGE_FD}
13772 The file descriptor for @samp{checking for...}  messages and results.
13773 By default, @code{AS_INIT} sets this to @samp{1} for standalone M4sh
13774 clients.  However, @code{AC_INIT} shuffles things around to another file
13775 descriptor, in order to allow the @option{-q} option of
13776 @command{configure} to choose whether messages should go to the script's
13777 standard output or be discarded.
13779 If you want to display some messages, consider using one of the printing
13780 macros (@pxref{Printing Messages}) instead.  Copies of messages output
13781 via these macros are also recorded in @file{config.log}.
13782 @end defmac
13784 @anchor{AS_MESSAGE_LOG_FD}
13785 @defmac AS_MESSAGE_LOG_FD
13786 @asindex{MESSAGE_LOG_FD}
13787 This must either be empty, or expand to a file descriptor for log
13788 messages.  By default, @code{AS_INIT} sets this macro to the empty
13789 string for standalone M4sh clients, thus disabling logging.  However,
13790 @code{AC_INIT} shuffles things around so that both @command{configure}
13791 and @command{config.status} use @file{config.log} for log messages.
13792 Macros that run tools, like @code{AC_COMPILE_IFELSE} (@pxref{Running the
13793 Compiler}), redirect all output to this descriptor.  You may want to do
13794 so if you develop such a low-level macro.
13795 @end defmac
13797 @defmac AS_ORIGINAL_STDIN_FD
13798 @asindex{ORIGINAL_STDIN_FD}
13799 This must expand to a file descriptor for the original standard input.
13800 By default, @code{AS_INIT} sets this macro to @samp{0} for standalone
13801 M4sh clients.  However, @code{AC_INIT} shuffles things around for
13802 safety.
13804 When @command{configure} runs, it may accidentally execute an
13805 interactive command that has the same name as the non-interactive meant
13806 to be used or checked.  If the standard input was the terminal, such
13807 interactive programs would cause @command{configure} to stop, pending
13808 some user input.  Therefore @command{configure} redirects its standard
13809 input from @file{/dev/null} during its initialization.  This is not
13810 normally a problem, since @command{configure} normally does not need
13811 user input.
13813 In the extreme case where your @file{configure} script really needs to
13814 obtain some values from the original standard input, you can read them
13815 explicitly from @code{AS_ORIGINAL_STDIN_FD}.
13816 @end defmac
13819 @c =================================================== Writing Autoconf Macros.
13821 @node Writing Autoconf Macros
13822 @chapter Writing Autoconf Macros
13824 When you write a feature test that could be applicable to more than one
13825 software package, the best thing to do is encapsulate it in a new macro.
13826 Here are some instructions and guidelines for writing Autoconf macros.
13828 @menu
13829 * Macro Definitions::           Basic format of an Autoconf macro
13830 * Macro Names::                 What to call your new macros
13831 * Reporting Messages::          Notifying @command{autoconf} users
13832 * Dependencies Between Macros::  What to do when macros depend on other macros
13833 * Obsoleting Macros::           Warning about old ways of doing things
13834 * Coding Style::                Writing Autoconf macros @`a la Autoconf
13835 @end menu
13837 @node Macro Definitions
13838 @section Macro Definitions
13840 @defmac AC_DEFUN (@var{name}, @ovar{body})
13841 @acindex{DEFUN}
13842 Autoconf macros are defined using the @code{AC_DEFUN} macro, which is
13843 similar to the M4 builtin @code{m4_define} macro; this creates a macro
13844 named @var{name} and with @var{body} as its expansion.  In addition to
13845 defining a macro, @code{AC_DEFUN} adds to it some code that is used to
13846 constrain the order in which macros are called, while avoiding redundant
13847 output (@pxref{Prerequisite Macros}).
13848 @end defmac
13850 An Autoconf macro definition looks like this:
13852 @example
13853 AC_DEFUN(@var{macro-name}, @var{macro-body})
13854 @end example
13856 You can refer to any arguments passed to the macro as @samp{$1},
13857 @samp{$2}, etc.  @xref{Definitions, , How to define new macros, m4.info,
13858 GNU M4}, for more complete information on writing M4 macros.
13860 Most macros fall in one of two general categories.  The first category
13861 includes macros which take arguments, in order to generate output
13862 parameterized by those arguments.  Macros in this category are designed
13863 to be directly expanded, often multiple times, and should not be used as
13864 the argument to @code{AC_REQUIRE}.  The other category includes macros
13865 which are shorthand for a fixed block of text, and therefore do not take
13866 arguments.  For this category of macros, directly expanding the macro
13867 multiple times results in redundant output, so it is more common to use
13868 the macro as the argument to @code{AC_REQUIRE}, or to declare the macro
13869 with @code{AC_DEFUN_ONCE} (@pxref{One-Shot Macros}).
13871 Be sure to properly quote both the @var{macro-body} @emph{and} the
13872 @var{macro-name} to avoid any problems if the macro happens to have
13873 been previously defined.
13875 Each macro should have a header comment that gives its prototype, and a
13876 brief description.  When arguments have default values, display them in
13877 the prototype.  For example:
13879 @example
13880 # AC_MSG_ERROR(ERROR, [EXIT-STATUS = 1])
13881 # --------------------------------------
13882 m4_define([AC_MSG_ERROR],
13883   [@{ AS_MESSAGE([error: $1], [2])
13884      exit m4_default([$2], [1]); @}])
13885 @end example
13887 Comments about the macro should be left in the header comment.  Most
13888 other comments make their way into @file{configure}, so just keep
13889 using @samp{#} to introduce comments.
13891 @cindex @code{dnl}
13892 If you have some special comments about pure M4 code, comments
13893 that make no sense in @file{configure} and in the header comment, then
13894 use the builtin @code{dnl}: it causes M4 to discard the text
13895 through the next newline.
13897 Keep in mind that @code{dnl} is rarely needed to introduce comments;
13898 @code{dnl} is more useful to get rid of the newlines following macros
13899 that produce no output, such as @code{AC_REQUIRE}.
13901 Public third-party macros need to use @code{AC_DEFUN}, and not
13902 @code{m4_define}, in order to be found by @command{aclocal}
13903 (@pxref{Extending aclocal,,, automake, GNU Automake}).
13904 Additionally, if it is ever determined that a macro should be made
13905 obsolete, it is easy to convert from @code{AC_DEFUN} to @code{AU_DEFUN}
13906 in order to have @command{autoupdate} assist the user in choosing a
13907 better alternative, but there is no corresponding way to make
13908 @code{m4_define} issue an upgrade notice (@pxref{AU_DEFUN}).
13910 There is another subtle, but important, difference between using
13911 @code{m4_define} and @code{AC_DEFUN}: only the former is unaffected by
13912 @code{AC_REQUIRE}.  When writing a file, it is always safe to replace a
13913 block of text with a @code{m4_define} macro that will expand to the same
13914 text.  But replacing a block of text with an @code{AC_DEFUN} macro with
13915 the same content does not necessarily give the same results, because it
13916 changes the location where any embedded but unsatisfied
13917 @code{AC_REQUIRE} invocations within the block will be expanded.  For an
13918 example of this, see @ref{Expanded Before Required}.
13920 @node Macro Names
13921 @section Macro Names
13923 All of the public Autoconf macros have all-uppercase names in the
13924 namespace @samp{^AC_} to prevent them from accidentally conflicting with
13925 other text; Autoconf also reserves the namespace @samp{^_AC_} for
13926 internal macros.  All shell variables that they use for internal
13927 purposes have mostly-lowercase names starting with @samp{ac_}.  Autoconf
13928 also uses here-document delimiters in the namespace @samp{^_AC[A-Z]}.  During
13929 @command{configure}, files produced by Autoconf make heavy use of the
13930 file system namespace @samp{^conf}.
13932 Since Autoconf is built on top of M4sugar (@pxref{Programming in
13933 M4sugar}) and M4sh (@pxref{Programming in M4sh}), you must also be aware
13934 of those namespaces (@samp{^_?\(m4\|AS\)_}).  And since
13935 @file{configure.ac} is also designed to be scanned by Autoheader,
13936 Autoscan, Autoupdate, and Automake, you should be aware of the
13937 @samp{^_?A[HNUM]_} namespaces.  In general, you @emph{should not use}
13938 the namespace of a package that does not own the macro or shell code you
13939 are writing.
13941 To ensure that your macros don't conflict with present or future
13942 Autoconf macros, you should prefix your own macro names and any shell
13943 variables they use with some other sequence.  Possibilities include your
13944 initials, or an abbreviation for the name of your organization or
13945 software package.  Historically, people have not always followed the
13946 rule of using a namespace appropriate for their package, and this has
13947 made it difficult for determining the origin of a macro (and where to
13948 report bugs about that macro), as well as difficult for the true
13949 namespace owner to add new macros without interference from pre-existing
13950 uses of third-party macros.  Perhaps the best example of this confusion
13951 is the @code{AM_GNU_GETTEXT} macro, which belongs, not to Automake, but
13952 to Gettext.
13954 Most of the Autoconf macros' names follow a structured naming convention
13955 that indicates the kind of feature check by the name.  The macro names
13956 consist of several words, separated by underscores, going from most
13957 general to most specific.  The names of their cache variables use the
13958 same convention (@pxref{Cache Variable Names}, for more information on
13959 them).
13961 The first word of the name after the namespace initials (such as
13962 @samp{AC_}) usually tells the category
13963 of the feature being tested.  Here are the categories used in Autoconf for
13964 specific test macros, the kind of macro that you are more likely to
13965 write.  They are also used for cache variables, in all-lowercase.  Use
13966 them where applicable; where they're not, invent your own categories.
13968 @table @code
13969 @item C
13970 C language builtin features.
13971 @item DECL
13972 Declarations of C variables in header files.
13973 @item FUNC
13974 Functions in libraries.
13975 @item GROUP
13976 Posix group owners of files.
13977 @item HEADER
13978 Header files.
13979 @item LIB
13980 C libraries.
13981 @item PROG
13982 The base names of programs.
13983 @item MEMBER
13984 Members of aggregates.
13985 @item SYS
13986 Operating system features.
13987 @item TYPE
13988 C builtin or declared types.
13989 @item VAR
13990 C variables in libraries.
13991 @end table
13993 After the category comes the name of the particular feature being
13994 tested.  Any further words in the macro name indicate particular aspects
13995 of the feature.  For example, @code{AC_PROG_CC_STDC} checks whether the
13996 C compiler supports ISO Standard C.
13998 An internal macro should have a name that starts with an underscore;
13999 Autoconf internals should therefore start with @samp{_AC_}.
14000 Additionally, a macro that is an internal subroutine of another macro
14001 should have a name that starts with an underscore and the name of that
14002 other macro, followed by one or more words saying what the internal
14003 macro does.  For example, @code{AC_PATH_X} has internal macros
14004 @code{_AC_PATH_X_XMKMF} and @code{_AC_PATH_X_DIRECT}.
14006 @node Reporting Messages
14007 @section Reporting Messages
14008 @cindex Messages, from @command{autoconf}
14010 When macros statically diagnose abnormal situations, benign or fatal, it
14011 is possible to make @command{autoconf} detect the problem, and refuse to
14012 create @file{configure} in the case of an error.  The macros in this
14013 section are considered obsolescent, and new code should use M4sugar
14014 macros for this purpose, see @ref{Diagnostic Macros}.
14016 On the other hand, it is possible to want to detect errors when
14017 @command{configure} is run, which are dependent on the environment of
14018 the user rather than the maintainer.  For dynamic diagnostics, see
14019 @ref{Printing Messages}.
14021 @defmac AC_DIAGNOSE (@var{category}, @var{message})
14022 @acindex{DIAGNOSE}
14023 Report @var{message} as a warning (or as an error if requested by the
14024 user) if warnings of the @var{category} are turned on.  This macro is
14025 obsolescent; you are encouraged to use:
14026 @example
14027 m4_warn([@var{category}], [@var{message}])
14028 @end example
14029 @noindent
14030 instead.  @xref{m4_warn}, for more details, including valid
14031 @var{category} names.
14032 @end defmac
14034 @defmac AC_WARNING (@var{message})
14035 @acindex{WARNING}
14036 Report @var{message} as a syntax warning.  This macro is obsolescent;
14037 you are encouraged to use:
14038 @example
14039 m4_warn([syntax], [@var{message}])
14040 @end example
14041 @noindent
14042 instead.  @xref{m4_warn}, for more details, as well as better
14043 finer-grained categories of warnings (not all problems have to do with
14044 syntax).
14045 @end defmac
14047 @defmac AC_FATAL (@var{message})
14048 @acindex{FATAL}
14049 Report a severe error @var{message}, and have @command{autoconf} die.
14050 This macro is obsolescent; you are encouraged to use:
14051 @example
14052 m4_fatal([@var{message}])
14053 @end example
14054 @noindent
14055 instead.  @xref{m4_fatal}, for more details.
14056 @end defmac
14058 When the user runs @samp{autoconf -W error}, warnings from
14059 @code{m4_warn} (including those issued through @code{AC_DIAGNOSE} and
14060 @code{AC_WARNING}) are reported as errors, see @ref{autoconf Invocation}.
14062 @node Dependencies Between Macros
14063 @section Dependencies Between Macros
14064 @cindex Dependencies between macros
14066 Some Autoconf macros depend on other macros having been called first in
14067 order to work correctly.  Autoconf provides a way to ensure that certain
14068 macros are called if needed and a way to warn the user if macros are
14069 called in an order that might cause incorrect operation.
14071 @menu
14072 * Prerequisite Macros::         Ensuring required information
14073 * Suggested Ordering::          Warning about possible ordering problems
14074 * One-Shot Macros::             Ensuring a macro is called only once
14075 @end menu
14077 @node Prerequisite Macros
14078 @subsection Prerequisite Macros
14079 @cindex Prerequisite macros
14080 @cindex Macros, prerequisites
14082 A macro that you write might need to use values that have previously
14083 been computed by other macros.  For example, @code{AC_DECL_YYTEXT}
14084 examines the output of @code{flex} or @code{lex}, so it depends on
14085 @code{AC_PROG_LEX} having been called first to set the shell variable
14086 @code{LEX}.
14088 Rather than forcing the user of the macros to keep track of the
14089 dependencies between them, you can use the @code{AC_REQUIRE} macro to do
14090 it automatically.  @code{AC_REQUIRE} can ensure that a macro is only
14091 called if it is needed, and only called once.
14093 @defmac AC_REQUIRE (@var{macro-name})
14094 @acindex{REQUIRE}
14095 If the M4 macro @var{macro-name} has not already been called, call it
14096 (without any arguments).  Make sure to quote @var{macro-name} with
14097 square brackets.  @var{macro-name} must have been defined using
14098 @code{AC_DEFUN} or else contain a call to @code{AC_PROVIDE} to indicate
14099 that it has been called.
14101 @code{AC_REQUIRE} must be used inside a macro defined by @code{AC_DEFUN}; it
14102 must not be called from the top level.  Also, it does not make sense to
14103 require a macro that takes parameters.
14104 @end defmac
14106 @code{AC_REQUIRE} is often misunderstood.  It really implements
14107 dependencies between macros in the sense that if one macro depends upon
14108 another, the latter is expanded @emph{before} the body of the
14109 former.  To be more precise, the required macro is expanded before
14110 the outermost defined macro in the current expansion stack.
14111 In particular, @samp{AC_REQUIRE([FOO])} is not replaced with the body of
14112 @code{FOO}.  For instance, this definition of macros:
14114 @example
14115 @group
14116 AC_DEFUN([TRAVOLTA],
14117 [test "$body_temperature_in_celsius" -gt "38" &&
14118   dance_floor=occupied])
14119 AC_DEFUN([NEWTON_JOHN],
14120 [test "x$hair_style" = xcurly &&
14121   dance_floor=occupied])
14122 @end group
14124 @group
14125 AC_DEFUN([RESERVE_DANCE_FLOOR],
14126 [if date | grep '^Sat.*pm' >/dev/null 2>&1; then
14127   AC_REQUIRE([TRAVOLTA])
14128   AC_REQUIRE([NEWTON_JOHN])
14129 fi])
14130 @end group
14131 @end example
14133 @noindent
14134 with this @file{configure.ac}
14136 @example
14137 AC_INIT([Dance Manager], [1.0], [bug-dance@@example.org])
14138 RESERVE_DANCE_FLOOR
14139 if test "x$dance_floor" = xoccupied; then
14140   AC_MSG_ERROR([cannot pick up here, let's move])
14142 @end example
14144 @noindent
14145 does not leave you with a better chance to meet a kindred soul at
14146 other times than Saturday night since it expands into:
14148 @example
14149 @group
14150 test "$body_temperature_in_Celsius" -gt "38" &&
14151   dance_floor=occupied
14152 test "x$hair_style" = xcurly &&
14153   dance_floor=occupied
14155 if date | grep '^Sat.*pm' >/dev/null 2>&1; then
14159 @end group
14160 @end example
14162 This behavior was chosen on purpose: (i) it prevents messages in
14163 required macros from interrupting the messages in the requiring macros;
14164 (ii) it avoids bad surprises when shell conditionals are used, as in:
14166 @example
14167 @group
14168 if @dots{}; then
14169   AC_REQUIRE([SOME_CHECK])
14171 @dots{}
14172 SOME_CHECK
14173 @end group
14174 @end example
14176 However, this implementation can lead to another class of problems.
14177 Consider the case where an outer macro first expands, then indirectly
14178 requires, an inner macro:
14180 @example
14181 AC_DEFUN([TESTA], [[echo in A
14182 if test -n "$SEEN_A" ; then echo duplicate ; fi
14183 SEEN_A=:]])
14184 AC_DEFUN([TESTB], [AC_REQUIRE([TESTA])[echo in B
14185 if test -z "$SEEN_A" ; then echo bug ; fi]])
14186 AC_DEFUN([TESTC], [AC_REQUIRE([TESTB])[echo in C]])
14187 AC_DEFUN([OUTER], [[echo in OUTER]
14188 TESTA
14189 TESTC])
14190 OUTER
14191 @end example
14193 @noindent
14194 Prior to Autoconf 2.64, the implementation of @code{AC_REQUIRE}
14195 recognized that @code{TESTB} needed to be hoisted prior to the expansion
14196 of @code{OUTER}, but because @code{TESTA} had already been directly
14197 expanded, it failed to hoist @code{TESTA}.  Therefore, the expansion of
14198 @code{TESTB} occurs prior to its prerequisites, leading to the following
14199 output:
14201 @example
14202 in B
14204 in OUTER
14205 in A
14206 in C
14207 @end example
14209 @noindent
14210 Newer Autoconf is smart enough to recognize this situation, and hoists
14211 @code{TESTA} even though it has already been expanded, but issues a
14212 syntax warning in the process.  This is because the hoisted expansion of
14213 @code{TESTA} defeats the purpose of using @code{AC_REQUIRE} to avoid
14214 redundant code, and causes its own set of problems if the hoisted macro
14215 is not idempotent:
14217 @example
14218 in A
14219 in B
14220 in OUTER
14221 in A
14222 duplicate
14223 in C
14224 @end example
14226 The bug is not in Autoconf, but in the macro definitions.  If you ever
14227 pass a particular macro name to @code{AC_REQUIRE}, then you are implying
14228 that the macro only needs to be expanded once.  But to enforce this,
14229 either the macro must be declared with @code{AC_DEFUN_ONCE} (although
14230 this only helps in Autoconf 2.64 or newer), or all
14231 uses of that macro should be through @code{AC_REQUIRE}; directly
14232 expanding the macro defeats the point of using @code{AC_REQUIRE} to
14233 eliminate redundant expansion.  In the example, this rule of thumb was
14234 violated because @code{TESTB} requires @code{TESTA} while @code{OUTER}
14235 directly expands it.  One way of fixing the bug is to factor
14236 @code{TESTA} into two macros, the portion designed for direct and
14237 repeated use (here, named @code{TESTA}), and the portion designed for
14238 one-shot output and used only inside @code{AC_REQUIRE} (here, named
14239 @code{TESTA_PREREQ}).  Then, by fixing all clients to use the correct
14240 calling convention according to their needs:
14242 @example
14243 AC_DEFUN([TESTA], [AC_REQUIRE([TESTA_PREREQ])[echo in A]])
14244 AC_DEFUN([TESTA_PREREQ], [[echo in A_PREREQ
14245 if test -n "$SEEN_A" ; then echo duplicate ; fi
14246 SEEN_A=:]])
14247 AC_DEFUN([TESTB], [AC_REQUIRE([TESTA_PREREQ])[echo in B
14248 if test -z "$SEEN_A" ; then echo bug ; fi]])
14249 AC_DEFUN([TESTC], [AC_REQUIRE([TESTB])[echo in C]])
14250 AC_DEFUN([OUTER], [[echo in OUTER]
14251 TESTA
14252 TESTC])
14253 OUTER
14254 @end example
14256 @noindent
14257 the resulting output will then obey all dependency rules and avoid any
14258 syntax warnings, whether the script is built with old or new Autoconf
14259 versions:
14261 @example
14262 in A_PREREQ
14263 in B
14264 in OUTER
14265 in A
14266 in C
14267 @end example
14269 The helper macros @code{AS_IF} and @code{AS_CASE} may be used to
14270 enforce expansion of required macros outside of shell conditional
14271 constructs.  You are furthermore encouraged, although not required, to
14272 put all @code{AC_REQUIRE} calls
14273 at the beginning of a macro.  You can use @code{dnl} to avoid the empty
14274 lines they leave.
14276 @node Suggested Ordering
14277 @subsection Suggested Ordering
14278 @cindex Macros, ordering
14279 @cindex Ordering macros
14281 Some macros should be run before another macro if both are called, but
14282 neither @emph{requires} that the other be called.  For example, a macro
14283 that changes the behavior of the C compiler should be called before any
14284 macros that run the C compiler.  Many of these dependencies are noted in
14285 the documentation.
14287 Autoconf provides the @code{AC_BEFORE} macro to warn users when macros
14288 with this kind of dependency appear out of order in a
14289 @file{configure.ac} file.  The warning occurs when creating
14290 @command{configure} from @file{configure.ac}, not when running
14291 @command{configure}.
14293 For example, @code{AC_PROG_CPP} checks whether the C compiler
14294 can run the C preprocessor when given the @option{-E} option.  It should
14295 therefore be called after any macros that change which C compiler is
14296 being used, such as @code{AC_PROG_CC}.  So @code{AC_PROG_CC} contains:
14298 @example
14299 AC_BEFORE([$0], [AC_PROG_CPP])dnl
14300 @end example
14302 @noindent
14303 This warns the user if a call to @code{AC_PROG_CPP} has already occurred
14304 when @code{AC_PROG_CC} is called.
14306 @defmac AC_BEFORE (@var{this-macro-name}, @var{called-macro-name})
14307 @acindex{BEFORE}
14308 Make M4 print a warning message to the standard error output if
14309 @var{called-macro-name} has already been called.  @var{this-macro-name}
14310 should be the name of the macro that is calling @code{AC_BEFORE}.  The
14311 macro @var{called-macro-name} must have been defined using
14312 @code{AC_DEFUN} or else contain a call to @code{AC_PROVIDE} to indicate
14313 that it has been called.
14314 @end defmac
14316 @node One-Shot Macros
14317 @subsection One-Shot Macros
14318 @cindex One-shot macros
14319 @cindex Macros, called once
14321 Some macros should be called only once, either because calling them
14322 multiple time is unsafe, or because it is bad style.  For instance
14323 Autoconf ensures that @code{AC_CANONICAL_BUILD} and cousins
14324 (@pxref{Canonicalizing}) are evaluated only once, because it makes no
14325 sense to run these expensive checks more than once.  Such one-shot
14326 macros can be defined using @code{AC_DEFUN_ONCE}.
14328 @defmac AC_DEFUN_ONCE (@var{macro-name}, @var{macro-body})
14329 @acindex{DEFUN_ONCE}
14330 Declare macro @var{macro-name} like @code{AC_DEFUN} would (@pxref{Macro
14331 Definitions}), but add additional logic that guarantees that only the
14332 first use of the macro (whether by direct expansion or
14333 @code{AC_REQUIRE}) causes an expansion of @var{macro-body}; the
14334 expansion will occur before the start of any enclosing macro defined by
14335 @code{AC_DEFUN}.  Subsequent expansions are silently ignored.
14336 Generally, it does not make sense for @var{macro-body} to use parameters
14337 such as @code{$1}.
14338 @end defmac
14340 Prior to Autoconf 2.64, a macro defined by @code{AC_DEFUN_ONCE} would
14341 emit a warning if it was directly expanded a second time, so for
14342 portability, it is better to use @code{AC_REQUIRE} than direct
14343 invocation of @var{macro-name} inside a macro defined by @code{AC_DEFUN}
14344 (@pxref{Prerequisite Macros}).
14346 @node Obsoleting Macros
14347 @section Obsoleting Macros
14348 @cindex Obsoleting macros
14349 @cindex Macros, obsoleting
14351 Configuration and portability technology has evolved over the years.
14352 Often better ways of solving a particular problem are developed, or
14353 ad-hoc approaches are systematized.  This process has occurred in many
14354 parts of Autoconf.  One result is that some of the macros are now
14355 considered @dfn{obsolete}; they still work, but are no longer considered
14356 the best thing to do, hence they should be replaced with more modern
14357 macros.  Ideally, @command{autoupdate} should replace the old macro calls
14358 with their modern implementation.
14360 Autoconf provides a simple means to obsolete a macro.
14362 @anchor{AU_DEFUN}
14363 @defmac AU_DEFUN (@var{old-macro}, @var{implementation}, @ovar{message})
14364 @auindex{DEFUN}
14365 Define @var{old-macro} as @var{implementation}.  The only difference
14366 with @code{AC_DEFUN} is that the user is warned that
14367 @var{old-macro} is now obsolete.
14369 If she then uses @command{autoupdate}, the call to @var{old-macro} is
14370 replaced by the modern @var{implementation}.  @var{message} should
14371 include information on what to do after running @command{autoupdate};
14372 @command{autoupdate} prints it as a warning, and includes it
14373 in the updated @file{configure.ac} file.
14375 The details of this macro are hairy: if @command{autoconf} encounters an
14376 @code{AU_DEFUN}ed macro, all macros inside its second argument are expanded
14377 as usual.  However, when @command{autoupdate} is run, only M4 and M4sugar
14378 macros are expanded here, while all other macros are disabled and
14379 appear literally in the updated @file{configure.ac}.
14380 @end defmac
14382 @defmac AU_ALIAS (@var{old-name}, @var{new-name})
14383 @auindex{ALIAS}
14384 Used if the @var{old-name} is to be replaced by a call to @var{new-macro}
14385 with the same parameters.  This happens for example if the macro was renamed.
14386 @end defmac
14388 @node Coding Style
14389 @section Coding Style
14390 @cindex Coding style
14392 The Autoconf macros follow a strict coding style.  You are encouraged to
14393 follow this style, especially if you intend to distribute your macro,
14394 either by contributing it to Autoconf itself or the
14395 @uref{http://@/www.gnu.org/@/software/@/autoconf-archive/, Autoconf Macro
14396 Archive}, or by other means.
14398 The first requirement is to pay great attention to the quotation.  For
14399 more details, see @ref{Autoconf Language}, and @ref{M4 Quotation}.
14401 Do not try to invent new interfaces.  It is likely that there is a macro
14402 in Autoconf that resembles the macro you are defining: try to stick to
14403 this existing interface (order of arguments, default values, etc.).  We
14404 @emph{are} conscious that some of these interfaces are not perfect;
14405 nevertheless, when harmless, homogeneity should be preferred over
14406 creativity.
14408 Be careful about clashes both between M4 symbols and between shell
14409 variables.
14411 If you stick to the suggested M4 naming scheme (@pxref{Macro Names}),
14412 you are unlikely to generate conflicts.  Nevertheless, when you need to
14413 set a special value, @emph{avoid using a regular macro name}; rather,
14414 use an ``impossible'' name.  For instance, up to version 2.13, the macro
14415 @code{AC_SUBST} used to remember what @var{symbol} macros were already defined
14416 by setting @code{AC_SUBST_@var{symbol}}, which is a regular macro name.
14417 But since there is a macro named @code{AC_SUBST_FILE}, it was just
14418 impossible to @samp{AC_SUBST(FILE)}!  In this case,
14419 @code{AC_SUBST(@var{symbol})} or @code{_AC_SUBST(@var{symbol})} should
14420 have been used (yes, with the parentheses).
14421 @c or better yet, high-level macros such as @code{m4_expand_once}
14423 No Autoconf macro should ever enter the user-variable name space; i.e.,
14424 except for the variables that are the actual result of running the
14425 macro, all shell variables should start with @code{ac_}.  In
14426 addition, small macros or any macro that is likely to be embedded in
14427 other macros should be careful not to use obvious names.
14429 @cindex @code{dnl}
14430 Do not use @code{dnl} to introduce comments: most of the comments you
14431 are likely to write are either header comments which are not output
14432 anyway, or comments that should make their way into @file{configure}.
14433 There are exceptional cases where you do want to comment special M4
14434 constructs, in which case @code{dnl} is right, but keep in mind that it
14435 is unlikely.
14437 M4 ignores the leading blanks and newlines before each argument.
14438 Use this feature to
14439 indent in such a way that arguments are (more or less) aligned with the
14440 opening parenthesis of the macro being called.  For instance, instead of
14442 @example
14443 AC_CACHE_CHECK(for EMX OS/2 environment,
14444 ac_cv_emxos2,
14445 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM(, [return __EMX__;])],
14446 [ac_cv_emxos2=yes], [ac_cv_emxos2=no])])
14447 @end example
14449 @noindent
14450 write
14452 @example
14453 AC_CACHE_CHECK([for EMX OS/2 environment], [ac_cv_emxos2],
14454 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([], [return __EMX__;])],
14455                    [ac_cv_emxos2=yes],
14456                    [ac_cv_emxos2=no])])
14457 @end example
14459 @noindent
14460 or even
14462 @example
14463 AC_CACHE_CHECK([for EMX OS/2 environment],
14464                [ac_cv_emxos2],
14465                [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([],
14466                                                    [return __EMX__;])],
14467                                   [ac_cv_emxos2=yes],
14468                                   [ac_cv_emxos2=no])])
14469 @end example
14471 When using @code{AC_RUN_IFELSE} or any macro that cannot work when
14472 cross-compiling, provide a pessimistic value (typically @samp{no}).
14474 Feel free to use various tricks to prevent auxiliary tools, such as
14475 syntax-highlighting editors, from behaving improperly.  For instance,
14476 instead of:
14478 @example
14479 m4_bpatsubst([$1], [$"])
14480 @end example
14482 @noindent
14485 @example
14486 m4_bpatsubst([$1], [$""])
14487 @end example
14489 @noindent
14490 so that Emacsen do not open an endless ``string'' at the first quote.
14491 For the same reasons, avoid:
14493 @example
14494 test $[#] != 0
14495 @end example
14497 @noindent
14498 and use:
14500 @example
14501 test $[@@%:@@] != 0
14502 @end example
14504 @noindent
14505 Otherwise, the closing bracket would be hidden inside a @samp{#}-comment,
14506 breaking the bracket-matching highlighting from Emacsen.  Note the
14507 preferred style to escape from M4: @samp{$[1]}, @samp{$[@@]}, etc.  Do
14508 not escape when it is unnecessary.  Common examples of useless quotation
14509 are @samp{[$]$1} (write @samp{$$1}), @samp{[$]var} (use @samp{$var}),
14510 etc.  If you add portability issues to the picture, you'll prefer
14511 @samp{$@{1+"$[@@]"@}} to @samp{"[$]@@"}, and you'll prefer do something
14512 better than hacking Autoconf @code{:-)}.
14514 When using @command{sed}, don't use @option{-e} except for indenting
14515 purposes.  With the @code{s} and @code{y} commands, the preferred
14516 separator is @samp{/} unless @samp{/} itself might appear in the pattern
14517 or replacement, in which case you should use @samp{|}, or optionally
14518 @samp{,} if you know the pattern and replacement cannot contain a file
14519 name.  If none of these characters will do, choose a printable character
14520 that cannot appear in the pattern or replacement.  Characters from the
14521 set @samp{"#$&'()*;<=>?`|~} are good choices if the pattern or
14522 replacement might contain a file name, since they have special meaning
14523 to the shell and are less likely to occur in file names.
14525 @xref{Macro Definitions}, for details on how to define a macro.  If a
14526 macro doesn't use @code{AC_REQUIRE}, is expected to never be the object
14527 of an @code{AC_REQUIRE} directive, and macros required by other macros
14528 inside arguments do not need to be expanded before this macro, then
14529 use @code{m4_define}.  In case of doubt, use @code{AC_DEFUN}.
14530 Also take into account that public third-party macros need to use
14531 @code{AC_DEFUN} in order to be found by @command{aclocal}
14532 (@pxref{Extending aclocal,,, automake, GNU Automake}).
14533 All the @code{AC_REQUIRE} statements should be at the beginning of the
14534 macro, and each statement should be followed by @code{dnl}.
14536 You should not rely on the number of arguments: instead of checking
14537 whether an argument is missing, test that it is not empty.  It provides
14538 both a simpler and a more predictable interface to the user, and saves
14539 room for further arguments.
14541 Unless the macro is short, try to leave the closing @samp{])} at the
14542 beginning of a line, followed by a comment that repeats the name of the
14543 macro being defined.  This introduces an additional newline in
14544 @command{configure}; normally, that is not a problem, but if you want to
14545 remove it you can use @samp{[]dnl} on the last line.  You can similarly
14546 use @samp{[]dnl} after a macro call to remove its newline.  @samp{[]dnl}
14547 is recommended instead of @samp{dnl} to ensure that M4 does not
14548 interpret the @samp{dnl} as being attached to the preceding text or
14549 macro output.  For example, instead of:
14551 @example
14552 AC_DEFUN([AC_PATH_X],
14553 [AC_MSG_CHECKING([for X])
14554 AC_REQUIRE_CPP()
14555 @r{# @dots{}omitted@dots{}}
14556   AC_MSG_RESULT([libraries $x_libraries, headers $x_includes])
14557 fi])
14558 @end example
14560 @noindent
14561 you would write:
14563 @example
14564 AC_DEFUN([AC_PATH_X],
14565 [AC_REQUIRE_CPP()[]dnl
14566 AC_MSG_CHECKING([for X])
14567 @r{# @dots{}omitted@dots{}}
14568   AC_MSG_RESULT([libraries $x_libraries, headers $x_includes])
14569 fi[]dnl
14570 ])# AC_PATH_X
14571 @end example
14573 If the macro is long, try to split it into logical chunks.  Typically,
14574 macros that check for a bug in a function and prepare its
14575 @code{AC_LIBOBJ} replacement should have an auxiliary macro to perform
14576 this setup.  Do not hesitate to introduce auxiliary macros to factor
14577 your code.
14579 In order to highlight the recommended coding style, here is a macro
14580 written the old way:
14582 @example
14583 dnl Check for EMX on OS/2.
14584 dnl _AC_EMXOS2
14585 AC_DEFUN(_AC_EMXOS2,
14586 [AC_CACHE_CHECK(for EMX OS/2 environment, ac_cv_emxos2,
14587 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM(, return __EMX__;)],
14588 ac_cv_emxos2=yes, ac_cv_emxos2=no)])
14589 test "x$ac_cv_emxos2" = xyes && EMXOS2=yes])
14590 @end example
14592 @noindent
14593 and the new way:
14595 @example
14596 # _AC_EMXOS2
14597 # ----------
14598 # Check for EMX on OS/2.
14599 m4_define([_AC_EMXOS2],
14600 [AC_CACHE_CHECK([for EMX OS/2 environment], [ac_cv_emxos2],
14601 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([], [return __EMX__;])],
14602                    [ac_cv_emxos2=yes],
14603                    [ac_cv_emxos2=no])])
14604 test "x$ac_cv_emxos2" = xyes && EMXOS2=yes[]dnl
14605 ])# _AC_EMXOS2
14606 @end example
14611 @c ============================================= Portable Shell Programming
14613 @node Portable Shell
14614 @chapter Portable Shell Programming
14615 @cindex Portable shell programming
14617 When writing your own checks, there are some shell-script programming
14618 techniques you should avoid in order to make your code portable.  The
14619 Bourne shell and upward-compatible shells like the Korn shell and Bash
14620 have evolved over the years, and many features added to the original
14621 System7 shell are now supported on all interesting porting targets.
14622 However, the following discussion between Russ Allbery and Robert Lipe
14623 is worth reading:
14625 @noindent
14626 Russ Allbery:
14628 @quotation
14629 The GNU assumption that @command{/bin/sh} is the one and only shell
14630 leads to a permanent deadlock.  Vendors don't want to break users'
14631 existing shell scripts, and there are some corner cases in the Bourne
14632 shell that are not completely compatible with a Posix shell.  Thus,
14633 vendors who have taken this route will @emph{never} (OK@dots{}``never say
14634 never'') replace the Bourne shell (as @command{/bin/sh}) with a
14635 Posix shell.
14636 @end quotation
14638 @noindent
14639 Robert Lipe:
14641 @quotation
14642 This is exactly the problem.  While most (at least most System V's) do
14643 have a Bourne shell that accepts shell functions most vendor
14644 @command{/bin/sh} programs are not the Posix shell.
14646 So while most modern systems do have a shell @emph{somewhere} that meets the
14647 Posix standard, the challenge is to find it.
14648 @end quotation
14650 For this reason, part of the job of M4sh (@pxref{Programming in M4sh})
14651 is to find such a shell.  But to prevent trouble, if you're not using
14652 M4sh you should not take advantage of features that were added after Unix
14653 version 7, circa 1977 (@pxref{Systemology}); you should not use aliases,
14654 negated character classes, or even @command{unset}.  @code{#} comments,
14655 while not in Unix version 7, were retrofitted in the original Bourne
14656 shell and can be assumed to be part of the least common denominator.
14658 On the other hand, if you're using M4sh you can assume that the shell
14659 has the features that were added in SVR2 (circa 1984), including shell
14660 functions,
14661 @command{return}, @command{unset}, and I/O redirection for builtins.  For
14662 more information, refer to @uref{http://@/www.in-ulm.de/@/~mascheck/@/bourne/}.
14663 However, some pitfalls have to be avoided for portable use of these
14664 constructs; these will be documented in the rest of this chapter.
14665 See in particular @ref{Shell Functions} and @ref{Limitations of
14666 Builtins, , Limitations of Shell Builtins}.
14668 Some ancient systems have quite
14669 small limits on the length of the @samp{#!} line; for instance, 32
14670 bytes (not including the newline) on SunOS 4.
14671 However, these ancient systems are no longer of practical concern.
14673 The set of external programs you should run in a @command{configure} script
14674 is fairly small.  @xref{Utilities in Makefiles, , Utilities in
14675 Makefiles, standards, The GNU Coding Standards}, for the list.  This
14676 restriction allows users to start out with a fairly small set of
14677 programs and build the rest, avoiding too many interdependencies between
14678 packages.
14680 Some of these external utilities have a portable subset of features; see
14681 @ref{Limitations of Usual Tools}.
14683 There are other sources of documentation about shells.  The
14684 specification for the Posix
14685 @uref{http://@/www.opengroup.org/@/susv3/@/utilities/@/xcu_chap02@/.html, Shell
14686 Command Language}, though more generous than the restrictive shell
14687 subset described above, is fairly portable nowadays.  Also please see
14688 @uref{http://@/www.faqs.org/@/faqs/@/unix-faq/@/shell/, the Shell FAQs}.
14690 @menu
14691 * Shellology::                  A zoology of shells
14692 * Here-Documents::              Quirks and tricks
14693 * File Descriptors::            FDs and redirections
14694 * File System Conventions::     File names
14695 * Shell Pattern Matching::      Pattern matching
14696 * Shell Substitutions::         Variable and command expansions
14697 * Assignments::                 Varying side effects of assignments
14698 * Parentheses::                 Parentheses in shell scripts
14699 * Slashes::                     Slashes in shell scripts
14700 * Special Shell Variables::     Variables you should not change
14701 * Shell Functions::             What to look out for if you use them
14702 * Limitations of Builtins::     Portable use of not so portable /bin/sh
14703 * Limitations of Usual Tools::  Portable use of portable tools
14704 @end menu
14706 @node Shellology
14707 @section Shellology
14708 @cindex Shellology
14710 There are several families of shells, most prominently the Bourne family
14711 and the C shell family which are deeply incompatible.  If you want to
14712 write portable shell scripts, avoid members of the C shell family.  The
14713 @uref{http://@/www.faqs.org/@/faqs/@/unix-faq/@/shell/@/shell-differences/, the
14714 Shell difference FAQ} includes a small history of Posix shells, and a
14715 comparison between several of them.
14717 Below we describe some of the members of the Bourne shell family.
14719 @table @asis
14720 @item Ash
14721 @cindex Ash
14722 Ash is often used on GNU/Linux and BSD
14723 systems as a light-weight Bourne-compatible shell.  Ash 0.2 has some
14724 bugs that are fixed in the 0.3.x series, but portable shell scripts
14725 should work around them, since version 0.2 is still shipped with many
14726 GNU/Linux distributions.
14728 To be compatible with Ash 0.2:
14730 @itemize @minus
14731 @item
14732 don't use @samp{$?} after expanding empty or unset variables,
14733 or at the start of an @command{eval}:
14735 @example
14736 foo=
14737 false
14738 $foo
14739 echo "Do not use it: $?"
14740 false
14741 eval 'echo "Do not use it: $?"'
14742 @end example
14744 @item
14745 don't use command substitution within variable expansion:
14747 @example
14748 cat $@{FOO=`bar`@}
14749 @end example
14751 @item
14752 beware that single builtin substitutions are not performed by a
14753 subshell, hence their effect applies to the current shell!  @xref{Shell
14754 Substitutions}, item ``Command Substitution''.
14755 @end itemize
14757 @item Bash
14758 @cindex Bash
14759 To detect whether you are running Bash, test whether
14760 @code{BASH_VERSION} is set.  To require
14761 Posix compatibility, run @samp{set -o posix}.  @xref{Bash POSIX
14762 Mode, , Bash Posix Mode, bash, The GNU Bash Reference
14763 Manual}, for details.
14765 @item Bash 2.05 and later
14766 @cindex Bash 2.05 and later
14767 Versions 2.05 and later of Bash use a different format for the
14768 output of the @command{set} builtin, designed to make evaluating its
14769 output easier.  However, this output is not compatible with earlier
14770 versions of Bash (or with many other shells, probably).  So if
14771 you use Bash 2.05 or higher to execute @command{configure},
14772 you'll need to use Bash 2.05 for all other build tasks as well.
14774 @item Ksh
14775 @cindex Ksh
14776 @cindex Korn shell
14777 @prindex @samp{ksh}
14778 @prindex @samp{ksh88}
14779 @prindex @samp{ksh93}
14780 The Korn shell is compatible with the Bourne family and it mostly
14781 conforms to Posix.  It has two major variants commonly
14782 called @samp{ksh88} and @samp{ksh93}, named after the years of initial
14783 release.  It is usually called @command{ksh}, but is called @command{sh}
14784 on some hosts if you set your path appropriately.
14786 Solaris systems have three variants:
14787 @prindex @command{/usr/bin/ksh} on Solaris
14788 @command{/usr/bin/ksh} is @samp{ksh88}; it is
14789 standard on Solaris 2.0 and later.
14790 @prindex @command{/usr/xpg4/bin/sh} on Solaris
14791 @command{/usr/xpg4/bin/sh} is a Posix-compliant variant of
14792 @samp{ksh88}; it is standard on Solaris 9 and later.
14793 @prindex @command{/usr/dt/bin/dtksh} on Solaris
14794 @command{/usr/dt/bin/dtksh} is @samp{ksh93}.
14795 Variants that are not standard may be parts of optional
14796 packages.  There is no extra charge for these packages, but they are
14797 not part of a minimal OS install and therefore some installations may
14798 not have it.
14800 Starting with Tru64 Version 4.0, the Korn shell @command{/usr/bin/ksh}
14801 is also available as @command{/usr/bin/posix/sh}.  If the environment
14802 variable @env{BIN_SH} is set to @code{xpg4}, subsidiary invocations of
14803 the standard shell conform to Posix.
14805 @item Pdksh
14806 @prindex @samp{pdksh}
14807 A public-domain clone of the Korn shell called @command{pdksh} is widely
14808 available: it has most of the @samp{ksh88} features along with a few of
14809 its own.  It usually sets @code{KSH_VERSION}, except if invoked as
14810 @command{/bin/sh} on OpenBSD, and similarly to Bash you can require
14811 Posix compatibility by running @samp{set -o posix}.  Unfortunately, with
14812 @command{pdksh} 5.2.14 (the latest stable version as of January 2007)
14813 Posix mode is buggy and causes @command{pdksh} to depart from Posix in
14814 at least one respect, see @ref{Shell Substitutions}.
14816 @item Zsh
14817 @cindex Zsh
14818 To detect whether you are running @command{zsh}, test whether
14819 @code{ZSH_VERSION} is set.  By default @command{zsh} is @emph{not}
14820 compatible with the Bourne shell: you must execute @samp{emulate sh},
14821 and for @command{zsh} versions before 3.1.6-dev-18 you must also
14822 set @code{NULLCMD} to @samp{:}.  @xref{Compatibility, , Compatibility,
14823 zsh, The Z Shell Manual}, for details.
14825 The default Mac OS X @command{sh} was originally Zsh; it was changed to
14826 Bash in Mac OS X 10.2.
14827 @end table
14829 @node Here-Documents
14830 @section Here-Documents
14831 @cindex Here-documents
14832 @cindex Shell here-documents
14834 Don't rely on @samp{\} being preserved just because it has no special
14835 meaning together with the next symbol.  In the native @command{sh}
14836 on OpenBSD 2.7 @samp{\"} expands to @samp{"} in here-documents with
14837 unquoted delimiter.  As a general rule, if @samp{\\} expands to @samp{\}
14838 use @samp{\\} to get @samp{\}.
14840 With OpenBSD 2.7's @command{sh}
14842 @example
14843 @group
14844 $ @kbd{cat <<EOF
14845 > \" \\
14846 > EOF}
14847 " \
14848 @end group
14849 @end example
14851 @noindent
14852 and with Bash:
14854 @example
14855 @group
14856 bash-2.04$ @kbd{cat <<EOF
14857 > \" \\
14858 > EOF}
14859 \" \
14860 @end group
14861 @end example
14863 Some shells mishandle large here-documents: for example,
14864 Solaris 10 @command{dtksh} and the UnixWare 7.1.1 Posix shell, which are
14865 derived from Korn shell version M-12/28/93d, mishandle braced variable
14866 expansion that crosses a 1024- or 4096-byte buffer boundary
14867 within a here-document.  Only the part of the variable name after the boundary
14868 is used.  For example, @code{$@{variable@}} could be replaced by the expansion
14869 of @code{$@{ble@}}.  If the end of the variable name is aligned with the block
14870 boundary, the shell reports an error, as if you used @code{$@{@}}.
14871 Instead of @code{$@{variable-default@}}, the shell may expand
14872 @code{$@{riable-default@}}, or even @code{$@{fault@}}.  This bug can often
14873 be worked around by omitting the braces: @code{$variable}.  The bug was
14874 fixed in
14875 @samp{ksh93g} (1998-04-30) but as of 2006 many operating systems were
14876 still shipping older versions with the bug.
14878 Many shells (including the Bourne shell) implement here-documents
14879 inefficiently.  In particular, some shells can be extremely inefficient when
14880 a single statement contains many here-documents.  For instance if your
14881 @file{configure.ac} includes something like:
14883 @example
14884 @group
14885 if <cross_compiling>; then
14886   assume this and that
14887 else
14888   check this
14889   check that
14890   check something else
14891   @dots{}
14892   on and on forever
14893   @dots{}
14895 @end group
14896 @end example
14898 A shell parses the whole @code{if}/@code{fi} construct, creating
14899 temporary files for each here-document in it.  Some shells create links
14900 for such here-documents on every @code{fork}, so that the clean-up code
14901 they had installed correctly removes them.  It is creating the links
14902 that can take the shell forever.
14904 Moving the tests out of the @code{if}/@code{fi}, or creating multiple
14905 @code{if}/@code{fi} constructs, would improve the performance
14906 significantly.  Anyway, this kind of construct is not exactly the
14907 typical use of Autoconf.  In fact, it's even not recommended, because M4
14908 macros can't look into shell conditionals, so we may fail to expand a
14909 macro when it was expanded before in a conditional path, and the
14910 condition turned out to be false at runtime, and we end up not
14911 executing the macro at all.
14913 Be careful with the use of @samp{<<-} to unindent here-documents.  The
14914 behavior is only portable for stripping leading @key{TAB}s, and things
14915 can silently break if an overzealous editor converts to using leading
14916 spaces (not all shells are nice enough to warn about unterminated
14917 here-documents).
14919 @example
14920 $ @kbd{printf 'cat <<-x\n\t1\n\t 2\n\tx\n' | bash && echo done}
14923 done
14924 $ @kbd{printf 'cat <<-x\n 1\n  2\n x\n' | bash-3.2 && echo done}
14926   2
14928 done
14929 @end example
14931 @node File Descriptors
14932 @section File Descriptors
14933 @cindex Descriptors
14934 @cindex File descriptors
14935 @cindex Shell file descriptors
14937 Most shells, if not all (including Bash, Zsh, Ash), output traces on
14938 stderr, even for subshells.  This might result in undesirable content
14939 if you meant to capture the standard-error output of the inner command:
14941 @example
14942 $ @kbd{ash -x -c '(eval "echo foo >&2") 2>stderr'}
14943 $ @kbd{cat stderr}
14944 + eval echo foo >&2
14945 + echo foo
14947 $ @kbd{bash -x -c '(eval "echo foo >&2") 2>stderr'}
14948 $ @kbd{cat stderr}
14949 + eval 'echo foo >&2'
14950 ++ echo foo
14952 $ @kbd{zsh -x -c '(eval "echo foo >&2") 2>stderr'}
14953 @i{# Traces on startup files deleted here.}
14954 $ @kbd{cat stderr}
14955 +zsh:1> eval echo foo >&2
14956 +zsh:1> echo foo
14958 @end example
14960 @noindent
14961 One workaround is to grep out uninteresting lines, hoping not to remove
14962 good ones.
14964 If you intend to redirect both standard error and standard output,
14965 redirect standard output first.  This works better with HP-UX,
14966 since its shell mishandles tracing if standard error is redirected
14967 first:
14969 @example
14970 $ @kbd{sh -x -c ': 2>err >out'}
14971 + :
14972 + 2> err $ @kbd{cat err}
14973 1> out
14974 @end example
14976 Don't try to redirect the standard error of a command substitution.  It
14977 must be done @emph{inside} the command substitution.  When running
14978 @samp{: `cd /zorglub` 2>/dev/null} expect the error message to
14979 escape, while @samp{: `cd /zorglub 2>/dev/null`} works properly.
14981 On the other hand, some shells, such as Solaris or FreeBSD
14982 @command{/bin/sh}, warn about missing programs before performing
14983 redirections.  Therefore, to silently check whether a program exists, it
14984 is necessary to perform redirections on a subshell:
14986 @example
14987 $ @kbd{/bin/sh -c 'nosuch 2>/dev/null'}
14988 nosuch: not found
14989 $ @kbd{/bin/sh -c '(nosuch) 2>/dev/null'}
14990 $ @kbd{bash -c 'nosuch 2>/dev/null'}
14991 @end example
14993 FreeBSD 6.2 sh may mix the trace output lines from the statements in a
14994 shell pipeline.
14996 It is worth noting that Zsh (but not Ash nor Bash) makes it possible
14997 in assignments though: @samp{foo=`cd /zorglub` 2>/dev/null}.
14999 Some shells, like @command{ash}, don't recognize bi-directional
15000 redirection (@samp{<>}).  And even on shells that recognize it, it is
15001 not portable to use on fifos: Posix does not require read-write support
15002 for named pipes, and Cygwin does not support it:
15004 @example
15005 $ @kbd{mkfifo fifo}
15006 $ @kbd{exec 5<>fifo}
15007 $ @kbd{echo hi >&5}
15008 bash: echo: write error: Communication error on send
15009 @end example
15011 When catering to old systems, don't redirect the same file descriptor
15012 several times, as you are doomed to failure under Ultrix.
15014 @example
15015 ULTRIX V4.4 (Rev. 69) System #31: Thu Aug 10 19:42:23 GMT 1995
15016 UWS V4.4 (Rev. 11)
15017 $ @kbd{eval 'echo matter >fullness' >void}
15018 illegal io
15019 $ @kbd{eval '(echo matter >fullness)' >void}
15020 illegal io
15021 $ @kbd{(eval '(echo matter >fullness)') >void}
15022 Ambiguous output redirect.
15023 @end example
15025 @noindent
15026 In each case the expected result is of course @file{fullness} containing
15027 @samp{matter} and @file{void} being empty.  However, this bug is
15028 probably not of practical concern to modern platforms.
15030 Solaris 10 @command{sh} will try to optimize away a @command{:} command
15031 in a loop after the first iteration, even if it is redirected:
15033 @example
15034 $ @kbd{for i in 1 2 3 ; do : >x$i; done}
15035 $ @kbd{ls}
15037 @end example
15039 @noindent
15040 As a workaround, @command{echo} or @command{eval} can be used.
15042 Don't rely on file descriptors 0, 1, and 2 remaining closed in a
15043 subsidiary program.  If any of these descriptors is closed, the
15044 operating system may open an unspecified file for the descriptor in the
15045 new process image.  Posix says this may be done only if the subsidiary
15046 program is set-user-ID or set-group-ID, but HP-UX 11.23 does
15047 it even for ordinary programs.
15049 Don't rely on open file descriptors being open in child processes.  In
15050 @command{ksh}, file descriptors above 2 which are opened using
15051 @samp{exec @var{n}>file} are closed by a subsequent @samp{exec} (such as
15052 that involved in the fork-and-exec which runs a program or script).
15053 Thus, using @command{sh}, we have:
15055 @example
15056 $ @kbd{cat ./descrips}
15057 #!/bin/sh -
15058 echo hello >&5
15059 $ @kbd{exec 5>t}
15060 $ @kbd{./descrips}
15061 $ @kbd{cat t}
15062 hello
15064 @end example
15066 @noindent
15067 But using ksh:
15069 @example
15070 $ @kbd{exec 5>t}
15071 $ @kbd{./descrips}
15072 hello
15073 $ @kbd{cat t}
15075 @end example
15077 @noindent
15078 Within the process which runs the @samp{descrips} script, file
15079 descriptor 5 is closed.
15081 Don't rely on duplicating a closed file descriptor to cause an
15082 error.  With Solaris @command{/bin/sh}, when the redirection fails, the
15083 output goes to the original file descriptor.
15085 @example
15086 $ @kbd{bash -c 'echo hi >&3' 3>&-; echo $?}
15087 bash: 3: Bad file descriptor
15089 $ @kbd{/bin/sh -c 'echo hi >&3' 3>&-; echo $?}
15092 @end example
15094 Fortunately, an attempt to close an already closed file descriptor will
15095 portably succeed.  Likewise, it is safe to use either style of
15096 @samp{@var{n}<&-} or @samp{@var{n}>&-} for closing a file descriptor,
15097 even if it doesn't match the read/write mode that the file descriptor
15098 was opened with.
15100 DOS variants cannot rename or remove open files, such as in
15101 @samp{mv foo bar >foo} or @samp{rm foo >foo}, even though this is
15102 perfectly portable among Posix hosts.
15104 A few ancient systems reserved some file descriptors.  By convention,
15105 file descriptor 3 was opened to @file{/dev/tty} when you logged into
15106 Eighth Edition (1985) through Tenth Edition Unix (1989).  File
15107 descriptor 4 had a special use on the Stardent/Kubota Titan (circa
15108 1990), though we don't now remember what it was.  Both these systems are
15109 obsolete, so it's now safe to treat file descriptors 3 and 4 like any
15110 other file descriptors.
15112 On the other hand, you can't portably use multi-digit file descriptors.
15113 Solaris @command{ksh} doesn't understand any file descriptor larger than
15114 @samp{9}:
15116 @example
15117 $ @kbd{bash -c 'exec 10>&-'; echo $?}
15119 $ @kbd{ksh -c 'exec 9>&-'; echo $?}
15121 $ @kbd{ksh -c 'exec 10>&-'; echo $?}
15122 ksh[1]: exec: 10: not found
15124 @end example
15126 @node File System Conventions
15127 @section File System Conventions
15128 @cindex File system conventions
15130 Autoconf uses shell-script processing extensively, so the file names
15131 that it processes should not contain characters that are special to the
15132 shell.  Special characters include space, tab, newline, NUL, and
15133 the following:
15135 @example
15136 " # $ & ' ( ) * ; < = > ? [ \ ` |
15137 @end example
15139 Also, file names should not begin with @samp{~} or @samp{-}, and should
15140 contain neither @samp{-} immediately after @samp{/} nor @samp{~}
15141 immediately after @samp{:}.  On Posix-like platforms, directory names
15142 should not contain @samp{:}, as this runs afoul of @samp{:} used as the
15143 path separator.
15145 These restrictions apply not only to the files that you distribute, but
15146 also to the absolute file names of your source, build, and destination
15147 directories.
15149 On some Posix-like platforms, @samp{!} and @samp{^} are special too, so
15150 they should be avoided.
15152 Posix lets implementations treat leading @file{//} specially, but
15153 requires leading @file{///} and beyond to be equivalent to @file{/}.
15154 Most Unix variants treat @file{//} like @file{/}.  However, some treat
15155 @file{//} as a ``super-root'' that can provide access to files that are
15156 not otherwise reachable from @file{/}.  The super-root tradition began
15157 with Apollo Domain/OS, which died out long ago, but unfortunately Cygwin
15158 has revived it.
15160 While @command{autoconf} and friends are usually run on some Posix
15161 variety, they can be used on other systems, most notably DOS
15162 variants.  This impacts several assumptions regarding file names.
15164 @noindent
15165 For example, the following code:
15167 @example
15168 case $foo_dir in
15169   /*) # Absolute
15170      ;;
15171   *)
15172      foo_dir=$dots$foo_dir ;;
15173 esac
15174 @end example
15176 @noindent
15177 fails to properly detect absolute file names on those systems, because
15178 they can use a drivespec, and usually use a backslash as directory
15179 separator.  If you want to be portable to DOS variants (at the
15180 price of rejecting valid but oddball Posix file names like @file{a:\b}),
15181 you can check for absolute file names like this:
15183 @cindex absolute file names, detect
15184 @example
15185 case $foo_dir in
15186   [\\/]* | ?:[\\/]* ) # Absolute
15187      ;;
15188   *)
15189      foo_dir=$dots$foo_dir ;;
15190 esac
15191 @end example
15193 @noindent
15194 Make sure you quote the brackets if appropriate and keep the backslash as
15195 first character (@pxref{case, , Limitations of Shell Builtins}).
15197 Also, because the colon is used as part of a drivespec, these systems don't
15198 use it as path separator.  When creating or accessing paths, you can use the
15199 @code{PATH_SEPARATOR} output variable instead.  @command{configure} sets this
15200 to the appropriate value for the build system (@samp{:} or @samp{;}) when it
15201 starts up.
15203 File names need extra care as well.  While DOS variants
15204 that are Posixy enough to run @command{autoconf} (such as DJGPP)
15205 are usually able to handle long file names properly, there are still
15206 limitations that can seriously break packages.  Several of these issues
15207 can be easily detected by the
15208 @uref{ftp://@/ftp.gnu.org/@/gnu/@/non-gnu/@/doschk/@/doschk-1.1.tar.gz, doschk}
15209 package.
15211 A short overview follows; problems are marked with SFN/LFN to
15212 indicate where they apply: SFN means the issues are only relevant to
15213 plain DOS, not to DOS under Microsoft Windows
15214 variants, while LFN identifies problems that exist even under
15215 Microsoft Windows variants.
15217 @table @asis
15218 @item No multiple dots (SFN)
15219 DOS cannot handle multiple dots in file names.  This is an especially
15220 important thing to remember when building a portable configure script,
15221 as @command{autoconf} uses a .in suffix for template files.
15223 This is perfectly OK on Posix variants:
15225 @example
15226 AC_CONFIG_HEADERS([config.h])
15227 AC_CONFIG_FILES([source.c foo.bar])
15228 AC_OUTPUT
15229 @end example
15231 @noindent
15232 but it causes problems on DOS, as it requires @samp{config.h.in},
15233 @samp{source.c.in} and @samp{foo.bar.in}.  To make your package more portable
15234 to DOS-based environments, you should use this instead:
15236 @example
15237 AC_CONFIG_HEADERS([config.h:config.hin])
15238 AC_CONFIG_FILES([source.c:source.cin foo.bar:foobar.in])
15239 AC_OUTPUT
15240 @end example
15242 @item No leading dot (SFN)
15243 DOS cannot handle file names that start with a dot.  This is usually
15244 not important for @command{autoconf}.
15246 @item Case insensitivity (LFN)
15247 DOS is case insensitive, so you cannot, for example, have both a
15248 file called @samp{INSTALL} and a directory called @samp{install}.  This
15249 also affects @command{make}; if there's a file called @samp{INSTALL} in
15250 the directory, @samp{make install} does nothing (unless the
15251 @samp{install} target is marked as PHONY).
15253 @item The 8+3 limit (SFN)
15254 Because the DOS file system only stores the first 8 characters of
15255 the file name and the first 3 of the extension, those must be unique.
15256 That means that @file{foobar-part1.c}, @file{foobar-part2.c} and
15257 @file{foobar-prettybird.c} all resolve to the same file name
15258 (@file{FOOBAR-P.C}).  The same goes for @file{foo.bar} and
15259 @file{foo.bartender}.
15261 The 8+3 limit is not usually a problem under Microsoft Windows, as it
15262 uses numeric
15263 tails in the short version of file names to make them unique.  However, a
15264 registry setting can turn this behavior off.  While this makes it
15265 possible to share file trees containing long file names between SFN
15266 and LFN environments, it also means the above problem applies there
15267 as well.
15269 @item Invalid characters (LFN)
15270 Some characters are invalid in DOS file names, and should therefore
15271 be avoided.  In a LFN environment, these are @samp{/}, @samp{\},
15272 @samp{?}, @samp{*}, @samp{:}, @samp{<}, @samp{>}, @samp{|} and @samp{"}.
15273 In a SFN environment, other characters are also invalid.  These
15274 include @samp{+}, @samp{,}, @samp{[} and @samp{]}.
15276 @item Invalid names (LFN)
15277 Some DOS file names are reserved, and cause problems if you
15278 try to use files with those names.  These names include @file{CON},
15279 @file{AUX}, @file{COM1}, @file{COM2}, @file{COM3}, @file{COM4},
15280 @file{LPT1}, @file{LPT2}, @file{LPT3}, @file{NUL}, and @file{PRN}.
15281 File names are case insensitive, so even names like
15282 @file{aux/config.guess} are disallowed.
15284 @end table
15286 @node Shell Pattern Matching
15287 @section Shell Pattern Matching
15288 @cindex Shell pattern matching
15290 Nowadays portable patterns can use negated character classes like
15291 @samp{[!-aeiou]}.  The older syntax @samp{[^-aeiou]} is supported by
15292 some shells but not others; hence portable scripts should never use
15293 @samp{^} as the first character of a bracket pattern.
15295 Outside the C locale, patterns like @samp{[a-z]} are problematic since
15296 they may match characters that are not lower-case letters.
15298 @node Shell Substitutions
15299 @section Shell Substitutions
15300 @cindex Shell substitutions
15302 Contrary to a persistent urban legend, the Bourne shell does not
15303 systematically split variables and back-quoted expressions, in particular
15304 on the right-hand side of assignments and in the argument of @code{case}.
15305 For instance, the following code:
15307 @example
15308 case "$given_srcdir" in
15309 .)  top_srcdir="`echo "$dots" | sed 's|/$||'`" ;;
15310 *)  top_srcdir="$dots$given_srcdir" ;;
15311 esac
15312 @end example
15314 @noindent
15315 is more readable when written as:
15317 @example
15318 case $given_srcdir in
15319 .)  top_srcdir=`echo "$dots" | sed 's|/$||'` ;;
15320 *)  top_srcdir=$dots$given_srcdir ;;
15321 esac
15322 @end example
15324 @noindent
15325 and in fact it is even @emph{more} portable: in the first case of the
15326 first attempt, the computation of @code{top_srcdir} is not portable,
15327 since not all shells properly understand @code{"`@dots{}"@dots{}"@dots{}`"},
15328 for example Solaris 10 ksh:
15330 @example
15331 $ @kbd{foo="`echo " bar" | sed 's, ,,'`"}
15332 ksh: : cannot execute
15333 ksh: bar | sed 's, ,,': cannot execute
15334 @end example
15336 @noindent
15337 Posix does not specify behavior for this sequence.  On the other hand,
15338 behavior for @code{"`@dots{}\"@dots{}\"@dots{}`"} is specified by Posix,
15339 but in practice, not all shells understand it the same way: pdksh 5.2.14
15340 prints spurious quotes when in Posix mode:
15342 @example
15343 $ @kbd{echo "`echo \"hello\"`"}
15344 hello
15345 $ @kbd{set -o posix}
15346 $ @kbd{echo "`echo \"hello\"`"}
15347 "hello"
15348 @end example
15350 @noindent
15351 There is just no portable way to use double-quoted strings inside
15352 double-quoted back-quoted expressions (pfew!).
15354 Bash 4.1 has a bug where quoted empty strings adjacent to unquoted
15355 parameter expansions are elided during word splitting.  Meanwhile, zsh
15356 does not perform word splitting except when in Bourne compatibility
15357 mode.  In the example below, the correct behavior is to have five
15358 arguments to the function, and exactly two spaces on either side of the
15359 middle @samp{-}, since word splitting collapses multiple spaces in
15360 @samp{$f} but leaves empty arguments intact.
15362 @example
15363 $ @kbd{bash -c 'n() @{ echo "$#$@@"; @}; f="  -  "; n - ""$f"" -'}
15364 3- - -
15365 $ @kbd{ksh -c 'n() @{ echo "$#$@@"; @}; f="  -  "; n - ""$f"" -'}
15366 5-  -  -
15367 $ @kbd{zsh -c 'n() @{ echo "$#$@@"; @}; f="  -  "; n - ""$f"" -'}
15368 3-   -   -
15369 $ @kbd{zsh -c 'emulate sh;}
15370 > @kbd{n() @{ echo "$#$@@"; @}; f="  -  "; n - ""$f"" -'}
15371 5-  -  -
15372 @end example
15374 @noindent
15375 You can work around this by doing manual word splitting, such as using
15376 @samp{"$str" $list} rather than @samp{"$str"$list}.
15378 There are also portability pitfalls with particular expansions:
15380 @table @code
15381 @item $@@
15382 @cindex @samp{"$@@"}
15383 One of the most famous shell-portability issues is related to
15384 @samp{"$@@"}.  When there are no positional arguments, Posix says
15385 that @samp{"$@@"} is supposed to be equivalent to nothing, but the
15386 original Unix version 7 Bourne shell treated it as equivalent to
15387 @samp{""} instead, and this behavior survives in later implementations
15388 like Digital Unix 5.0.
15390 The traditional way to work around this portability problem is to use
15391 @samp{$@{1+"$@@"@}}.  Unfortunately this method does not work with
15392 Zsh (3.x and 4.x), which is used on Mac OS X@.  When emulating
15393 the Bourne shell, Zsh performs word splitting on @samp{$@{1+"$@@"@}}:
15395 @example
15396 zsh $ @kbd{emulate sh}
15397 zsh $ @kbd{for i in "$@@"; do echo $i; done}
15398 Hello World
15400 zsh $ @kbd{for i in $@{1+"$@@"@}; do echo $i; done}
15401 Hello
15402 World
15404 @end example
15406 @noindent
15407 Zsh handles plain @samp{"$@@"} properly, but we can't use plain
15408 @samp{"$@@"} because of the portability problems mentioned above.
15409 One workaround relies on Zsh's ``global aliases'' to convert
15410 @samp{$@{1+"$@@"@}} into @samp{"$@@"} by itself:
15412 @example
15413 test "$@{ZSH_VERSION+set@}" = set && alias -g '$@{1+"$@@"@}'='"$@@"'
15414 @end example
15416 Zsh only recognizes this alias when a shell word matches it exactly;
15417 @samp{"foo"$@{1+"$@@"@}} remains subject to word splitting.  Since this
15418 case always yields at least one shell word, use plain @samp{"$@@"}.
15420 A more conservative workaround is to avoid @samp{"$@@"} if it is
15421 possible that there may be no positional arguments.  For example,
15422 instead of:
15424 @example
15425 cat conftest.c "$@@"
15426 @end example
15428 you can use this instead:
15430 @example
15431 case $# in
15432 0) cat conftest.c;;
15433 *) cat conftest.c "$@@";;
15434 esac
15435 @end example
15437 Autoconf macros often use the @command{set} command to update
15438 @samp{$@@}, so if you are writing shell code intended for
15439 @command{configure} you should not assume that the value of @samp{$@@}
15440 persists for any length of time.
15443 @item $@{10@}
15444 @cindex positional parameters
15445 The 10th, 11th, @dots{} positional parameters can be accessed only after
15446 a @code{shift}.  The 7th Edition shell reported an error if given
15447 @code{$@{10@}}, and
15448 Solaris 10 @command{/bin/sh} still acts that way:
15450 @example
15451 $ @kbd{set 1 2 3 4 5 6 7 8 9 10}
15452 $ @kbd{echo $@{10@}}
15453 bad substitution
15454 @end example
15456 @item $@{@var{var}:-@var{value}@}
15457 @c Info cannot handle `:' in index entries.
15458 @ifnotinfo
15459 @cindex $@{@var{var}:-@var{value}@}
15460 @end ifnotinfo
15461 @cindex $@{@var{var}-@var{value}@}
15462 Old BSD shells, including the Ultrix @code{sh}, don't accept the
15463 colon for any shell substitution, and complain and die.
15464 Similarly for $@{@var{var}:=@var{value}@}, $@{@var{var}:?@var{value}@}, etc.
15465 However, all shells that support functions allow the use of colon in
15466 shell substitution, and since m4sh requires functions, you can portably
15467 use null variable substitution patterns in configure scripts.
15469 @item $@{@var{var}+@var{value}@}
15470 @cindex $@{@var{var}+@var{value}@}
15471 When using @samp{$@{@var{var}-@var{value}@}} or
15472 @samp{$@{@var{var}-@var{value}@}} for providing alternate substitutions,
15473 @var{value} must either be a single shell word, quoted, or in the
15474 context of an unquoted here-document.  Solaris
15475 @command{/bin/sh} complains otherwise.
15477 @example
15478 $ @kbd{/bin/sh -c 'echo $@{a-b c@}'}
15479 /bin/sh: bad substitution
15480 $ @kbd{/bin/sh -c 'echo $@{a-'\''b c'\''@}'}
15481 b c
15482 $ @kbd{/bin/sh -c 'echo "$@{a-b c@}"'}
15483 b c
15484 $ @kbd{/bin/sh -c 'cat <<EOF
15485 $@{a-b c@}
15486 EOF}
15487 b c
15488 @end example
15490 According to Posix, if an expansion occurs inside double quotes, then
15491 the use of unquoted double quotes within @var{value} is unspecified, and
15492 any single quotes become literal characters; in that case, escaping must
15493 be done with backslash.  Likewise, the use of unquoted here-documents is
15494 a case where double quotes have unspecified results:
15496 @example
15497 $ @kbd{/bin/sh -c 'echo "$@{a-"b  c"@}"'}
15498 /bin/sh: bad substitution
15499 $ @kbd{ksh -c 'echo "$@{a-"b  c"@}"'}
15500 b c
15501 $ @kbd{bash -c 'echo "$@{a-"b  c"@}"'}
15502 b  c
15503 $ @kbd{/bin/sh -c 'a=; echo $@{a+'\''b  c'\''@}'}
15504 b  c
15505 $ @kbd{/bin/sh -c 'a=; echo "$@{a+'\''b  c'\''@}"'}
15506 'b  c'
15507 $ @kbd{/bin/sh -c 'a=; echo "$@{a+\"b  c\"@}"'}
15508 "b  c"
15509 $ @kbd{/bin/sh -c 'a=; echo "$@{a+b  c@}"'}
15510 b  c
15511 $ @kbd{/bin/sh -c 'cat <<EOF
15512 $@{a-"b  c"@}
15513 EOF'}
15514 "b  c"
15515 $ @kbd{/bin/sh -c 'cat <<EOF
15516 $@{a-'b  c'@}
15517 EOF'}
15518 'b  c'
15519 $ @kbd{bash -c 'cat <<EOF
15520 $@{a-"b  c"@}
15521 EOF'}
15522 b  c
15523 $ @kbd{bash -c 'cat <<EOF
15524 $@{a-'b  c'@}
15525 EOF'}
15526 'b  c'
15527 @end example
15529 Perhaps the easiest way to work around quoting issues in a manner
15530 portable to all shells is to place the results in a temporary variable,
15531 then use @samp{$t} as the @var{value}, rather than trying to inline
15532 the expression needing quoting.
15534 @example
15535 $ @kbd{/bin/sh -c 't="a  b\"'\''@}\\"; echo "$@{a-$t@}"'}
15536 b  c"'@}\
15537 $ @kbd{ksh -c 't="a  b\"'\''@}\\"; echo "$@{a-$t@}"'}
15538 b  c"'@}\
15539 $ @kbd{bash -c 't="a  b\"'\''@}\\"; echo "$@{a-$t@}"'}
15540 b  c"'@}\
15541 @end example
15543 @item $@{@var{var}=@var{value}@}
15544 @cindex $@{@var{var}=@var{value}@}
15545 When using @samp{$@{@var{var}=@var{value}@}} to assign a default value
15546 to @var{var}, remember that even though the assignment to @var{var} does
15547 not undergo file name expansion, the result of the variable expansion
15548 does unless the expansion occurred within double quotes.  In particular,
15549 when using @command{:} followed by unquoted variable expansion for the
15550 side effect of setting a default value, if the final value of
15551 @samp{$var} contains any globbing characters (either from @var{value} or
15552 from prior contents), the shell has to spend time performing file name
15553 expansion and field splitting even though those results will not be
15554 used.  Therefore, it is a good idea to consider double quotes when performing
15555 default initialization; while remembering how this impacts any quoting
15556 characters appearing in @var{value}.
15558 @example
15559 $ @kbd{time bash -c ': "$@{a=/usr/bin/*@}"; echo "$a"'}
15560 /usr/bin/*
15562 real    0m0.005s
15563 user    0m0.002s
15564 sys     0m0.003s
15565 $ @kbd{time bash -c ': $@{a=/usr/bin/*@}; echo "$a"'}
15566 /usr/bin/*
15568 real    0m0.039s
15569 user    0m0.026s
15570 sys     0m0.009s
15571 $ @kbd{time bash -c 'a=/usr/bin/*; : $@{a=noglob@}; echo "$a"'}
15572 /usr/bin/*
15574 real    0m0.031s
15575 user    0m0.020s
15576 sys     0m0.010s
15578 $ @kbd{time bash -c 'a=/usr/bin/*; : "$@{a=noglob@}"; echo "$a"'}
15579 /usr/bin/*
15581 real    0m0.006s
15582 user    0m0.002s
15583 sys     0m0.003s
15584 @end example
15586 As with @samp{+} and @samp{-}, you must use quotes when using @samp{=}
15587 if the @var{value} contains more than one shell word; either single
15588 quotes for just the @var{value}, or double quotes around the entire
15589 expansion:
15591 @example
15592 $ @kbd{: $@{var1='Some words'@}}
15593 $ @kbd{: "$@{var2=like this@}"}
15594 $ @kbd{echo $var1 $var2}
15595 Some words like this
15596 @end example
15598 @noindent
15599 otherwise some shells, such as Solaris @command{/bin/sh} or on Digital
15600 Unix V 5.0, die because of a ``bad substitution''.  Meanwhile, Posix
15601 requires that with @samp{=}, quote removal happens prior to the
15602 assignment, and the expansion be the final contents of @var{var} without
15603 quoting (and thus subject to field splitting), in contrast to the
15604 behavior with @samp{-} passing the quoting through to the final
15605 expansion.  However, @command{bash} 4.1 does not obey this rule.
15607 @example
15608 $ @kbd{ksh -c 'echo $@{var-a\ \ b@}'}
15609 a  b
15610 $ @kbd{ksh -c 'echo $@{var=a\ \ b@}'}
15611 a b
15612 $ @kbd{bash -c 'echo $@{var=a\ \ b@}'}
15613 a  b
15614 @end example
15616 Finally, Posix states that when mixing @samp{$@{a=b@}} with regular
15617 commands, it is unspecified whether the assignments affect the parent
15618 shell environment.  It is best to perform assignments independently from
15619 commands, to avoid the problems demonstrated in this example:
15621 @example
15622 $ @kbd{bash -c 'x= y=$@{x:=b@} sh -c "echo +\$x+\$y+";echo -$x-'}
15623 +b+b+
15625 $ @kbd{/bin/sh -c 'x= y=$@{x:=b@} sh -c "echo +\$x+\$y+";echo -$x-'}
15626 ++b+
15628 $ @kbd{ksh -c 'x= y=$@{x:=b@} sh -c "echo +\$x+\$y+";echo -$x-'}
15629 +b+b+
15631 @end example
15633 @item $@{@var{var}=@var{value}@}
15634 @cindex $@{@var{var}=@var{literal}@}
15635 Solaris @command{/bin/sh} has a frightening bug in its handling of
15636 literal assignments.  Imagine you need set a variable to a string containing
15637 @samp{@}}.  This @samp{@}} character confuses Solaris @command{/bin/sh}
15638 when the affected variable was already set.  This bug can be exercised
15639 by running:
15641 @example
15642 $ @kbd{unset foo}
15643 $ @kbd{foo=$@{foo='@}'@}}
15644 $ @kbd{echo $foo}
15646 $ @kbd{foo=$@{foo='@}'   # no error; this hints to what the bug is}
15647 $ @kbd{echo $foo}
15649 $ @kbd{foo=$@{foo='@}'@}}
15650 $ @kbd{echo $foo}
15651 @}@}
15652  ^ ugh!
15653 @end example
15655 It seems that @samp{@}} is interpreted as matching @samp{$@{}, even
15656 though it is enclosed in single quotes.  The problem doesn't happen
15657 using double quotes, or when using a temporary variable holding the
15658 problematic string.
15660 @item $@{@var{var}=@var{expanded-value}@}
15661 @cindex $@{@var{var}=@var{expanded-value}@}
15662 On Ultrix,
15663 running
15665 @example
15666 default="yu,yaa"
15667 : $@{var="$default"@}
15668 @end example
15670 @noindent
15671 sets @var{var} to @samp{M-yM-uM-,M-yM-aM-a}, i.e., the 8th bit of
15672 each char is set.  You don't observe the phenomenon using a simple
15673 @samp{echo $var} since apparently the shell resets the 8th bit when it
15674 expands $var.  Here are two means to make this shell confess its sins:
15676 @example
15677 $ @kbd{cat -v <<EOF
15678 $var
15679 EOF}
15680 @end example
15682 @noindent
15685 @example
15686 $ @kbd{set | grep '^var=' | cat -v}
15687 @end example
15689 One classic incarnation of this bug is:
15691 @example
15692 default="a b c"
15693 : $@{list="$default"@}
15694 for c in $list; do
15695   echo $c
15696 done
15697 @end example
15699 @noindent
15700 You'll get @samp{a b c} on a single line.  Why?  Because there are no
15701 spaces in @samp{$list}: there are @samp{M- }, i.e., spaces with the 8th
15702 bit set, hence no IFS splitting is performed!!!
15704 One piece of good news is that Ultrix works fine with @samp{:
15705 $@{list=$default@}}; i.e., if you @emph{don't} quote.  The bad news is
15706 then that QNX 4.25 then sets @var{list} to the @emph{last} item of
15707 @var{default}!
15709 The portable way out consists in using a double assignment, to switch
15710 the 8th bit twice on Ultrix:
15712 @example
15713 list=$@{list="$default"@}
15714 @end example
15716 @noindent
15717 @dots{}but beware of the @samp{@}} bug from Solaris (see above).  For safety,
15718 use:
15720 @example
15721 test "$@{var+set@}" = set || var=@var{@{value@}}
15722 @end example
15724 @item $@{#@var{var}@}
15725 @itemx $@{@var{var}%@var{word}@}
15726 @itemx $@{@var{var}%%@var{word}@}
15727 @itemx $@{@var{var}#@var{word}@}
15728 @itemx $@{@var{var}##@var{word}@}
15729 @cindex $@{#@var{var}@}
15730 @cindex $@{@var{var}%@var{word}@}
15731 @cindex $@{@var{var}%%@var{word}@}
15732 @cindex $@{@var{var}#@var{word}@}
15733 @cindex $@{@var{var}##@var{word}@}
15734 Posix requires support for these usages, but they do not work with many
15735 traditional shells, e.g., Solaris 10 @command{/bin/sh}.
15737 Also, @command{pdksh} 5.2.14 mishandles some @var{word} forms.  For
15738 example if @samp{$1} is @samp{a/b} and @samp{$2} is @samp{a}, then
15739 @samp{$@{1#$2@}} should yield @samp{/b}, but with @command{pdksh} it
15740 yields the empty string.
15743 @item `@var{commands}`
15744 @cindex `@var{commands}`
15745 @cindex Command Substitution
15746 Posix requires shells to trim all trailing newlines from command
15747 output before substituting it, so assignments like
15748 @samp{dir=`echo "$file" | tr a A`} do not work as expected if
15749 @samp{$file} ends in a newline.
15751 While in general it makes no sense, do not substitute a single builtin
15752 with side effects, because Ash 0.2, trying to optimize, does not fork a
15753 subshell to perform the command.
15755 For instance, if you wanted to check that @command{cd} is silent, do not
15756 use @samp{test -z "`cd /`"} because the following can happen:
15758 @example
15759 $ @kbd{pwd}
15760 /tmp
15761 $ @kbd{test -z "`cd /`" && pwd}
15763 @end example
15765 @noindent
15766 The result of @samp{foo=`exit 1`} is left as an exercise to the reader.
15768 The MSYS shell leaves a stray byte in the expansion of a double-quoted
15769 command substitution of a native program, if the end of the substitution
15770 is not aligned with the end of the double quote.  This may be worked
15771 around by inserting another pair of quotes:
15773 @example
15774 $ @kbd{echo "`printf 'foo\r\n'` bar" > broken}
15775 $ @kbd{echo "`printf 'foo\r\n'`"" bar" | cmp - broken}
15776 - broken differ: char 4, line 1
15777 @end example
15779 Upon interrupt or SIGTERM, some shells may abort a command substitution,
15780 replace it with a null string, and wrongly evaluate the enclosing
15781 command before entering the trap or ending the script.  This can lead to
15782 spurious errors:
15784 @example
15785 $ @kbd{sh -c 'if test `sleep 5; echo hi` = hi; then echo yes; fi'}
15786 $ @kbd{^C}
15787 sh: test: hi: unexpected operator/operand
15788 @end example
15790 @noindent
15791 You can avoid this by assigning the command substitution to a temporary
15792 variable:
15794 @example
15795 $ @kbd{sh -c 'res=`sleep 5; echo hi`
15796          if test "x$res" = xhi; then echo yes; fi'}
15797 $ @kbd{^C}
15798 @end example
15800 @item $(@var{commands})
15801 @cindex $(@var{commands})
15802 This construct is meant to replace @samp{`@var{commands}`},
15803 and it has most of the problems listed under @code{`@var{commands}`}.
15805 This construct can be
15806 nested while this is impossible to do portably with back quotes.
15807 Unfortunately it is not yet universally supported.  Most notably, even recent
15808 releases of Solaris don't support it:
15810 @example
15811 $ @kbd{showrev -c /bin/sh | grep version}
15812 Command version: SunOS 5.10 Generic 121005-03 Oct 2006
15813 $ @kbd{echo $(echo blah)}
15814 syntax error: `(' unexpected
15815 @end example
15817 @noindent
15818 nor does IRIX 6.5's Bourne shell:
15819 @example
15820 $ @kbd{uname -a}
15821 IRIX firebird-image 6.5 07151432 IP22
15822 $ @kbd{echo $(echo blah)}
15823 $(echo blah)
15824 @end example
15826 If you do use @samp{$(@var{commands})}, make sure that the commands
15827 do not start with a parenthesis, as that would cause confusion with
15828 a different notation @samp{$((@var{expression}))} that in modern
15829 shells is an arithmetic expression not a command.  To avoid the
15830 confusion, insert a space between the two opening parentheses.
15832 Avoid @var{commands} that contain unbalanced parentheses in
15833 here-documents, comments, or case statement patterns, as many shells
15834 mishandle them.  For example, Bash 3.1, @samp{ksh88}, @command{pdksh}
15835 5.2.14, and Zsh 4.2.6 all mishandle the following valid command:
15837 @example
15838 echo $(case x in x) echo hello;; esac)
15839 @end example
15842 @item $((@var{expression}))
15843 @cindex $((@var{expression}))
15844 Arithmetic expansion is not portable as some shells (most
15845 notably Solaris 10 @command{/bin/sh}) don't support it.
15847 Among shells that do support @samp{$(( ))}, not all of them obey the
15848 Posix rule that octal and hexadecimal constants must be recognized:
15850 @example
15851 $ @kbd{bash -c 'echo $(( 010 + 0x10 ))'}
15853 $ @kbd{zsh -c 'echo $(( 010 + 0x10 ))'}
15855 $ @kbd{zsh -c 'emulate sh; echo $(( 010 + 0x10 ))'}
15857 $ @kbd{pdksh -c 'echo $(( 010 + 0x10 ))'}
15858 pdksh:  010 + 0x10 : bad number `0x10'
15859 $ @kbd{pdksh -c 'echo $(( 010 ))'}
15861 @end example
15863 When it is available, using arithmetic expansion provides a noticeable
15864 speedup in script execution; but testing for support requires
15865 @command{eval} to avoid syntax errors.  The following construct is used
15866 by @code{AS_VAR_ARITH} to provide arithmetic computation when all
15867 arguments are provided in decimal and without a leading zero, and all
15868 operators are properly quoted and appear as distinct arguments:
15870 @example
15871 if ( eval 'test $(( 1 + 1 )) = 2' ) 2>/dev/null; then
15872   eval 'func_arith ()
15873   @{
15874     func_arith_result=$(( $* ))
15875   @}'
15876 else
15877   func_arith ()
15878   @{
15879     func_arith_result=`expr "$@@"`
15880   @}
15882 func_arith 1 + 1
15883 foo=$func_arith_result
15884 @end example
15887 @item ^
15888 @cindex ^ quoting
15889 Always quote @samp{^}, otherwise traditional shells such as
15890 @command{/bin/sh} on Solaris 10 treat this like @samp{|}.
15892 @end table
15895 @node Assignments
15896 @section Assignments
15897 @cindex Shell assignments
15899 When setting several variables in a row, be aware that the order of the
15900 evaluation is undefined.  For instance @samp{foo=1 foo=2; echo $foo}
15901 gives @samp{1} with Solaris @command{/bin/sh}, but @samp{2} with Bash.
15902 You must use
15903 @samp{;} to enforce the order: @samp{foo=1; foo=2; echo $foo}.
15905 Don't rely on the following to find @file{subdir/program}:
15907 @example
15908 PATH=subdir$PATH_SEPARATOR$PATH program
15909 @end example
15911 @noindent
15912 as this does not work with Zsh 3.0.6.  Use something like this
15913 instead:
15915 @example
15916 (PATH=subdir$PATH_SEPARATOR$PATH; export PATH; exec program)
15917 @end example
15919 Don't rely on the exit status of an assignment: Ash 0.2 does not change
15920 the status and propagates that of the last statement:
15922 @example
15923 $ @kbd{false || foo=bar; echo $?}
15925 $ @kbd{false || foo=`:`; echo $?}
15927 @end example
15929 @noindent
15930 and to make things even worse, QNX 4.25 just sets the exit status
15931 to 0 in any case:
15933 @example
15934 $ @kbd{foo=`exit 1`; echo $?}
15936 @end example
15938 To assign default values, follow this algorithm:
15940 @enumerate
15941 @item
15942 If the default value is a literal and does not contain any closing
15943 brace, use:
15945 @example
15946 : "$@{var='my literal'@}"
15947 @end example
15949 @item
15950 If the default value contains no closing brace, has to be expanded, and
15951 the variable being initialized is not intended to be IFS-split
15952 (i.e., it's not a list), then use:
15954 @example
15955 : $@{var="$default"@}
15956 @end example
15958 @item
15959 If the default value contains no closing brace, has to be expanded, and
15960 the variable being initialized is intended to be IFS-split (i.e., it's a list),
15961 then use:
15963 @example
15964 var=$@{var="$default"@}
15965 @end example
15967 @item
15968 If the default value contains a closing brace, then use:
15970 @example
15971 test "$@{var+set@}" = set || var="has a '@}'"
15972 @end example
15973 @end enumerate
15975 In most cases @samp{var=$@{var="$default"@}} is fine, but in case of
15976 doubt, just use the last form.  @xref{Shell Substitutions}, items
15977 @samp{$@{@var{var}:-@var{value}@}} and @samp{$@{@var{var}=@var{value}@}}
15978 for the rationale.
15980 @node Parentheses
15981 @section Parentheses in Shell Scripts
15982 @cindex Shell parentheses
15984 Beware of two opening parentheses in a row, as many shell
15985 implementations treat them specially.  Posix requires that the command
15986 @samp{((cat))} must behave like @samp{(cat)}, but many shells, including
15987 Bash and the Korn shell, treat @samp{((cat))} as an arithmetic
15988 expression equivalent to @samp{let "cat"}, and may or may not report an
15989 error when they detect that @samp{cat} is not a number.  As another
15990 example, @samp{pdksh} 5.2.14 misparses the following code:
15992 @example
15993 if ((true) || false); then
15994   echo ok
15996 @end example
15998 @noindent
15999 To work around this problem, insert a space between the two opening
16000 parentheses.  There is a similar problem and workaround with
16001 @samp{$((}; see @ref{Shell Substitutions}.
16003 @node Slashes
16004 @section Slashes in Shell Scripts
16005 @cindex Shell slashes
16007 Unpatched Tru64 5.1 @command{sh} omits the last slash of command-line
16008 arguments that contain two trailing slashes:
16010 @example
16011 $ @kbd{echo / // /// //// .// //.}
16012 / / // /// ./ //.
16013 $ @kbd{x=//}
16014 $ @kbd{eval "echo \$x"}
16016 $ @kbd{set -x}
16017 $ @kbd{echo abc | tr -t ab //}
16018 + echo abc
16019 + tr -t ab /
16021 @end example
16023 Unpatched Tru64 4.0 @command{sh} adds a slash after @samp{"$var"} if the
16024 variable is empty and the second double-quote is followed by a word that
16025 begins and ends with slash:
16027 @example
16028 $ @kbd{sh -xc 'p=; echo "$p"/ouch/'}
16030 + echo //ouch/
16031 //ouch/
16032 @end example
16034 However, our understanding is that patches are available, so perhaps
16035 it's not worth worrying about working around these horrendous bugs.
16037 @node Special Shell Variables
16038 @section Special Shell Variables
16039 @cindex Shell variables
16040 @cindex Special shell variables
16042 Some shell variables should not be used, since they can have a deep
16043 influence on the behavior of the shell.  In order to recover a sane
16044 behavior from the shell, some variables should be unset; M4sh takes
16045 care of this and provides fallback values, whenever needed, to cater
16046 for a very old @file{/bin/sh} that does not support @command{unset}.
16047 (@pxref{Portable Shell, , Portable Shell Programming}).
16049 As a general rule, shell variable names containing a lower-case letter
16050 are safe; you can define and use these variables without worrying about
16051 their effect on the underlying system, and without worrying about
16052 whether the shell changes them unexpectedly.  (The exception is the
16053 shell variable @code{status}, as described below.)
16055 Here is a list of names that are known to cause trouble.  This list is
16056 not exhaustive, but you should be safe if you avoid the name
16057 @code{status} and names containing only upper-case letters and
16058 underscores.
16060 @c Alphabetical order, case insensitive, `A' before `a'.
16061 @table @code
16062 @item ?
16063 Not all shells correctly reset @samp{$?} after conditionals (@pxref{if,
16064 , Limitations of Shell Builtins}).  Not all shells manage @samp{$?}
16065 correctly in shell functions (@pxref{Shell Functions}) or in traps
16066 (@pxref{trap, , Limitations of Shell Builtins}).  Not all shells reset
16067 @samp{$?} to zero after an empty command.
16069 @example
16070 $ @kbd{bash -c 'false; $empty; echo $?'}
16072 $ @kbd{zsh -c 'false; $empty; echo $?'}
16074 @end example
16076 @item _
16077 @evindex _
16078 Many shells reserve @samp{$_} for various purposes, e.g., the name of
16079 the last command executed.
16081 @item BIN_SH
16082 @evindex BIN_SH
16083 In Tru64, if @env{BIN_SH} is set to @code{xpg4}, subsidiary invocations of
16084 the standard shell conform to Posix.
16086 @item CDPATH
16087 @evindex CDPATH
16088 When this variable is set it specifies a list of directories to search
16089 when invoking @code{cd} with a relative file name that did not start
16090 with @samp{./} or @samp{../}.  Posix
16091 1003.1-2001 says that if a nonempty directory name from @env{CDPATH}
16092 is used successfully, @code{cd} prints the resulting absolute
16093 file name.  Unfortunately this output can break idioms like
16094 @samp{abs=`cd src && pwd`} because @code{abs} receives the name twice.
16095 Also, many shells do not conform to this part of Posix; for
16096 example, @command{zsh} prints the result only if a directory name
16097 other than @file{.} was chosen from @env{CDPATH}.
16099 In practice the shells that have this problem also support
16100 @command{unset}, so you can work around the problem as follows:
16102 @example
16103 (unset CDPATH) >/dev/null 2>&1 && unset CDPATH
16104 @end example
16106 You can also avoid output by ensuring that your directory name is
16107 absolute or anchored at @samp{./}, as in @samp{abs=`cd ./src && pwd`}.
16109 Configure scripts use M4sh, which automatically unsets @env{CDPATH} if
16110 possible, so you need not worry about this problem in those scripts.
16112 @item CLICOLOR_FORCE
16113 @evindex CLICOLOR_FORCE
16114 When this variable is set, some implementations of tools like
16115 @command{ls} attempt to add color to their output via terminal escape
16116 sequences, even when the output is not directed to a terminal, and can
16117 thus cause spurious failures in scripts.  Configure scripts use M4sh,
16118 which automatically unsets this variable.
16120 @item DUALCASE
16121 @evindex DUALCASE
16122 In the MKS shell, case statements and file name generation are
16123 case-insensitive unless @env{DUALCASE} is nonzero.
16124 Autoconf-generated scripts export this variable when they start up.
16126 @item ENV
16127 @itemx MAIL
16128 @itemx MAILPATH
16129 @itemx PS1
16130 @itemx PS2
16131 @itemx PS4
16132 @evindex ENV
16133 @evindex MAIL
16134 @evindex MAILPATH
16135 @evindex PS1
16136 @evindex PS2
16137 @evindex PS4
16138 These variables should not matter for shell scripts, since they are
16139 supposed to affect only interactive shells.  However, at least one
16140 shell (the pre-3.0 UWIN Korn shell) gets confused about
16141 whether it is interactive, which means that (for example) a @env{PS1}
16142 with a side effect can unexpectedly modify @samp{$?}.  To work around
16143 this bug, M4sh scripts (including @file{configure} scripts) do something
16144 like this:
16146 @example
16147 (unset ENV) >/dev/null 2>&1 && unset ENV MAIL MAILPATH
16148 PS1='$ '
16149 PS2='> '
16150 PS4='+ '
16151 @end example
16153 @noindent
16154 (actually, there is some complication due to bugs in @command{unset};
16155 see @pxref{unset, , Limitations of Shell Builtins}).
16157 @item FPATH
16158 @evindex FPATH
16159 The Korn shell uses @env{FPATH} to find shell functions, so avoid
16160 @env{FPATH} in portable scripts.  @env{FPATH} is consulted after
16161 @env{PATH}, but you still need to be wary of tests that use @env{PATH}
16162 to find whether a command exists, since they might report the wrong
16163 result if @env{FPATH} is also set.
16165 @item GREP_OPTIONS
16166 @evindex GREP_OPTIONS
16167 When this variable is set, some implementations of @command{grep} honor
16168 these options, even if the options include direction to enable colored
16169 output via terminal escape sequences, and the result can cause spurious
16170 failures when the output is not directed to a terminal.  Configure
16171 scripts use M4sh, which automatically unsets this variable.
16173 @item IFS
16174 @evindex IFS
16175 Long ago, shell scripts inherited @env{IFS} from the environment,
16176 but this caused many problems so modern shells ignore any environment
16177 settings for @env{IFS}.
16179 Don't set the first character of @env{IFS} to backslash.  Indeed,
16180 Bourne shells use the first character (backslash) when joining the
16181 components in @samp{"$@@"} and some shells then reinterpret (!)@: the
16182 backslash escapes, so you can end up with backspace and other strange
16183 characters.
16185 The proper value for @env{IFS} (in regular code, not when performing
16186 splits) is @samp{@key{SPC}@key{TAB}@key{RET}}.  The first character is
16187 especially important, as it is used to join the arguments in @samp{$*};
16188 however, note that traditional shells, but also bash-2.04, fail to adhere
16189 to this and join with a space anyway.
16191 M4sh guarantees that @env{IFS} will have the default value at the
16192 beginning of a script, and many macros within autoconf rely on this
16193 setting.  It is okay to use blocks of shell code that temporarily change
16194 the value of @env{IFS} in order to split on another character, but
16195 remember to restore it before expanding further macros.
16197 Unsetting @code{IFS} instead of resetting it to the default sequence
16198 is not suggested, since code that tries to save and restore the
16199 variable's value will incorrectly reset it to an empty value, thus
16200 disabling field splitting:
16202 @example
16203 unset IFS
16204 # default separators used for field splitting
16206 save_IFS=$IFS
16207 IFS=:
16208 # ...
16209 IFS=$save_IFS
16210 # no field splitting performed
16211 @end example
16213 @item LANG
16214 @itemx LC_ALL
16215 @itemx LC_COLLATE
16216 @itemx LC_CTYPE
16217 @itemx LC_MESSAGES
16218 @itemx LC_MONETARY
16219 @itemx LC_NUMERIC
16220 @itemx LC_TIME
16221 @evindex LANG
16222 @evindex LC_ALL
16223 @evindex LC_COLLATE
16224 @evindex LC_CTYPE
16225 @evindex LC_MESSAGES
16226 @evindex LC_MONETARY
16227 @evindex LC_NUMERIC
16228 @evindex LC_TIME
16230 You should set all these variables to @samp{C} because so much
16231 configuration code assumes the C locale and Posix requires that locale
16232 environment variables be set to @samp{C} if the C locale is desired;
16233 @file{configure} scripts and M4sh do that for you.
16234 Export these variables after setting them.
16236 @c  However, some older, nonstandard
16237 @c  systems (notably SCO) break if locale environment variables
16238 @c  are set to @samp{C}, so when running on these systems
16239 @c  Autoconf-generated scripts unset the variables instead.
16241 @item LANGUAGE
16242 @evindex LANGUAGE
16244 @env{LANGUAGE} is not specified by Posix, but it is a GNU
16245 extension that overrides @env{LC_ALL} in some cases, so you (or M4sh)
16246 should set it too.
16248 @item LC_ADDRESS
16249 @itemx LC_IDENTIFICATION
16250 @itemx LC_MEASUREMENT
16251 @itemx LC_NAME
16252 @itemx LC_PAPER
16253 @itemx LC_TELEPHONE
16254 @evindex LC_ADDRESS
16255 @evindex LC_IDENTIFICATION
16256 @evindex LC_MEASUREMENT
16257 @evindex LC_NAME
16258 @evindex LC_PAPER
16259 @evindex LC_TELEPHONE
16261 These locale environment variables are GNU extensions.  They
16262 are treated like their Posix brethren (@env{LC_COLLATE},
16263 etc.)@: as described above.
16265 @item LINENO
16266 @evindex LINENO
16267 Most modern shells provide the current line number in @code{LINENO}.
16268 Its value is the line number of the beginning of the current command.
16269 M4sh, and hence Autoconf, attempts to execute @command{configure} with
16270 a shell that supports @code{LINENO}.  If no such shell is available, it
16271 attempts to implement @code{LINENO} with a Sed prepass that replaces each
16272 instance of the string @code{$LINENO} (not followed by an alphanumeric
16273 character) with the line's number.  In M4sh scripts you should execute
16274 @code{AS_LINENO_PREPARE} so that these workarounds are included in
16275 your script; configure scripts do this automatically in @code{AC_INIT}.
16277 You should not rely on @code{LINENO} within @command{eval} or shell
16278 functions, as the behavior differs in practice.  The presence of a
16279 quoted newline within simple commands can alter which line number is
16280 used as the starting point for @code{$LINENO} substitutions within that
16281 command.  Also, the possibility of the Sed prepass means that you should
16282 not rely on @code{$LINENO} when quoted, when in here-documents, or when
16283 line continuations are used.  Subshells should be OK, though.  In the
16284 following example, lines 1, 9, and 14 are portable, but the other
16285 instances of @code{$LINENO} do not have deterministic values:
16287 @example
16288 @group
16289 $ @kbd{cat lineno}
16290 echo 1. $LINENO
16291 echo "2. $LINENO
16292 3. $LINENO"
16293 cat <<EOF
16294 5. $LINENO
16295 6. $LINENO
16296 7. \$LINENO
16298 ( echo 9. $LINENO )
16299 eval 'echo 10. $LINENO'
16300 eval 'echo 11. $LINENO
16301 echo 12. $LINENO'
16302 echo 13. '$LINENO'
16303 echo 14. $LINENO '
16304 15.' $LINENO
16305 f () @{ echo $1 $LINENO;
16306 echo $1 $LINENO @}
16307 f 18.
16308 echo 19. \
16309 $LINENO
16310 @end group
16311 @group
16312 $ @kbd{bash-3.2 ./lineno}
16313 1. 1
16314 2. 3
16315 3. 3
16316 5. 4
16317 6. 4
16318 7. $LINENO
16319 9. 9
16320 10. 10
16321 11. 12
16322 12. 13
16323 13. $LINENO
16324 14. 14
16325 15. 14
16326 18. 16
16327 18. 17
16328 19. 19
16329 @end group
16330 @group
16331 $ @kbd{zsh-4.3.4 ./lineno}
16332 1. 1
16333 2. 2
16334 3. 2
16335 5. 4
16336 6. 4
16337 7. $LINENO
16338 9. 9
16339 10. 1
16340 11. 1
16341 12. 2
16342 13. $LINENO
16343 14. 14
16344 15. 14
16345 18. 0
16346 18. 1
16347 19. 19
16348 @end group
16349 @group
16350 $ @kbd{pdksh-5.2.14 ./lineno}
16351 1. 1
16352 2. 2
16353 3. 2
16354 5. 4
16355 6. 4
16356 7. $LINENO
16357 9. 9
16358 10. 0
16359 11. 0
16360 12. 0
16361 13. $LINENO
16362 14. 14
16363 15. 14
16364 18. 16
16365 18. 17
16366 19. 19
16367 @end group
16368 @group
16369 $ @kbd{sed '=' <lineno |}
16370 > @kbd{  sed '}
16371 > @kbd{    N}
16372 > @kbd{    s,$,-,}
16373 > @kbd{    t loop}
16374 > @kbd{    :loop}
16375 > @kbd{    s,^\([0-9]*\)\(.*\)[$]LINENO\([^a-zA-Z0-9_]\),\1\2\1\3,}
16376 > @kbd{    t loop}
16377 > @kbd{    s,-$,,}
16378 > @kbd{    s,^[0-9]*\n,,}
16379 > @kbd{  ' |}
16380 > @kbd{  sh}
16381 1. 1
16382 2. 2
16383 3. 3
16384 5. 5
16385 6. 6
16386 7. \7
16387 9. 9
16388 10. 10
16389 11. 11
16390 12. 12
16391 13. 13
16392 14. 14
16393 15. 15
16394 18. 16
16395 18. 17
16396 19. 20
16397 @end group
16398 @end example
16400 In particular, note that @file{config.status} (and any other subsidiary
16401 script created by @code{AS_INIT_GENERATED}) might report line numbers
16402 relative to the parent script as a result of the potential Sed pass.
16404 @item NULLCMD
16405 @evindex NULLCMD
16406 When executing the command @samp{>foo}, @command{zsh} executes
16407 @samp{$NULLCMD >foo} unless it is operating in Bourne shell
16408 compatibility mode and the @command{zsh} version is newer
16409 than 3.1.6-dev-18.  If you are using an older @command{zsh}
16410 and forget to set @env{NULLCMD},
16411 your script might be suspended waiting for data on its standard input.
16413 @item PATH_SEPARATOR
16414 @evindex PATH_SEPARATOR
16415 On DJGPP systems, the @env{PATH_SEPARATOR} environment
16416 variable can be set to either @samp{:} or @samp{;} to control the path
16417 separator Bash uses to set up certain environment variables (such as
16418 @env{PATH}).  You can set this variable to @samp{;} if you want
16419 @command{configure} to use @samp{;} as a separator; this might be useful
16420 if you plan to use non-Posix shells to execute files.  @xref{File System
16421 Conventions}, for more information about @code{PATH_SEPARATOR}.
16423 @item POSIXLY_CORRECT
16424 @evindex POSIXLY_CORRECT
16425 In the GNU environment, exporting @env{POSIXLY_CORRECT} with any value
16426 (even empty) causes programs to try harder to conform to Posix.
16427 Autoconf does not directly manipulate this variable, but @command{bash}
16428 ties the shell variable @env{POSIXLY_CORRECT} to whether the script is
16429 running in Posix mode.  Therefore, take care when exporting or unsetting
16430 this variable, so as not to change whether @command{bash} is in Posix
16431 mode.
16433 @example
16434 $ @kbd{bash --posix -c 'set -o | grep posix}
16435 > @kbd{unset POSIXLY_CORRECT}
16436 > @kbd{set -o | grep posix'}
16437 posix           on
16438 posix           off
16439 @end example
16441 @item PWD
16442 @evindex PWD
16443 Posix 1003.1-2001 requires that @command{cd} and
16444 @command{pwd} must update the @env{PWD} environment variable to point
16445 to the logical name of the current directory, but traditional shells
16446 do not support this.  This can cause confusion if one shell instance
16447 maintains @env{PWD} but a subsidiary and different shell does not know
16448 about @env{PWD} and executes @command{cd}; in this case @env{PWD}
16449 points to the wrong directory.  Use @samp{`pwd`} rather than
16450 @samp{$PWD}.
16452 @item RANDOM
16453 @evindex RANDOM
16454 Many shells provide @code{RANDOM}, a variable that returns a different
16455 integer each time it is used.  Most of the time, its value does not
16456 change when it is not used, but on IRIX 6.5 the value changes all
16457 the time.  This can be observed by using @command{set}.  It is common
16458 practice to use @code{$RANDOM} as part of a file name, but code
16459 shouldn't rely on @code{$RANDOM} expanding to a nonempty string.
16461 @item status
16462 @evindex status
16463 This variable is an alias to @samp{$?} for @code{zsh} (at least 3.1.6),
16464 hence read-only.  Do not use it.
16465 @end table
16467 @node Shell Functions
16468 @section Shell Functions
16469 @cindex Shell Functions
16471 Nowadays, it is difficult to find a shell that does not support
16472 shell functions at all.  However, some differences should be expected.
16474 When declaring a shell function, you must include whitespace between the
16475 @samp{)} after the function name and the start of the compound
16476 expression, to avoid upsetting @command{ksh}.  While it is possible to
16477 use any compound command, most scripts use @samp{@{@dots{}@}}.
16479 @example
16480 $ @kbd{/bin/sh -c 'a()@{ echo hi;@}; a'}
16482 $ @kbd{ksh -c 'a()@{ echo hi;@}; a'}
16483 ksh: syntax error at line 1: `@}' unexpected
16484 $ @kbd{ksh -c 'a() @{ echo hi;@}; a'}
16486 @end example
16488 Inside a shell function, you should not rely on the error status of a
16489 subshell if the last command of that subshell was @code{exit} or
16490 @code{trap}, as this triggers bugs in zsh 4.x; while Autoconf tries to
16491 find a shell that does not exhibit the bug, zsh might be the only shell
16492 present on the user's machine.
16494 Likewise, the state of @samp{$?} is not reliable when entering a shell
16495 function.  This has the effect that using a function as the first
16496 command in a @command{trap} handler can cause problems.
16498 @example
16499 $ @kbd{bash -c 'foo() @{ echo $?; @}; trap foo 0; (exit 2); exit 2'; echo $?}
16502 $ @kbd{ash -c 'foo() @{ echo $?; @}; trap foo 0; (exit 2); exit 2'; echo $?}
16505 @end example
16507 DJGPP bash 2.04 has a bug in that @command{return} from a
16508 shell function which also used a command substitution causes a
16509 segmentation fault.  To work around the issue, you can use
16510 @command{return} from a subshell, or @samp{AS_SET_STATUS} as last command
16511 in the execution flow of the function (@pxref{Common Shell Constructs}).
16513 Not all shells treat shell functions as simple commands impacted by
16514 @samp{set -e}, for example with Solaris 10 @command{bin/sh}:
16516 @example
16517 $ @kbd{bash -c 'f() @{ return 1; @}; set -e; f; echo oops}
16518 $ @kbd{/bin/sh -c 'f() @{ return 1; @}; set -e; f; echo oops}
16519 oops
16520 @end example
16522 Shell variables and functions may share the same namespace, for example
16523 with Solaris 10 @command{/bin/sh}:
16525 @example
16526 $ @kbd{f () @{ :; @}; f=; f}
16527 f: not found
16528 @end example
16530 @noindent
16531 For this reason, Autoconf (actually M4sh, @pxref{Programming in M4sh})
16532 uses the prefix @samp{as_fn_} for its functions.
16534 Handling of positional parameters and shell options varies among shells.
16535 For example, Korn shells reset and restore trace output (@samp{set -x})
16536 and other options upon function entry and exit.  Inside a function,
16537 IRIX sh sets @samp{$0} to the function name.
16539 It is not portable to pass temporary environment variables to shell
16540 functions.  Solaris @command{/bin/sh} does not see the variable.
16541 Meanwhile, not all shells follow the Posix rule that the assignment must
16542 affect the current environment in the same manner as special built-ins.
16544 @example
16545 $ @kbd{/bin/sh -c 'func() @{ echo $a;@}; a=1 func; echo $a'}
16546 @result{}
16547 @result{}
16548 $ @kbd{ash -c 'func() @{ echo $a;@}; a=1 func; echo $a'}
16549 @result{}1
16550 @result{}
16551 $ @kbd{bash -c 'set -o posix; func() @{ echo $a;@}; a=1 func; echo $a'}
16552 @result{}1
16553 @result{}1
16554 @end example
16556 Some ancient Bourne shell variants with function support did not reset
16557 @samp{$@var{i}, @var{i} >= 0}, upon function exit, so effectively the
16558 arguments of the script were lost after the first function invocation.
16559 It is probably not worth worrying about these shells any more.
16561 With AIX sh, a @command{trap} on 0 installed in a shell function
16562 triggers at function exit rather than at script exit, see @xref{trap, ,
16563 Limitations of Shell Builtins}.
16565 @node Limitations of Builtins
16566 @section Limitations of Shell Builtins
16567 @cindex Shell builtins
16568 @cindex Limitations of shell builtins
16570 No, no, we are serious: some shells do have limitations!  :)
16572 You should always keep in mind that any builtin or command may support
16573 options, and therefore differ in behavior with arguments
16574 starting with a dash.  For instance, even the innocent @samp{echo "$word"}
16575 can give unexpected results when @code{word} starts with a dash.  It is
16576 often possible to avoid this problem using @samp{echo "x$word"}, taking
16577 the @samp{x} into account later in the pipe.  Many of these limitations
16578 can be worked around using M4sh (@pxref{Programming in M4sh}).
16580 @c This table includes things like `@command{test} (files)', so we can't
16581 @c use @table @command.
16582 @table @asis
16583 @item @command{.}
16584 @c --------------
16585 @prindex @command{.}
16586 Use @command{.} only with regular files (use @samp{test -f}).  Bash
16587 2.03, for instance, chokes on @samp{. /dev/null}.  Remember that
16588 @command{.} uses @env{PATH} if its argument contains no slashes.  Also,
16589 some shells, including bash 3.2, implicitly append the current directory
16590 to this @env{PATH} search, even though Posix forbids it.  So if you want
16591 to use @command{.} on a file @file{foo} in the current directory, you
16592 must use @samp{. ./foo}.
16594 Not all shells gracefully handle syntax errors within a sourced file.
16595 On one extreme, some non-interactive shells abort the entire script.  On
16596 the other, @command{zsh} 4.3.10 has a bug where it fails to react to the
16597 syntax error.
16599 @example
16600 $ @kbd{echo 'fi' > syntax}
16601 $ @kbd{bash -c '. ./syntax; echo $?'}
16602 ./syntax: line 1: syntax error near unexpected token `fi'
16603 ./syntax: line 1: `fi'
16605 $ @kbd{ash -c '. ./syntax; echo $?'}
16606 ./syntax: 1: Syntax error: "fi" unexpected
16607 $ @kbd{zsh -c '. ./syntax; echo $?'}
16608 ./syntax:1: parse error near `fi'
16610 @end example
16612 @item @command{!}
16613 @c --------------
16614 @prindex @command{!}
16615 The Unix version 7 shell did not support
16616 negating the exit status of commands with @command{!}, and this feature
16617 is still absent from some shells (e.g., Solaris @command{/bin/sh}).
16618 Other shells, such as FreeBSD @command{/bin/sh} or @command{ash}, have
16619 bugs when using @command{!}:
16621 @example
16622 $ @kbd{sh -c '! : | :'; echo $?}
16624 $ @kbd{ash -c '! : | :'; echo $?}
16626 $ @kbd{sh -c '! @{ :; @}'; echo $?}
16628 $ @kbd{ash -c '! @{ :; @}'; echo $?}
16629 @{: not found
16630 Syntax error: "@}" unexpected
16632 @end example
16634 Shell code like this:
16636 @example
16637 if ! cmp file1 file2 >/dev/null 2>&1; then
16638   echo files differ or trouble
16640 @end example
16642 is therefore not portable in practice.  Typically it is easy to rewrite
16643 such code, e.g.:
16645 @example
16646 cmp file1 file2 >/dev/null 2>&1 ||
16647   echo files differ or trouble
16648 @end example
16650 More generally, one can always rewrite @samp{! @var{command}} as:
16652 @example
16653 if @var{command}; then (exit 1); else :; fi
16654 @end example
16657 @item @command{@{...@}}
16658 @c --------------------
16659 @prindex @command{@{...@}}
16660 Bash 3.2 (and earlier versions) sometimes does not properly set
16661 @samp{$?} when failing to write redirected output of a compound command.
16662 This problem is most commonly observed with @samp{@{@dots{}@}}; it does
16663 not occur with @samp{(@dots{})}.  For example:
16665 @example
16666 $ @kbd{bash -c '@{ echo foo; @} >/bad; echo $?'}
16667 bash: line 1: /bad: Permission denied
16669 $ @kbd{bash -c 'while :; do echo; done >/bad; echo $?'}
16670 bash: line 1: /bad: Permission denied
16672 @end example
16674 To work around the bug, prepend @samp{:;}:
16676 @example
16677 $ @kbd{bash -c ':;@{ echo foo; @} >/bad; echo $?'}
16678 bash: line 1: /bad: Permission denied
16680 @end example
16682 Posix requires a syntax error if a brace list has no contents.  However,
16683 not all shells obey this rule; and on shells where empty lists are
16684 permitted, the effect on @samp{$?} is inconsistent.  To avoid problems,
16685 ensure that a brace list is never empty.
16687 @example
16688 $ @kbd{bash -c 'false; @{ @}; echo $?' || echo $?}
16689 bash: line 1: syntax error near unexpected token `@}'
16690 bash: line 1: `false; @{ @}; echo $?'
16692 $ @kbd{zsh -c 'false; @{ @}; echo $?' || echo $?}
16694 $ @kbd{pdksh -c 'false; @{ @}; echo $?' || echo $?}
16696 @end example
16699 @item @command{break}
16700 @c ------------------
16701 @prindex @command{break}
16702 The use of @samp{break 2} etc.@: is safe.
16705 @anchor{case}
16706 @item @command{case}
16707 @c -----------------
16708 @prindex @command{case}
16709 You don't need to quote the argument; no splitting is performed.
16711 You don't need the final @samp{;;}, but you should use it.
16713 Posix requires support for @code{case} patterns with opening
16714 parentheses like this:
16716 @example
16717 case $file_name in
16718   (*.c) echo "C source code";;
16719 esac
16720 @end example
16722 @noindent
16723 but the @code{(} in this example is not portable to many Bourne
16724 shell implementations, which is a pity for those of us using tools that
16725 rely on balanced parentheses.  For instance, with Solaris
16726 @command{/bin/sh}:
16728 @example
16729 $ @kbd{case foo in (foo) echo foo;; esac}
16730 @error{}syntax error: `(' unexpected
16731 @end example
16733 @noindent
16734 The leading @samp{(} can be omitted safely.  Unfortunately, there are
16735 contexts where unbalanced parentheses cause other problems, such as when
16736 using a syntax-highlighting editor that searches for the balancing
16737 counterpart, or more importantly, when using a case statement as an
16738 underquoted argument to an Autoconf macro.  @xref{Balancing
16739 Parentheses}, for tradeoffs involved in various styles of dealing with
16740 unbalanced @samp{)}.
16742 Zsh handles pattern fragments derived from parameter expansions or
16743 command substitutions as though quoted:
16745 @example
16746 $ pat=\?; case aa in ?$pat) echo match;; esac
16747 $ pat=\?; case a? in ?$pat) echo match;; esac
16748 match
16749 @end example
16751 @noindent
16752 Because of a bug in its @code{fnmatch}, Bash fails to properly
16753 handle backslashes in character classes:
16755 @example
16756 bash-2.02$ @kbd{case /tmp in [/\\]*) echo OK;; esac}
16757 bash-2.02$
16758 @end example
16760 @noindent
16761 This is extremely unfortunate, since you are likely to use this code to
16762 handle Posix or MS-DOS absolute file names.  To work around this
16763 bug, always put the backslash first:
16765 @example
16766 bash-2.02$ @kbd{case '\TMP' in [\\/]*) echo OK;; esac}
16768 bash-2.02$ @kbd{case /tmp in [\\/]*) echo OK;; esac}
16770 @end example
16772 Many Bourne shells cannot handle closing brackets in character classes
16773 correctly.
16775 Some shells also have problems with backslash escaping in case you do not want
16776 to match the backslash: both a backslash and the escaped character match this
16777 pattern.  To work around this, specify the character class in a variable, so
16778 that quote removal does not apply afterwards, and the special characters don't
16779 have to be backslash-escaped:
16781 @example
16782 $ @kbd{case '\' in [\<]) echo OK;; esac}
16784 $ @kbd{scanset='[<]'; case '\' in $scanset) echo OK;; esac}
16786 @end example
16788 Even with this, Solaris @command{ksh} matches a backslash if the set
16789 contains any
16790 of the characters @samp{|}, @samp{&}, @samp{(}, or @samp{)}.
16792 Conversely, Tru64 @command{ksh} (circa 2003) erroneously always matches
16793 a closing parenthesis if not specified in a character class:
16795 @example
16796 $ @kbd{case foo in *\)*) echo fail ;; esac}
16797 fail
16798 $ @kbd{case foo in *')'*) echo fail ;; esac}
16799 fail
16800 @end example
16802 Some shells, such as Ash 0.3.8, are confused by an empty
16803 @code{case}/@code{esac}:
16805 @example
16806 ash-0.3.8 $ @kbd{case foo in esac;}
16807 @error{}Syntax error: ";" unexpected (expecting ")")
16808 @end example
16810 Posix requires @command{case} to give an exit status of 0 if no cases
16811 match.  However, @command{/bin/sh} in Solaris 10 does not obey this
16812 rule.  Meanwhile, it is unclear whether a case that matches, but
16813 contains no statements, must also change the exit status to 0.  The M4sh
16814 macro @code{AS_CASE} works around these inconsistencies.
16816 @example
16817 $ @kbd{bash -c 'case `false` in ?) ;; esac; echo $?'}
16819 $ @kbd{/bin/sh -c 'case `false` in ?) ;; esac; echo $?'}
16821 @end example
16824 @item @command{cd}
16825 @c ---------------
16826 @prindex @command{cd}
16827 Posix 1003.1-2001 requires that @command{cd} must support
16828 the @option{-L} (``logical'') and @option{-P} (``physical'') options,
16829 with @option{-L} being the default.  However, traditional shells do
16830 not support these options, and their @command{cd} command has the
16831 @option{-P} behavior.
16833 Portable scripts should assume neither option is supported, and should
16834 assume neither behavior is the default.  This can be a bit tricky,
16835 since the Posix default behavior means that, for example,
16836 @samp{ls ..} and @samp{cd ..} may refer to different directories if
16837 the current logical directory is a symbolic link.  It is safe to use
16838 @code{cd @var{dir}} if @var{dir} contains no @file{..} components.
16839 Also, Autoconf-generated scripts check for this problem when computing
16840 variables like @code{ac_top_srcdir} (@pxref{Configuration Actions}),
16841 so it is safe to @command{cd} to these variables.
16843 Posix states that behavior is undefined if @command{cd} is given an
16844 explicit empty argument.  Some shells do nothing, some change to the
16845 first entry in @env{CDPATH}, some change to @env{HOME}, and some exit
16846 the shell rather than returning an error.  Unfortunately, this means
16847 that if @samp{$var} is empty, then @samp{cd "$var"} is less predictable
16848 than @samp{cd $var} (at least the latter is well-behaved in all shells
16849 at changing to @env{HOME}, although this is probably not what you wanted
16850 in a script).  You should check that a directory name was supplied
16851 before trying to change locations.
16853 See @xref{Special Shell Variables}, for portability problems involving
16854 @command{cd} and the @env{CDPATH} environment variable.
16855 Also please see the discussion of the @command{pwd} command.
16858 @anchor{echo}
16859 @item @command{echo}
16860 @c -----------------
16861 @prindex @command{echo}
16862 The simple @command{echo} is probably the most surprising source of
16863 portability troubles.  It is not possible to use @samp{echo} portably
16864 unless both options and escape sequences are omitted.  Don't expect any
16865 option.
16867 Do not use backslashes in the arguments, as there is no consensus on
16868 their handling.  For @samp{echo '\n' | wc -l}, the @command{sh} of
16869 Solaris outputs 2, but Bash and Zsh (in @command{sh} emulation mode) output 1.
16870 The problem is truly @command{echo}: all the shells
16871 understand @samp{'\n'} as the string composed of a backslash and an
16872 @samp{n}.  Within a command substitution, @samp{echo 'string\c'} will
16873 mess up the internal state of ksh88 on AIX 6.1 so that it will print
16874 the first character @samp{s} only, followed by a newline, and then
16875 entirely drop the output of the next echo in a command substitution.
16877 Because of these problems, do not pass a string containing arbitrary
16878 characters to @command{echo}.  For example, @samp{echo "$foo"} is safe
16879 only if you know that @var{foo}'s value cannot contain backslashes and
16880 cannot start with @samp{-}.
16882 If this may not be true, @command{printf} is in general safer and
16883 easier to use than @command{echo} and @command{echo -n}.  Thus, scripts
16884 where portability is not a major concern should use @command{printf
16885 '%s\n'} whenever @command{echo} could fail, and similarly use
16886 @command{printf %s} instead of @command{echo -n}. For portable shell
16887 scripts, instead, it is suggested to use a here-document like this:
16889 @example
16890 cat <<EOF
16891 $foo
16893 @end example
16895 Alternatively, M4sh provides @code{AS_ECHO} and @code{AS_ECHO_N} macros
16896 which choose between various portable implementations: @samp{echo}
16897 or @samp{print} where they work, @command{printf} if it is available,
16898 or else other creative tricks in order to work around the above problems.
16901 @item @command{eval}
16902 @c -----------------
16903 @prindex @command{eval}
16904 The @command{eval} command is useful in limited circumstances, e.g.,
16905 using commands like @samp{eval table_$key=\$value} and @samp{eval
16906 value=table_$key} to simulate a hash table when the key is known to be
16907 alphanumeric.
16909 You should also be wary of common bugs in @command{eval} implementations.
16910 In some shell implementations (e.g., older @command{ash}, OpenBSD 3.8
16911 @command{sh}, @command{pdksh} v5.2.14 99/07/13.2, and @command{zsh}
16912 4.2.5), the arguments of @samp{eval} are evaluated in a context where
16913 @samp{$?} is 0, so they exhibit behavior like this:
16915 @example
16916 $ @kbd{false; eval 'echo $?'}
16918 @end example
16920 The correct behavior here is to output a nonzero value,
16921 but portable scripts should not rely on this.
16923 You should not rely on @code{LINENO} within @command{eval}.
16924 @xref{Special Shell Variables}.
16926 Note that, even though these bugs are easily avoided,
16927 @command{eval} is tricky to use on arbitrary arguments.
16928 It is obviously unwise to use @samp{eval $cmd} if the string value of
16929 @samp{cmd} was derived from an untrustworthy source.  But even if the
16930 string value is valid, @samp{eval $cmd} might not work as intended,
16931 since it causes field splitting and file name expansion to occur twice,
16932 once for the @command{eval} and once for the command itself.  It is
16933 therefore safer to use @samp{eval "$cmd"}.  For example, if @var{cmd}
16934 has the value @samp{cat test?.c}, @samp{eval $cmd} might expand to the
16935 equivalent of @samp{cat test;.c} if there happens to be a file named
16936 @file{test;.c} in the current directory; and this in turn
16937 mistakenly attempts to invoke @command{cat} on the file @file{test} and
16938 then execute the command @command{.c}.  To avoid this problem, use
16939 @samp{eval "$cmd"} rather than @samp{eval $cmd}.
16941 However, suppose that you want to output the text of the evaluated
16942 command just before executing it.  Assuming the previous example,
16943 @samp{echo "Executing: $cmd"} outputs @samp{Executing: cat test?.c}, but
16944 this output doesn't show the user that @samp{test;.c} is the actual name
16945 of the copied file.  Conversely, @samp{eval "echo Executing: $cmd"}
16946 works on this example, but it fails with @samp{cmd='cat foo >bar'},
16947 since it mistakenly replaces the contents of @file{bar} by the
16948 string @samp{cat foo}.  No simple, general, and portable solution to
16949 this problem is known.
16951 @item @command{exec}
16952 @c -----------------
16953 @prindex @command{exec}
16954 Posix describes several categories of shell built-ins.  Special
16955 built-ins (such as @command{exit}) must impact the environment of the
16956 current shell, and need not be available through @command{exec}.  All
16957 other built-ins are regular, and must not propagate variable assignments
16958 to the environment of the current shell.  However, the group of regular
16959 built-ins is further distinguished by commands that do not require a
16960 @env{PATH} search (such as @command{cd}), in contrast to built-ins that
16961 are offered as a more efficient version of something that must still be
16962 found in a @env{PATH} search (such as @command{echo}).  Posix is not
16963 clear on whether @command{exec} must work with the list of 17 utilities
16964 that are invoked without a @env{PATH} search, and many platforms lack an
16965 executable for some of those built-ins:
16967 @example
16968 $ @kbd{sh -c 'exec cd /tmp'}
16969 sh: line 0: exec: cd: not found
16970 @end example
16972 All other built-ins that provide utilities specified by Posix must have
16973 a counterpart executable that exists on @env{PATH}, although Posix
16974 allows @command{exec} to use the built-in instead of the executable.
16975 For example, contrast @command{bash} 3.2 and @command{pdksh} 5.2.14:
16977 @example
16978 $ @kbd{bash -c 'pwd --version' | head -n1}
16979 bash: line 0: pwd: --: invalid option
16980 pwd: usage: pwd [-LP]
16981 $ @kbd{bash -c 'exec pwd --version' | head -n1}
16982 pwd (GNU coreutils) 6.10
16983 $ @kbd{pdksh -c 'exec pwd --version' | head -n1}
16984 pdksh: pwd: --: unknown option
16985 @end example
16987 When it is desired to avoid a regular shell built-in, the workaround is
16988 to use some other forwarding command, such as @command{env} or
16989 @command{nice}, that will ensure a path search:
16991 @example
16992 $ @kbd{pdksh -c 'exec true --version' | head -n1}
16993 $ @kbd{pdksh -c 'nice true --version' | head -n1}
16994 true (GNU coreutils) 6.10
16995 $ @kbd{pdksh -c 'env true --version' | head -n1}
16996 true (GNU coreutils) 6.10
16997 @end example
16999 @item @command{exit}
17000 @c -----------------
17001 @prindex @command{exit}
17002 The default value of @command{exit} is supposed to be @code{$?};
17003 unfortunately, some shells, such as the DJGPP port of Bash 2.04, just
17004 perform @samp{exit 0}.
17006 @example
17007 bash-2.04$ @kbd{foo=`exit 1` || echo fail}
17008 fail
17009 bash-2.04$ @kbd{foo=`(exit 1)` || echo fail}
17010 fail
17011 bash-2.04$ @kbd{foo=`(exit 1); exit` || echo fail}
17012 bash-2.04$
17013 @end example
17015 Using @samp{exit $?} restores the expected behavior.
17017 Some shell scripts, such as those generated by @command{autoconf}, use a
17018 trap to clean up before exiting.  If the last shell command exited with
17019 nonzero status, the trap also exits with nonzero status so that the
17020 invoker can tell that an error occurred.
17022 Unfortunately, in some shells, such as Solaris @command{/bin/sh}, an exit
17023 trap ignores the @code{exit} command's argument.  In these shells, a trap
17024 cannot determine whether it was invoked by plain @code{exit} or by
17025 @code{exit 1}.  Instead of calling @code{exit} directly, use the
17026 @code{AC_MSG_ERROR} macro that has a workaround for this problem.
17029 @anchor{export}
17030 @item @command{export}
17031 @c -------------------
17032 @prindex @command{export}
17033 The builtin @command{export} dubs a shell variable @dfn{environment
17034 variable}.  Each update of exported variables corresponds to an update
17035 of the environment variables.  Conversely, each environment variable
17036 received by the shell when it is launched should be imported as a shell
17037 variable marked as exported.
17039 Alas, many shells, such as Solaris @command{/bin/sh},
17040 IRIX 6.3, IRIX 5.2,
17041 AIX 4.1.5, and Digital Unix 4.0, forget to
17042 @command{export} the environment variables they receive.  As a result,
17043 two variables coexist: the environment variable and the shell
17044 variable.  The following code demonstrates this failure:
17046 @example
17047 #!/bin/sh
17048 echo $FOO
17049 FOO=bar
17050 echo $FOO
17051 exec /bin/sh $0
17052 @end example
17054 @noindent
17055 when run with @samp{FOO=foo} in the environment, these shells print
17056 alternately @samp{foo} and @samp{bar}, although they should print only
17057 @samp{foo} and then a sequence of @samp{bar}s.
17059 Therefore you should @command{export} again each environment variable
17060 that you update; the export can occur before or after the assignment.
17062 Posix is not clear on whether the @command{export} of an undefined
17063 variable causes the variable to be defined with the value of an empty
17064 string, or merely marks any future definition of a variable by that name
17065 for export.  Various shells behave differently in this regard:
17067 @example
17068 $ @kbd{sh -c 'export foo; env | grep foo'}
17069 $ @kbd{ash -c 'export foo; env | grep foo'}
17070 foo=
17071 @end example
17073 @item @command{false}
17074 @c ------------------
17075 @prindex @command{false}
17076 Don't expect @command{false} to exit with status 1: in native
17077 Solaris @file{/bin/false} exits with status 255.
17080 @item @command{for}
17081 @c ----------------
17082 @prindex @command{for}
17083 To loop over positional arguments, use:
17085 @example
17086 for arg
17088   echo "$arg"
17089 done
17090 @end example
17092 @noindent
17093 You may @emph{not} leave the @code{do} on the same line as @code{for},
17094 since some shells improperly grok:
17096 @example
17097 for arg; do
17098   echo "$arg"
17099 done
17100 @end example
17102 If you want to explicitly refer to the positional arguments, given the
17103 @samp{$@@} bug (@pxref{Shell Substitutions}), use:
17105 @example
17106 for arg in $@{1+"$@@"@}; do
17107   echo "$arg"
17108 done
17109 @end example
17111 @noindent
17112 But keep in mind that Zsh, even in Bourne shell emulation mode, performs
17113 word splitting on @samp{$@{1+"$@@"@}}; see @ref{Shell Substitutions},
17114 item @samp{$@@}, for more.
17116 In Solaris @command{/bin/sh}, when the list of arguments of a
17117 @command{for} loop starts with @emph{unquoted} tokens looking like
17118 variable assignments, the loop is not executed on those tokens:
17120 @example
17121 $ @kbd{/bin/sh -c 'for v in a=b c=d x e=f; do echo $v; done'}
17124 @end example
17126 @noindent
17127 Thankfully, quoting the assignment-like tokens, or starting the list
17128 with other tokens (including unquoted variable expansion that results in
17129 an assignment-like result), avoids the problem, so it is easy to work
17130 around:
17132 @example
17133 $ @kbd{/bin/sh -c 'for v in "a=b"; do echo $v; done'}
17135 $ @kbd{/bin/sh -c 'x=a=b; for v in $x c=d; do echo $v; done'}
17138 @end example
17140 @anchor{if}
17141 @item @command{if}
17142 @c ---------------
17143 @prindex @command{if}
17144 Using @samp{!} is not portable.  Instead of:
17146 @example
17147 if ! cmp -s file file.new; then
17148   mv file.new file
17150 @end example
17152 @noindent
17153 use:
17155 @example
17156 if cmp -s file file.new; then :; else
17157   mv file.new file
17159 @end example
17161 @noindent
17162 Or, especially if the @dfn{else} branch is short, you can use @code{||}.
17163 In M4sh, the @code{AS_IF} macro provides an easy way to write these kinds
17164 of conditionals:
17166 @example
17167 AS_IF([cmp -s file file.new], [], [mv file.new file])
17168 @end example
17170 This is especially useful in other M4 macros, where the @dfn{then} and
17171 @dfn{else} branches might be macro arguments.
17173 Some very old shells did not reset the exit status from an @command{if}
17174 with no @command{else}:
17176 @example
17177 $ @kbd{if (exit 42); then true; fi; echo $?}
17179 @end example
17181 @noindent
17182 whereas a proper shell should have printed @samp{0}.  But this is no
17183 longer a portability problem; any shell that supports functions gets it
17184 correct.  However, it explains why some makefiles have lengthy
17185 constructs:
17187 @example
17188 if test -f "$file"; then
17189   install "$file" "$dest"
17190 else
17191   :
17193 @end example
17196 @item @command{printf}
17197 @c ------------------
17198 @prindex @command{printf}
17199 A format string starting with a @samp{-} can cause problems.
17200 Bash interprets it as an option and
17201 gives an error.  And @samp{--} to mark the end of options is not good
17202 in the NetBSD Almquist shell (e.g., 0.4.6) which takes that
17203 literally as the format string.  Putting the @samp{-} in a @samp{%c}
17204 or @samp{%s} is probably easiest:
17206 @example
17207 printf %s -foo
17208 @end example
17210 Bash 2.03 mishandles an escape sequence that happens to evaluate to @samp{%}:
17212 @example
17213 $ @kbd{printf '\045'}
17214 bash: printf: `%': missing format character
17215 @end example
17217 Large outputs may cause trouble.  On Solaris 2.5.1 through 10, for
17218 example, @file{/usr/bin/printf} is buggy, so when using
17219 @command{/bin/sh} the command @samp{printf %010000x 123} normally dumps
17220 core.
17222 Since @command{printf} is not always a shell builtin, there is a
17223 potential speed penalty for using @code{printf '%s\n'} as a replacement
17224 for an @command{echo} that does not interpret @samp{\} or leading
17225 @samp{-}. With Solaris @command{ksh}, it is possible to use @code{print
17226 -r --} for this role instead.
17228 For a discussion of portable alternatives to both @command{printf}
17229 and @command{echo}, @xref{echo, , Limitations of Shell Builtins}.
17232 @item @command{pwd}
17233 @c ----------------
17234 @prindex @command{pwd}
17235 With modern shells, plain @command{pwd} outputs a ``logical''
17236 directory name, some of whose components may be symbolic links.  These
17237 directory names are in contrast to ``physical'' directory names, whose
17238 components are all directories.
17240 Posix 1003.1-2001 requires that @command{pwd} must support
17241 the @option{-L} (``logical'') and @option{-P} (``physical'') options,
17242 with @option{-L} being the default.  However, traditional shells do
17243 not support these options, and their @command{pwd} command has the
17244 @option{-P} behavior.
17246 Portable scripts should assume neither option is supported, and should
17247 assume neither behavior is the default.  Also, on many hosts
17248 @samp{/bin/pwd} is equivalent to @samp{pwd -P}, but Posix
17249 does not require this behavior and portable scripts should not rely on
17252 Typically it's best to use plain @command{pwd}.  On modern hosts this
17253 outputs logical directory names, which have the following advantages:
17255 @itemize @bullet
17256 @item
17257 Logical names are what the user specified.
17258 @item
17259 Physical names may not be portable from one installation
17260 host to another due to network file system gymnastics.
17261 @item
17262 On modern hosts @samp{pwd -P} may fail due to lack of permissions to
17263 some parent directory, but plain @command{pwd} cannot fail for this
17264 reason.
17265 @end itemize
17267 Also please see the discussion of the @command{cd} command.
17270 @item @command{read}
17271 @c -----------------
17272 @prindex @command{read}
17273 No options are portable, not even support @option{-r} (Solaris
17274 @command{/bin/sh} for example).
17277 @anchor{set}
17278 @item @command{set}
17279 @c ----------------
17280 @prindex @command{set}
17281 With the FreeBSD 6.0 shell, the @command{set} command (without
17282 any options) does not sort its output.
17284 The @command{set} builtin faces the usual problem with arguments
17285 starting with a
17286 dash.  Modern shells such as Bash or Zsh understand @option{--} to specify
17287 the end of the options (any argument after @option{--} is a parameter,
17288 even @samp{-x} for instance), but many traditional shells (e.g., Solaris
17289 10 @command{/bin/sh}) simply stop option
17290 processing as soon as a non-option argument is found.  Therefore, use
17291 @samp{dummy} or simply @samp{x} to end the option processing, and use
17292 @command{shift} to pop it out:
17294 @example
17295 set x $my_list; shift
17296 @end example
17298 Avoid @samp{set -}, e.g., @samp{set - $my_list}.  Posix no
17299 longer requires support for this command, and in traditional shells
17300 @samp{set - $my_list} resets the @option{-v} and @option{-x} options, which
17301 makes scripts harder to debug.
17303 Some nonstandard shells do not recognize more than one option
17304 (e.g., @samp{set -e -x} assigns @samp{-x} to the command line).  It is
17305 better to combine them:
17307 @example
17308 set -ex
17309 @end example
17311 @cindex @command{set -e}
17312 The option @option{-e} has historically been underspecified, with enough
17313 ambiguities to cause numerous differences across various shell
17314 implementations.  Perhaps the best reference is
17315 @uref{http://www.opengroup.org/@/austin/@/mailarchives/@/ag-review/@/msg03507.html,
17316 this link}, recommending a change to Posix 2008 to match @command{ksh88}
17317 behavior.  Note that mixing @code{set -e} and shell functions is asking
17318 for surprises:
17320 @example
17321 set -e
17322 doit()
17324   rm file
17325   echo one
17327 doit || echo two
17328 @end example
17330 @noindent
17331 According to the recommendation, @samp{one} should always be output
17332 regardless of whether the @command{rm} failed, because it occurs within
17333 the body of the shell function @samp{doit} invoked on the left side of
17334 @samp{||}, where the effects of @samp{set -e} are not enforced.
17335 Likewise, @samp{two} should never be printed, since the failure of
17336 @command{rm} does not abort the function, such that the status of
17337 @samp{doit} is 0.
17339 The BSD shell has had several problems with the @option{-e}
17340 option.  Older versions of the BSD
17341 shell (circa 1990) mishandled @samp{&&}, @samp{||}, @samp{if}, and
17342 @samp{case} when @option{-e} was in effect, causing the shell to exit
17343 unexpectedly in some cases.  This was particularly a problem with
17344 makefiles, and led to circumlocutions like @samp{sh -c 'test -f file ||
17345 touch file'}, where the seemingly-unnecessary @samp{sh -c '@dots{}'}
17346 wrapper works around the bug (@pxref{Failure in Make Rules}).
17348 Even relatively-recent versions of the BSD shell (e.g., OpenBSD 3.4)
17349 wrongly exit with @option{-e} if the last command within a compound
17350 statement fails and is guarded by an @samp{&&} only.  For example:
17352 @example
17353 #! /bin/sh
17354 set -e
17355 foo=''
17356 test -n "$foo" && exit 1
17357 echo one
17358 if :; then
17359   test -n "$foo" && exit 1
17360   echo two
17361   test -n "$foo" && exit 1
17363 echo three
17364 @end example
17366 @noindent
17367 does not print @samp{three}.  One workaround is to change the last
17368 instance of @samp{test -n "$foo" && exit 1} to be @samp{if test -n
17369 "$foo"; then exit 1; fi} instead.  Another possibility is to warn BSD
17370 users not to use @samp{sh -e}.
17372 When @samp{set -e} is in effect, a failed command substitution in
17373 Solaris @command{/bin/sh} cannot be ignored, even with @samp{||}.
17375 @example
17376 $ @kbd{/bin/sh -c 'set -e; foo=`false` || echo foo; echo bar'}
17377 $ @kbd{bash -c 'set -e; foo=`false` || echo foo; echo bar'}
17380 @end example
17382 @noindent
17383 Moreover, a command substitution, successful or not, causes this shell to
17384 exit from a failing outer command even in presence of an @samp{&&} list:
17386 @example
17387 $ @kbd{bash -c 'set -e; false `true` && echo notreached; echo ok'}
17389 $ @kbd{sh -c 'set -e; false `true` && echo notreached; echo ok'}
17391 @end example
17393 Portable scripts should not use @samp{set -e} if @command{trap} is used
17394 to install an exit handler.  This is because Tru64/OSF 5.1 @command{sh}
17395 sometimes enters the trap handler with the exit status of the command
17396 prior to the one that triggered the errexit handler:
17398 @example
17399 $ @kbd{sh -ec 'trap '\''echo $?'\'' 0; false'}
17401 $ @kbd{sh -c 'set -e; trap '\''echo $?'\'' 0; false'}
17403 @end example
17405 @noindent
17406 Thus, when writing a script in M4sh, rather than trying to rely on
17407 @samp{set -e}, it is better to append @samp{|| AS_EXIT} to any
17408 statement where it is desirable to abort on failure.
17410 @cindex @command{set -b}
17411 @cindex @command{set -m}
17412 Job control is not provided by all shells, so the use of @samp{set -m}
17413 or @samp{set -b} must be done with care.  When using @command{zsh} in
17414 native mode, asynchronous notification (@samp{set -b}) is enabled by
17415 default, and using @samp{emulate sh} to switch to Posix mode does not
17416 clear this setting (although asynchronous notification has no impact
17417 unless job monitoring is also enabled).  Also, @command{zsh} 4.3.10 and
17418 earlier have a bug where job control can be manipulated in interactive
17419 shells, but not in subshells or scripts.  Furthermore, some shells, like
17420 @command{pdksh}, fail to treat subshells as interactive, even though the
17421 parent shell was.
17423 @example
17424 $ @kbd{echo $ZSH_VERSION}
17425 4.3.10
17426 $ @kbd{set -m; echo $?}
17428 $ @kbd{zsh -c 'set -m; echo $?'}
17429 set: can't change option: -m
17430 $ @kbd{(set -m); echo $?}
17431 set: can't change option: -m
17433 $ @kbd{pdksh -ci 'echo $-; (echo $-)'}
17436 @end example
17439 @item @command{shift}
17440 @c ------------------
17441 @prindex @command{shift}
17442 Not only is @command{shift}ing a bad idea when there is nothing left to
17443 shift, but in addition it is not portable: the shell of MIPS
17444 RISC/OS 4.52 refuses to do it.
17446 Don't use @samp{shift 2} etc.; while it in the SVR1 shell (1983),
17447 it is also absent in many pre-Posix shells.
17450 @item @command{source}
17451 @c -------------------
17452 @prindex @command{source}
17453 This command is not portable, as Posix does not require it; use
17454 @command{.} instead.
17457 @item @command{test}
17458 @c -----------------
17459 @prindex @command{test}
17460 The @code{test} program is the way to perform many file and string
17461 tests.  It is often invoked by the alternate name @samp{[}, but using
17462 that name in Autoconf code is asking for trouble since it is an M4 quote
17463 character.
17465 The @option{-a}, @option{-o}, @samp{(}, and @samp{)} operands are not
17466 present in all implementations, and have been marked obsolete by Posix
17467 2008.  This is because there are inherent ambiguities in using them.
17468 For example, @samp{test "$1" -a "$2"} looks like a binary operator to
17469 check whether two strings are both non-empty, but if @samp{$1} is the
17470 literal @samp{!}, then some implementations of @command{test} treat it
17471 as a negation of the unary operator @option{-a}.
17473 Thus, portable uses of @command{test} should never have more than four
17474 arguments, and scripts should use shell constructs like @samp{&&} and
17475 @samp{||} instead.  If you combine @samp{&&} and @samp{||} in the same
17476 statement, keep in mind that they have equal precedence, so it is often
17477 better to parenthesize even when this is redundant.  For example:
17479 @smallexample
17480 # Not portable:
17481 test "X$a" = "X$b" -a \
17482   '(' "X$c" != "X$d" -o "X$e" = "X$f" ')'
17484 # Portable:
17485 test "X$a" = "X$b" &&
17486   @{ test "X$c" != "X$d" || test "X$e" = "X$f"; @}
17487 @end smallexample
17489 @command{test} does not process options like most other commands do; for
17490 example, it does not recognize the @option{--} argument as marking the
17491 end of options.
17493 It is safe to use @samp{!} as a @command{test} operator.  For example,
17494 @samp{if test ! -d foo; @dots{}} is portable even though @samp{if ! test
17495 -d foo; @dots{}} is not.
17498 @item @command{test} (files)
17499 @c -------------------------
17500 To enable @command{configure} scripts to support cross-compilation, they
17501 shouldn't do anything that tests features of the build system instead of
17502 the host system.  But occasionally you may find it necessary to check
17503 whether some arbitrary file exists.  To do so, use @samp{test -f} or
17504 @samp{test -r}.  Do not use @samp{test -x}, because 4.3BSD does not
17505 have it.  Do not use @samp{test -e} either, because Solaris @command{/bin/sh}
17506 lacks it.  To test for symbolic links on systems that have them, use
17507 @samp{test -h} rather than @samp{test -L}; either form conforms to
17508 Posix 1003.1-2001, but older shells like Solaris 8
17509 @code{/bin/sh} support only @option{-h}.
17511 @item @command{test} (strings)
17512 @c ---------------------------
17513 Posix says that @samp{test "@var{string}"} succeeds if @var{string} is
17514 not null, but this usage is not portable to traditional platforms like
17515 Solaris 10 @command{/bin/sh}, which mishandle strings like @samp{!} and
17516 @samp{-n}.
17518 Posix also says that @samp{test ! "@var{string}"},
17519 @samp{test -n "@var{string}"} and
17520 @samp{test -z "@var{string}"} work with any string, but many
17521 shells (such as Solaris, AIX 3.2, UNICOS 10.0.0.6,
17522 Digital Unix 4, etc.)@: get confused if
17523 @var{string} looks like an operator:
17525 @example
17526 $ @kbd{test -n =}
17527 test: argument expected
17528 $ @kbd{test ! -n}
17529 test: argument expected
17530 $ @kbd{test -z ")"; echo $?}
17532 @end example
17534 Similarly, Posix says that both @samp{test "@var{string1}" = "@var{string2"}}
17535 and @samp{test "@var{string1}" != "@var{string2"}} work for any pairs of
17536 strings, but in practice this is not true for troublesome strings that
17537 look like operators or parentheses, or that begin with @samp{-}.
17539 It is best to protect such strings with a leading @samp{X}, e.g.,
17540 @samp{test "X@var{string}" != X} rather than @samp{test -n
17541 "@var{string}"} or @samp{test ! "@var{string}"}.
17543 It is common to find variations of the following idiom:
17545 @example
17546 test -n "`echo $ac_feature | sed 's/[-a-zA-Z0-9_]//g'`" &&
17547   @var{action}
17548 @end example
17550 @noindent
17551 to take an action when a token matches a given pattern.  Such constructs
17552 should be avoided by using:
17554 @example
17555 case $ac_feature in
17556   *[!-a-zA-Z0-9_]*) @var{action};;
17557 esac
17558 @end example
17560 If the pattern is a complicated regular expression that cannot be
17561 expressed as a shell pattern, use something like this instead:
17563 @example
17564 expr "X$ac_feature" : 'X.*[^-a-zA-Z0-9_]' >/dev/null &&
17565   @var{action}
17566 @end example
17568 @samp{expr "X@var{foo}" : "X@var{bar}"} is more robust than @samp{echo
17569 "X@var{foo}" | grep "^X@var{bar}"}, because it avoids problems when
17570 @samp{@var{foo}} contains backslashes.
17573 @anchor{trap}
17574 @item @command{trap}
17575 @c -----------------
17576 @prindex @command{trap}
17577 It is safe to trap at least the signals 1, 2, 13, and 15.  You can also
17578 trap 0, i.e., have the @command{trap} run when the script ends (either via an
17579 explicit @command{exit}, or the end of the script).  The trap for 0 should be
17580 installed outside of a shell function, or AIX 5.3 @command{/bin/sh}
17581 will invoke the trap at the end of this function.
17583 Posix says that @samp{trap - 1 2 13 15} resets the traps for the
17584 specified signals to their default values, but many common shells (e.g.,
17585 Solaris @command{/bin/sh}) misinterpret this and attempt to execute a
17586 ``command'' named @command{-} when the specified conditions arise.
17587 Posix 2008 also added a requirement to support @samp{trap 1 2 13 15} to
17588 reset traps, as this is supported by a larger set of shells, but there
17589 are still shells like @command{dash} that mistakenly try to execute
17590 @command{1} instead of resetting the traps.  Therefore, there is no
17591 portable workaround, except for @samp{trap - 0}, for which
17592 @samp{trap '' 0} is a portable substitute.
17594 Although Posix is not absolutely clear on this point, it is widely
17595 admitted that when entering the trap @samp{$?} should be set to the exit
17596 status of the last command run before the trap.  The ambiguity can be
17597 summarized as: ``when the trap is launched by an @command{exit}, what is
17598 the @emph{last} command run: that before @command{exit}, or
17599 @command{exit} itself?''
17601 Bash considers @command{exit} to be the last command, while Zsh and
17602 Solaris @command{/bin/sh} consider that when the trap is run it is
17603 @emph{still} in the @command{exit}, hence it is the previous exit status
17604 that the trap receives:
17606 @example
17607 $ @kbd{cat trap.sh}
17608 trap 'echo $?' 0
17609 (exit 42); exit 0
17610 $ @kbd{zsh trap.sh}
17612 $ @kbd{bash trap.sh}
17614 @end example
17616 The portable solution is then simple: when you want to @samp{exit 42},
17617 run @samp{(exit 42); exit 42}, the first @command{exit} being used to
17618 set the exit status to 42 for Zsh, and the second to trigger the trap
17619 and pass 42 as exit status for Bash.  In M4sh, this is covered by using
17620 @code{AS_EXIT}.
17622 The shell in FreeBSD 4.0 has the following bug: @samp{$?} is
17623 reset to 0 by empty lines if the code is inside @command{trap}.
17625 @example
17626 $ @kbd{trap 'false}
17628 echo $?' 0
17629 $ @kbd{exit}
17631 @end example
17633 @noindent
17634 Fortunately, this bug only affects @command{trap}.
17636 Several shells fail to execute an exit trap that is defined inside a
17637 subshell, when the last command of that subshell is not a builtin.  A
17638 workaround is to use @samp{exit $?} as the shell builtin.
17640 @example
17641 $ @kbd{bash -c '(trap "echo hi" 0; /bin/true)'}
17643 $ @kbd{/bin/sh -c '(trap "echo hi" 0; /bin/true)'}
17644 $ @kbd{/bin/sh -c '(trap "echo hi" 0; /bin/true; exit $?)'}
17646 @end example
17648 @noindent
17649 Likewise, older implementations of @command{bash} failed to preserve
17650 @samp{$?} across an exit trap consisting of a single cleanup command.
17652 @example
17653 $ @kbd{bash -c 'trap "/bin/true" 0; exit 2'; echo $?}
17655 $ @kbd{bash-2.05b -c 'trap "/bin/true" 0; exit 2'; echo $?}
17657 $ @kbd{bash-2.05b -c 'trap ":; /bin/true" 0; exit 2'; echo $?}
17659 @end example
17661 @item @command{true}
17662 @c -----------------
17663 @prindex @command{true}
17664 @c Info cannot handle `:' in index entries.
17665 @c @prindex @command{:}
17666 Don't worry: as far as we know @command{true} is portable.
17667 Nevertheless, it's not always a builtin (e.g., Bash 1.x), and the
17668 portable shell community tends to prefer using @command{:}.  This has a
17669 funny side effect: when asked whether @command{false} is more portable
17670 than @command{true} Alexandre Oliva answered:
17672 @quotation
17673 In a sense, yes, because if it doesn't exist, the shell will produce an
17674 exit status of failure, which is correct for @command{false}, but not
17675 for @command{true}.
17676 @end quotation
17678 Remember that even though @samp{:} ignores its arguments, it still takes
17679 time to compute those arguments.  It is a good idea to use double quotes
17680 around any arguments to @samp{:} to avoid time spent in field splitting
17681 and file name expansion.
17684 @anchor{unset}
17685 @item @command{unset}
17686 @c ------------------
17687 @prindex @command{unset}
17688 In some nonconforming shells (e.g., Bash 2.05a), @code{unset FOO} fails
17689 when @code{FOO} is not set.  You can use
17691 @smallexample
17692 FOO=; unset FOO
17693 @end smallexample
17695 if you are not sure that @code{FOO} is set.
17697 A few ancient shells lack @command{unset} entirely.  For some variables
17698 such as @code{PS1}, you can use a neutralizing value instead:
17700 @smallexample
17701 PS1='$ '
17702 @end smallexample
17704 Usually, shells that do not support @command{unset} need less effort to
17705 make the environment sane, so for example is not a problem if you cannot
17706 unset @command{CDPATH} on those shells.  However, Bash 2.01 mishandles
17707 @code{unset MAIL} in some cases and dumps core.  So, you should do
17708 something like
17710 @smallexample
17711 ( (unset MAIL) || exit 1) >/dev/null 2>&1 && unset MAIL || :
17712 @end smallexample
17714 @noindent
17715 @xref{Special Shell Variables}, for some neutralizing values.  Also, see
17716 @ref{export, , Limitations of Builtins}, for
17717 the case of environment variables.
17719 @item @command{wait}
17720 @c -----------------
17721 @prindex @command{wait}
17722 The exit status of @command{wait} is not always reliable.
17723 @end table
17725 @node Limitations of Usual Tools
17726 @section Limitations of Usual Tools
17727 @cindex Limitations of usual tools
17729 The small set of tools you can expect to find on any machine can still
17730 include some limitations you should be aware of.
17732 @comment Between this list and the list of builtins above, we should
17733 @comment mention all the tools in GNU Coding Standards ``Utilities in
17734 @comment Makefiles''.
17736 @c This table includes things like `@command{expr} (|)', so we can't
17737 @c use @table @command.
17738 @table @asis
17739 @anchor{awk}
17740 @item @command{awk}
17741 @c ----------------
17742 @prindex @command{awk}
17743 Don't leave white space before the opening parenthesis in a user function call.
17744 Posix does not allow this and GNU Awk rejects it:
17746 @example
17747 $ @kbd{gawk 'function die () @{ print "Aaaaarg!"  @}
17748         BEGIN @{ die () @}'}
17749 gawk: cmd. line:2:         BEGIN @{ die () @}
17750 gawk: cmd. line:2:                      ^ parse error
17751 $ @kbd{gawk 'function die () @{ print "Aaaaarg!"  @}
17752         BEGIN @{ die() @}'}
17753 Aaaaarg!
17754 @end example
17756 Posix says that if a program contains only @samp{BEGIN} actions, and
17757 contains no instances of @code{getline}, then the program merely
17758 executes the actions without reading input.  However, traditional Awk
17759 implementations (such as Solaris 10 @command{awk}) read and discard
17760 input in this case.  Portable scripts can redirect input from
17761 @file{/dev/null} to work around the problem.  For example:
17763 @example
17764 awk 'BEGIN @{print "hello world"@}' </dev/null
17765 @end example
17767 Posix says that in an @samp{END} action, @samp{$NF} (and presumably,
17768 @samp{$1}) retain their value from the last record read, if no
17769 intervening @samp{getline} occurred.  However, some implementations
17770 (such as Solaris 10 @samp{/usr/bin/awk}, @samp{nawk}, or Darwin
17771 @samp{awk}) reset these variables.  A workaround is to use an
17772 intermediate variable prior to the @samp{END} block.  For example:
17774 @example
17775 $ @kbd{cat end.awk}
17776 @{ tmp = $1 @}
17777 END @{ print "a", $1, $NF, "b", tmp @}
17778 $ @kbd{echo 1 | awk -f end.awk}
17779 a   b 1
17780 $ @kbd{echo 1 | gawk -f end.awk}
17781 a 1 1 b 1
17782 @end example
17784 If you want your program to be deterministic, don't depend on @code{for}
17785 on arrays:
17787 @example
17788 $ @kbd{cat for.awk}
17789 END @{
17790   arr["foo"] = 1
17791   arr["bar"] = 1
17792   for (i in arr)
17793     print i
17795 $ @kbd{gawk -f for.awk </dev/null}
17798 $ @kbd{nawk -f for.awk </dev/null}
17801 @end example
17803 Some Awk implementations, such as HP-UX 11.0's native one,
17804 mishandle anchors:
17806 @example
17807 $ @kbd{echo xfoo | $AWK '/foo|^bar/ @{ print @}'}
17808 $ @kbd{echo bar | $AWK '/foo|^bar/ @{ print @}'}
17810 $ @kbd{echo xfoo | $AWK '/^bar|foo/ @{ print @}'}
17811 xfoo
17812 $ @kbd{echo bar | $AWK '/^bar|foo/ @{ print @}'}
17814 @end example
17816 @noindent
17817 Either do not depend on such patterns (i.e., use @samp{/^(.*foo|bar)/},
17818 or use a simple test to reject such implementations.
17820 On @samp{ia64-hp-hpux11.23}, Awk mishandles @code{printf} conversions
17821 after @code{%u}:
17823 @example
17824 $ @kbd{awk 'BEGIN @{ printf "%u %d\n", 0, -1 @}'}
17825 0 0
17826 @end example
17828 AIX version 5.2 has an arbitrary limit of 399 on the
17829 length of regular expressions and literal strings in an Awk program.
17831 Traditional Awk implementations derived from Unix version 7, such as
17832 Solaris @command{/bin/awk}, have many limitations and do not
17833 conform to Posix.  Nowadays @code{AC_PROG_AWK} (@pxref{Particular
17834 Programs}) finds you an Awk that doesn't have these problems, but if
17835 for some reason you prefer not to use @code{AC_PROG_AWK} you may need to
17836 address them.  For more detailed descriptions, see @ref{Language
17837 History, , @command{awk} language history, gawk, GNU Awk User's Guide}.
17839 Traditional Awk does not support multidimensional arrays or user-defined
17840 functions.
17842 Traditional Awk does not support the @option{-v} option.  You can use
17843 assignments after the program instead, e.g., @code{$AWK '@{print v
17844 $1@}' v=x}; however, don't forget that such assignments are not
17845 evaluated until they are encountered (e.g., after any @code{BEGIN}
17846 action).
17848 Traditional Awk does not support the keywords @code{delete} or @code{do}.
17850 Traditional Awk does not support the expressions
17851 @code{@var{a}?@var{b}:@var{c}}, @code{!@var{a}}, @code{@var{a}^@var{b}},
17852 or @code{@var{a}^=@var{b}}.
17854 Traditional Awk does not support the predefined @code{CONVFMT} or
17855 @code{ENVIRON} variables.
17857 Traditional Awk supports only the predefined functions @code{exp}, @code{index},
17858 @code{int}, @code{length}, @code{log}, @code{split}, @code{sprintf},
17859 @code{sqrt}, and @code{substr}.
17861 Traditional Awk @code{getline} is not at all compatible with Posix;
17862 avoid it.
17864 Traditional Awk has @code{for (i in a) @dots{}} but no other uses of the
17865 @code{in} keyword.  For example, it lacks @code{if (i in a) @dots{}}.
17867 In code portable to both traditional and modern Awk, @code{FS} must be a
17868 string containing just one ordinary character, and similarly for the
17869 field-separator argument to @code{split}.
17871 Traditional Awk has a limit of 99 fields in a record.  Since some Awk
17872 implementations, like Tru64's, split the input even if you don't refer
17873 to any field in the script, to circumvent this problem, set @samp{FS}
17874 to an unusual character and use @code{split}.
17876 Traditional Awk has a limit of at most 99 bytes in a number formatted by
17877 @code{OFMT}; for example, @code{OFMT="%.300e"; print 0.1;} typically
17878 dumps core.
17880 The original version of Awk had a limit of at most 99 bytes per
17881 @code{split} field, 99 bytes per @code{substr} substring, and 99 bytes
17882 per run of non-special characters in a @code{printf} format, but these
17883 bugs have been fixed on all practical hosts that we know of.
17885 HP-UX 11.00 and IRIX 6.5 Awk require that input files have a line length
17886 of at most 3070 bytes.
17888 @item @command{basename}
17889 @c ---------------------
17890 @prindex @command{basename}
17891 Not all hosts have a working @command{basename}.
17892 You can use @command{expr} instead.
17894 @c AS_BASENAME is to be replaced by a better API.
17895 @ignore
17896 Not all hosts have a working @command{basename}, and you should instead
17897 use @code{AS_BASENAME} (@pxref{Programming in M4sh}), followed by
17898 @command{expr} if you need to strip a suffix.  For example:
17900 @example
17901 a=`basename "$aname"`       # This is not portable.
17902 a=`AS_BASENAME(["$aname"])` # This is more portable.
17904 # This is not portable.
17905 c=`basename "$cname" .c`
17907 # This is more portable.
17908 c=`AS_BASENAME(["$cname"])`
17909 case $c in
17910 ?*.c) c=`expr "X$c" : 'X\(.*\)\.c'`;;
17911 esac
17912 @end example
17913 @end ignore
17916 @item @command{cat}
17917 @c ----------------
17918 @prindex @command{cat}
17919 Don't rely on any option.
17922 @item @command{cc}
17923 @c ---------------
17924 @prindex @command{cc}
17925 The command @samp{cc -c foo.c} traditionally produces an object file
17926 named @file{foo.o}.  Most compilers allow @option{-c} to be combined
17927 with @option{-o} to specify a different object file name, but
17928 Posix does not require this combination and a few compilers
17929 lack support for it.  @xref{C Compiler}, for how GNU Make
17930 tests for this feature with @code{AC_PROG_CC_C_O}.
17932 When a compilation such as @samp{cc -o foo foo.c} fails, some compilers
17933 (such as CDS on Reliant Unix) leave a @file{foo.o}.
17935 HP-UX @command{cc} doesn't accept @file{.S} files to preprocess and
17936 assemble.  @samp{cc -c foo.S} appears to succeed, but in fact does
17937 nothing.
17939 The default executable, produced by @samp{cc foo.c}, can be
17941 @itemize
17942 @item @file{a.out} --- usual Posix convention.
17943 @item @file{b.out} --- i960 compilers (including @command{gcc}).
17944 @item @file{a.exe} --- DJGPP port of @command{gcc}.
17945 @item @file{a_out.exe} --- GNV @command{cc} wrapper for DEC C on OpenVMS.
17946 @item @file{foo.exe} --- various MS-DOS compilers.
17947 @end itemize
17949 The C compiler's traditional name is @command{cc}, but other names like
17950 @command{gcc} are common.  Posix 1003.1-2001 specifies the
17951 name @command{c99}, but older Posix editions specified
17952 @command{c89} and anyway these standard names are rarely used in
17953 practice.  Typically the C compiler is invoked from makefiles that use
17954 @samp{$(CC)}, so the value of the @samp{CC} make variable selects the
17955 compiler name.
17957 @item @command{chgrp}
17958 @itemx @command{chown}
17959 @c -------------------
17960 @prindex @command{chgrp}
17961 @prindex @command{chown}
17962 It is not portable to change a file's group to a group that the owner
17963 does not belong to.
17965 @item @command{chmod}
17966 @c ------------------
17967 @prindex @command{chmod}
17968 Avoid usages like @samp{chmod -w file}; use @samp{chmod a-w file}
17969 instead, for two reasons.  First, plain @option{-w} does not necessarily
17970 make the file unwritable, since it does not affect mode bits that
17971 correspond to bits in the file mode creation mask.  Second,
17972 Posix says that the @option{-w} might be interpreted as an
17973 implementation-specific option, not as a mode; Posix suggests
17974 using @samp{chmod -- -w file} to avoid this confusion, but unfortunately
17975 @samp{--} does not work on some older hosts.
17978 @item @command{cmp}
17979 @c ----------------
17980 @prindex @command{cmp}
17981 @command{cmp} performs a raw data comparison of two files, while
17982 @command{diff} compares two text files.  Therefore, if you might compare
17983 DOS files, even if only checking whether two files are different, use
17984 @command{diff} to avoid spurious differences due to differences of
17985 newline encoding.
17988 @item @command{cp}
17989 @c ---------------
17990 @prindex @command{cp}
17991 Avoid the @option{-r} option, since Posix 1003.1-2004 marks it as
17992 obsolescent and its behavior on special files is implementation-defined.
17993 Use @option{-R} instead.  On GNU hosts the two options
17994 are equivalent, but on Solaris hosts (for example) @code{cp -r}
17995 reads from pipes instead of replicating them.
17997 Some @command{cp} implementations (e.g., BSD/OS 4.2) do not allow
17998 trailing slashes at the end of nonexistent destination directories.  To
17999 avoid this problem, omit the trailing slashes.  For example, use
18000 @samp{cp -R source /tmp/newdir} rather than @samp{cp -R source
18001 /tmp/newdir/} if @file{/tmp/newdir} does not exist.
18003 @c This is thanks to Ian.
18004 The ancient SunOS 4 @command{cp} does not support @option{-f}, although
18005 its @command{mv} does.
18007 @cindex timestamp resolution
18008 Traditionally, file timestamps had 1-second resolution, and @samp{cp
18009 -p} copied the timestamps exactly.  However, many modern file systems
18010 have timestamps with 1-nanosecond resolution.  Unfortunately, @samp{cp
18011 -p} implementations truncate timestamps when copying files, so this
18012 can result in the destination file appearing to be older than the
18013 source.  The exact amount of truncation depends on the resolution of
18014 the system calls that @command{cp} uses; traditionally this was
18015 @code{utime}, which has 1-second resolution, but some newer
18016 @command{cp} implementations use @code{utimes}, which has
18017 1-microsecond resolution.  These newer implementations include GNU
18018 Core Utilities 5.0.91 or later, and Solaris 8 (sparc) patch 109933-02 or
18019 later.  Unfortunately as of January 2006 there is still no system
18020 call to set timestamps to the full nanosecond resolution.
18022 Bob Proulx notes that @samp{cp -p} always @emph{tries} to copy
18023 ownerships.  But whether it actually does copy ownerships or not is a
18024 system dependent policy decision implemented by the kernel.  If the
18025 kernel allows it then it happens.  If the kernel does not allow it then
18026 it does not happen.  It is not something @command{cp} itself has control
18027 over.
18029 In Unix System V any user can chown files to any other user, and System
18030 V also has a non-sticky @file{/tmp}.  That probably derives from the
18031 heritage of System V in a business environment without hostile users.
18032 BSD changed this
18033 to be a more secure model where only root can @command{chown} files and
18034 a sticky @file{/tmp} is used.  That undoubtedly derives from the heritage
18035 of BSD in a campus environment.
18037 GNU/Linux and Solaris by default follow BSD, but
18038 can be configured to allow a System V style @command{chown}.  On the
18039 other hand, HP-UX follows System V, but can
18040 be configured to use the modern security model and disallow
18041 @command{chown}.  Since it is an administrator-configurable parameter
18042 you can't use the name of the kernel as an indicator of the behavior.
18046 @item @command{date}
18047 @c -----------------
18048 @prindex @command{date}
18049 Some versions of @command{date} do not recognize special @samp{%} directives,
18050 and unfortunately, instead of complaining, they just pass them through,
18051 and exit with success:
18053 @example
18054 $ @kbd{uname -a}
18055 OSF1 medusa.sis.pasteur.fr V5.1 732 alpha
18056 $ @kbd{date "+%s"}
18058 @end example
18061 @item @command{diff}
18062 @c -----------------
18063 @prindex @command{diff}
18064 Option @option{-u} is nonportable.
18066 Some implementations, such as Tru64's, fail when comparing to
18067 @file{/dev/null}.  Use an empty file instead.
18070 @item @command{dirname}
18071 @c --------------------
18072 @prindex @command{dirname}
18073 Not all hosts have a working @command{dirname}, and you should instead
18074 use @code{AS_DIRNAME} (@pxref{Programming in M4sh}).  For example:
18076 @example
18077 dir=`dirname "$file"`       # This is not portable.
18078 dir=`AS_DIRNAME(["$file"])` # This is more portable.
18079 @end example
18082 @item @command{egrep}
18083 @c ------------------
18084 @prindex @command{egrep}
18085 Posix 1003.1-2001 no longer requires @command{egrep},
18086 but many hosts do not yet support the Posix
18087 replacement @code{grep -E}.  Also, some traditional implementations do
18088 not work on long input lines.  To work around these problems, invoke
18089 @code{AC_PROG_EGREP} and then use @code{$EGREP}.
18091 Portable extended regular expressions should use @samp{\} only to escape
18092 characters in the string @samp{$()*+.?[\^@{|}.  For example, @samp{\@}}
18093 is not portable, even though it typically matches @samp{@}}.
18095 The empty alternative is not portable.  Use @samp{?} instead.  For
18096 instance with Digital Unix v5.0:
18098 @example
18099 > printf "foo\n|foo\n" | $EGREP '^(|foo|bar)$'
18100 |foo
18101 > printf "bar\nbar|\n" | $EGREP '^(foo|bar|)$'
18102 bar|
18103 > printf "foo\nfoo|\n|bar\nbar\n" | $EGREP '^(foo||bar)$'
18105 |bar
18106 @end example
18108 @command{$EGREP} also suffers the limitations of @command{grep}
18109 (@pxref{grep, , Limitations of Usual Tools}).
18111 @item @command{expr}
18112 @c -----------------
18113 @prindex @command{expr}
18114 Not all implementations obey the Posix rule that @samp{--} separates
18115 options from arguments; likewise, not all implementations provide the
18116 extension to Posix that the first argument can be treated as part of a
18117 valid expression rather than an invalid option if it begins with
18118 @samp{-}.  When performing arithmetic, use @samp{expr 0 + $var} if
18119 @samp{$var} might be a negative number, to keep @command{expr} from
18120 interpreting it as an option.
18122 No @command{expr} keyword starts with @samp{X}, so use @samp{expr
18123 X"@var{word}" : 'X@var{regex}'} to keep @command{expr} from
18124 misinterpreting @var{word}.
18126 Don't use @code{length}, @code{substr}, @code{match} and @code{index}.
18128 @item @command{expr} (@samp{|})
18129 @prindex @command{expr} (@samp{|})
18130 You can use @samp{|}.  Although Posix does require that @samp{expr
18131 ''} return the empty string, it does not specify the result when you
18132 @samp{|} together the empty string (or zero) with the empty string.  For
18133 example:
18135 @example
18136 expr '' \| ''
18137 @end example
18139 Posix 1003.2-1992 returns the empty string
18140 for this case, but traditional Unix returns @samp{0} (Solaris is
18141 one such example).  In Posix 1003.1-2001, the specification was
18142 changed to match traditional Unix's behavior (which is
18143 bizarre, but it's too late to fix this).  Please note that the same
18144 problem does arise when the empty string results from a computation,
18145 as in:
18147 @example
18148 expr bar : foo \| foo : bar
18149 @end example
18151 @noindent
18152 Avoid this portability problem by avoiding the empty string.
18155 @item @command{expr} (@samp{:})
18156 @c ----------------------------
18157 @prindex @command{expr}
18158 Portable @command{expr} regular expressions should use @samp{\} to
18159 escape only characters in the string @samp{$()*.0123456789[\^n@{@}}.
18160 For example, alternation, @samp{\|}, is common but Posix does not
18161 require its support, so it should be avoided in portable scripts.
18162 Similarly, @samp{\+} and @samp{\?} should be avoided.
18164 Portable @command{expr} regular expressions should not begin with
18165 @samp{^}.  Patterns are automatically anchored so leading @samp{^} is
18166 not needed anyway.
18168 On the other hand, the behavior of the @samp{$} anchor is not portable
18169 on multi-line strings.  Posix is ambiguous whether the anchor applies to
18170 each line, as was done in older versions of GNU Coreutils, or
18171 whether it applies only to the end of the overall string, as in
18172 Coreutils 6.0 and most other implementations.
18174 @example
18175 $ @kbd{baz='foo}
18176 > @kbd{bar'}
18177 $ @kbd{expr "X$baz" : 'X\(foo\)$'}
18179 $ @kbd{expr-5.97 "X$baz" : 'X\(foo\)$'}
18181 @end example
18183 The Posix standard is ambiguous as to whether
18184 @samp{expr 'a' : '\(b\)'} outputs @samp{0} or the empty string.
18185 In practice, it outputs the empty string on most platforms, but portable
18186 scripts should not assume this.  For instance, the QNX 4.25 native
18187 @command{expr} returns @samp{0}.
18189 One might think that a way to get a uniform behavior would be to use
18190 the empty string as a default value:
18192 @example
18193 expr a : '\(b\)' \| ''
18194 @end example
18196 @noindent
18197 Unfortunately this behaves exactly as the original expression; see the
18198 @command{expr} (@samp{|}) entry for more information.
18200 Some ancient @command{expr} implementations (e.g., SunOS 4 @command{expr} and
18201 Solaris 8 @command{/usr/ucb/expr}) have a silly length limit that causes
18202 @command{expr} to fail if the matched substring is longer than 120
18203 bytes.  In this case, you might want to fall back on @samp{echo|sed} if
18204 @command{expr} fails.  Nowadays this is of practical importance only for
18205 the rare installer who mistakenly puts @file{/usr/ucb} before
18206 @file{/usr/bin} in @env{PATH}.
18208 On Mac OS X 10.4, @command{expr} mishandles the pattern @samp{[^-]} in
18209 some cases.  For example, the command
18210 @example
18211 expr Xpowerpc-apple-darwin8.1.0 : 'X[^-]*-[^-]*-\(.*\)'
18212 @end example
18214 @noindent
18215 outputs @samp{apple-darwin8.1.0} rather than the correct @samp{darwin8.1.0}.
18216 This particular case can be worked around by substituting @samp{[^--]}
18217 for @samp{[^-]}.
18219 Don't leave, there is some more!
18221 The QNX 4.25 @command{expr}, in addition of preferring @samp{0} to
18222 the empty string, has a funny behavior in its exit status: it's always 1
18223 when parentheses are used!
18225 @example
18226 $ @kbd{val=`expr 'a' : 'a'`; echo "$?: $val"}
18227 0: 1
18228 $ @kbd{val=`expr 'a' : 'b'`; echo "$?: $val"}
18229 1: 0
18231 $ @kbd{val=`expr 'a' : '\(a\)'`; echo "?: $val"}
18232 1: a
18233 $ @kbd{val=`expr 'a' : '\(b\)'`; echo "?: $val"}
18234 1: 0
18235 @end example
18237 @noindent
18238 In practice this can be a big problem if you are ready to catch failures
18239 of @command{expr} programs with some other method (such as using
18240 @command{sed}), since you may get twice the result.  For instance
18242 @example
18243 $ @kbd{expr 'a' : '\(a\)' || echo 'a' | sed 's/^\(a\)$/\1/'}
18244 @end example
18246 @noindent
18247 outputs @samp{a} on most hosts, but @samp{aa} on QNX 4.25.  A
18248 simple workaround consists of testing @command{expr} and using a variable
18249 set to @command{expr} or to @command{false} according to the result.
18251 Tru64 @command{expr} incorrectly treats the result as a number, if it
18252 can be interpreted that way:
18254 @example
18255 $ @kbd{expr 00001 : '.*\(...\)'}
18257 @end example
18259 On HP-UX 11, @command{expr} only supports a single
18260 sub-expression.
18262 @example
18263 $ @kbd{expr 'Xfoo' : 'X\(f\(oo\)*\)$'}
18264 expr: More than one '\(' was used.
18265 @end example
18268 @item @command{fgrep}
18269 @c ------------------
18270 @prindex @command{fgrep}
18271 Posix 1003.1-2001 no longer requires @command{fgrep},
18272 but many hosts do not yet support the Posix
18273 replacement @code{grep -F}.  Also, some traditional implementations do
18274 not work on long input lines.  To work around these problems, invoke
18275 @code{AC_PROG_FGREP} and then use @code{$FGREP}.
18277 Tru64/OSF 5.1 @command{fgrep} does not match an empty pattern.
18280 @item @command{find}
18281 @c -----------------
18282 @prindex @command{find}
18283 The option @option{-maxdepth} seems to be GNU specific.
18284 Tru64 v5.1, NetBSD 1.5 and Solaris @command{find}
18285 commands do not understand it.
18287 The replacement of @samp{@{@}} is guaranteed only if the argument is
18288 exactly @emph{@{@}}, not if it's only a part of an argument.  For
18289 instance on DU, and HP-UX 10.20 and HP-UX 11:
18291 @example
18292 $ @kbd{touch foo}
18293 $ @kbd{find . -name foo -exec echo "@{@}-@{@}" \;}
18294 @{@}-@{@}
18295 @end example
18297 @noindent
18298 while GNU @command{find} reports @samp{./foo-./foo}.
18301 @anchor{grep}
18302 @item @command{grep}
18303 @c -----------------
18304 @prindex @command{grep}
18305 Portable scripts can rely on the @command{grep} options @option{-c},
18306 @option{-l}, @option{-n}, and @option{-v}, but should avoid other
18307 options.  For example, don't use @option{-w}, as Posix does not require
18308 it and Irix 6.5.16m's @command{grep} does not support it.  Also,
18309 portable scripts should not combine @option{-c} with @option{-l},
18310 as Posix does not allow this.
18312 Some of the options required by Posix are not portable in practice.
18313 Don't use @samp{grep -q} to suppress output, because many @command{grep}
18314 implementations (e.g., Solaris) do not support @option{-q}.
18315 Don't use @samp{grep -s} to suppress output either, because Posix
18316 says @option{-s} does not suppress output, only some error messages;
18317 also, the @option{-s} option of traditional @command{grep} behaved
18318 like @option{-q} does in most modern implementations.  Instead,
18319 redirect the standard output and standard error (in case the file
18320 doesn't exist) of @code{grep} to @file{/dev/null}.  Check the exit
18321 status of @code{grep} to determine whether it found a match.
18323 The QNX4 implementation fails to count lines with @code{grep -c '$'},
18324 but works with @code{grep -c '^'}.  Other alternatives for counting
18325 lines are to use @code{sed -n '$='} or @code{wc -l}.
18327 Some traditional @command{grep} implementations do not work on long
18328 input lines.  On AIX the default @code{grep} silently truncates long
18329 lines on the input before matching.
18331 Also, many implementations do not support multiple regexps
18332 with @option{-e}: they either reject @option{-e} entirely (e.g., Solaris)
18333 or honor only the last pattern (e.g., IRIX 6.5 and NeXT).  To
18334 work around these problems, invoke @code{AC_PROG_GREP} and then use
18335 @code{$GREP}.
18337 Another possible workaround for the multiple @option{-e} problem is to
18338 separate the patterns by newlines, for example:
18340 @example
18341 grep 'foo
18342 bar' in.txt
18343 @end example
18345 @noindent
18346 except that this fails with traditional @command{grep}
18347 implementations and with OpenBSD 3.8 @command{grep}.
18349 Traditional @command{grep} implementations (e.g., Solaris) do not
18350 support the @option{-E} or @option{-F} options.  To work around these
18351 problems, invoke @code{AC_PROG_EGREP} and then use @code{$EGREP}, and
18352 similarly for @code{AC_PROG_FGREP} and @code{$FGREP}.  Even if you are
18353 willing to require support for Posix @command{grep}, your script should
18354 not use both @option{-E} and @option{-F}, since Posix does not allow
18355 this combination.
18357 Portable @command{grep} regular expressions should use @samp{\} only to
18358 escape characters in the string @samp{$()*.0123456789[\^@{@}}.  For example,
18359 alternation, @samp{\|}, is common but Posix does not require its
18360 support in basic regular expressions, so it should be avoided in
18361 portable scripts.  Solaris and HP-UX @command{grep} do not support it.
18362 Similarly, the following escape sequences should also be avoided:
18363 @samp{\<}, @samp{\>}, @samp{\+}, @samp{\?}, @samp{\`}, @samp{\'},
18364 @samp{\B}, @samp{\b}, @samp{\S}, @samp{\s}, @samp{\W}, and @samp{\w}.
18366 Posix does not specify the behavior of @command{grep} on binary files.
18367 An example where this matters is using BSD @command{grep} to
18368 search text that includes embedded ANSI escape sequences for
18369 colored output to terminals (@samp{\033[m} is the sequence to restore
18370 normal output); the behavior depends on whether input is seekable:
18372 @example
18373 $ @kbd{printf 'esc\033[mape\n' > sample}
18374 $ @kbd{grep . sample}
18375 Binary file sample matches
18376 $ @kbd{cat sample | grep .}
18377 escape
18378 @end example
18381 @item @command{join}
18382 @c -----------------
18383 @prindex @command{join}
18384 Solaris 8 @command{join} has bugs when the second operand is standard
18385 input, and when standard input is a pipe.  For example, the following
18386 shell script causes Solaris 8 @command{join} to loop forever:
18388 @example
18389 cat >file <<'EOF'
18390 1 x
18391 2 y
18393 cat file | join file -
18394 @end example
18396 Use @samp{join - file} instead.
18399 @item @command{ln}
18400 @c ---------------
18401 @prindex @command{ln}
18402 @cindex Symbolic links
18403 Don't rely on @command{ln} having a @option{-f} option.  Symbolic links
18404 are not available on old systems; use @samp{$(LN_S)} as a portable substitute.
18406 For versions of the DJGPP before 2.04,
18407 @command{ln} emulates symbolic links
18408 to executables by generating a stub that in turn calls the real
18409 program.  This feature also works with nonexistent files like in the
18410 Posix spec.  So @samp{ln -s file link} generates @file{link.exe},
18411 which attempts to call @file{file.exe} if run.  But this feature only
18412 works for executables, so @samp{cp -p} is used instead for these
18413 systems.  DJGPP versions 2.04 and later have full support
18414 for symbolic links.
18417 @item @command{ls}
18418 @c ---------------
18419 @prindex @command{ls}
18420 @cindex Listing directories
18421 The portable options are @option{-acdilrtu}.  Current practice is for
18422 @option{-l} to output both owner and group, even though ancient versions
18423 of @command{ls} omitted the group.
18425 On ancient hosts, @samp{ls foo} sent the diagnostic @samp{foo not found}
18426 to standard output if @file{foo} did not exist.  Hence a shell command
18427 like @samp{sources=`ls *.c 2>/dev/null`} did not always work, since it
18428 was equivalent to @samp{sources='*.c not found'} in the absence of
18429 @samp{.c} files.  This is no longer a practical problem, since current
18430 @command{ls} implementations send diagnostics to standard error.
18432 The behavior of @command{ls} on a directory that is being concurrently
18433 modified is not always predictable, because of a data race where cached
18434 information returned by @code{readdir} does not match the current
18435 directory state.  In fact, MacOS 10.5 has an intermittent bug where
18436 @code{readdir}, and thus @command{ls}, sometimes lists a file more than
18437 once if other files were added or removed from the directory immediately
18438 prior to the @command{ls} call.  Since @command{ls} already sorts its
18439 output, the duplicate entries can be avoided by piping the results
18440 through @code{uniq}.
18442 @anchor{mkdir}
18443 @item @command{mkdir}
18444 @c ------------------
18445 @prindex @command{mkdir}
18446 @cindex Making directories
18447 No @command{mkdir} option is portable to older systems.  Instead of
18448 @samp{mkdir -p @var{file-name}}, you should use
18449 @code{AS_MKDIR_P(@var{file-name})} (@pxref{Programming in M4sh})
18450 or @code{AC_PROG_MKDIR_P} (@pxref{Particular Programs}).
18452 Combining the @option{-m} and @option{-p} options, as in @samp{mkdir -m
18453 go-w -p @var{dir}}, often leads to trouble.  FreeBSD
18454 @command{mkdir} incorrectly attempts to change the permissions of
18455 @var{dir} even if it already exists.  HP-UX 11.23 and
18456 IRIX 6.5 @command{mkdir} often assign the wrong permissions to
18457 any newly-created parents of @var{dir}.
18459 Posix does not clearly specify whether @samp{mkdir -p foo}
18460 should succeed when @file{foo} is a symbolic link to an already-existing
18461 directory.  The GNU Core Utilities 5.1.0 @command{mkdir}
18462 succeeds, but Solaris @command{mkdir} fails.
18464 Traditional @code{mkdir -p} implementations suffer from race conditions.
18465 For example, if you invoke @code{mkdir -p a/b} and @code{mkdir -p a/c}
18466 at the same time, both processes might detect that @file{a} is missing,
18467 one might create @file{a}, then the other might try to create @file{a}
18468 and fail with a @code{File exists} diagnostic.  The GNU Core
18469 Utilities (@samp{fileutils} version 4.1), FreeBSD 5.0,
18470 NetBSD 2.0.2, and OpenBSD 2.4 are known to be
18471 race-free when two processes invoke @code{mkdir -p} simultaneously, but
18472 earlier versions are vulnerable.  Solaris @command{mkdir} is still
18473 vulnerable as of Solaris 10, and other traditional Unix systems are
18474 probably vulnerable too.  This possible race is harmful in parallel
18475 builds when several Make rules call @code{mkdir -p} to
18476 construct directories.  You may use
18477 @code{install-sh -d} as a safe replacement, provided this script is
18478 recent enough; the copy shipped with Autoconf 2.60 and Automake 1.10 is
18479 OK, but copies from older versions are vulnerable.
18482 @item @command{mkfifo}
18483 @itemx @command{mknod}
18484 @c -------------------
18485 @prindex @command{mkfifo}
18486 @prindex @command{mknod}
18487 The GNU Coding Standards state that @command{mknod} is safe to use on
18488 platforms where it has been tested to exist; but it is generally portable
18489 only for creating named FIFOs, since device numbers are
18490 platform-specific.  Autotest uses @command{mkfifo} to implement parallel
18491 testsuites.  Posix states that behavior is unspecified when opening a
18492 named FIFO for both reading and writing; on at least Cygwin, this
18493 results in failure on any attempt to read or write to that file
18494 descriptor.
18496 @item @command{mktemp}
18497 @c -------------------
18498 @prindex @command{mktemp}
18499 @cindex Creating temporary files
18500 Shell scripts can use temporary files safely with @command{mktemp}, but
18501 it does not exist on all systems.  A portable way to create a safe
18502 temporary file name is to create a temporary directory with mode 700 and
18503 use a file inside this directory.  Both methods prevent attackers from
18504 gaining control, though @command{mktemp} is far less likely to fail
18505 gratuitously under attack.
18507 Here is sample code to create a new temporary directory @samp{$dir} safely:
18509 @example
18510 # Create a temporary directory $dir in $TMPDIR (default /tmp).
18511 # Use mktemp if possible; otherwise fall back on mkdir,
18512 # with $RANDOM to make collisions less likely.
18513 : "$@{TMPDIR:=/tmp@}"
18515   dir=`
18516     (umask 077 && mktemp -d "$TMPDIR/fooXXXXXX") 2>/dev/null
18517   ` &&
18518   test -d "$dir"
18519 @} || @{
18520   dir=$TMPDIR/foo$$-$RANDOM
18521 @c $$ restore font-lock
18522   (umask 077 && mkdir "$dir")
18523 @} || exit $?
18524 @end example
18527 @item @command{mv}
18528 @c ---------------
18529 @prindex @command{mv}
18530 @cindex Moving open files
18531 The only portable options are @option{-f} and @option{-i}.
18533 Moving individual files between file systems is portable (it was in Unix
18534 version 6),
18535 but it is not always atomic: when doing @samp{mv new existing}, there's
18536 a critical section where neither the old nor the new version of
18537 @file{existing} actually exists.
18539 On some systems moving files from @file{/tmp} can sometimes cause
18540 undesirable (but perfectly valid) warnings, even if you created these
18541 files.  This is because @file{/tmp} belongs to a group that ordinary
18542 users are not members of, and files created in @file{/tmp} inherit
18543 the group of @file{/tmp}.  When the file is copied, @command{mv} issues
18544 a diagnostic without failing:
18546 @smallexample
18547 $ @kbd{touch /tmp/foo}
18548 $ @kbd{mv /tmp/foo .}
18549 @error{}mv: ./foo: set owner/group (was: 100/0): Operation not permitted
18550 $ @kbd{echo $?}
18552 $ @kbd{ls foo}
18554 @end smallexample
18556 @noindent
18557 This annoying behavior conforms to Posix, unfortunately.
18559 Moving directories across mount points is not portable, use @command{cp}
18560 and @command{rm}.
18562 DOS variants cannot rename or remove open files, and do not
18563 support commands like @samp{mv foo bar >foo}, even though this is
18564 perfectly portable among Posix hosts.
18567 @item @command{od}
18568 @c ---------------
18569 @prindex @command{od}
18571 In Mac OS X 10.3, @command{od} does not support the
18572 standard Posix options @option{-A}, @option{-j}, @option{-N}, or
18573 @option{-t}, or the XSI option @option{-s}.  The only
18574 supported Posix option is @option{-v}, and the only supported
18575 XSI options are those in @option{-bcdox}.  The BSD
18576 @command{hexdump} program can be used instead.
18578 This problem no longer exists in Mac OS X 10.4.3.
18581 @item @command{rm}
18582 @c ---------------
18583 @prindex @command{rm}
18584 The @option{-f} and @option{-r} options are portable.
18586 It is not portable to invoke @command{rm} without operands.  For
18587 example, on many systems @samp{rm -f -r} (with no other arguments)
18588 silently succeeds without doing anything, but it fails with a diagnostic
18589 on NetBSD 2.0.2.
18591 A file might not be removed even if its parent directory is writable
18592 and searchable.  Many Posix hosts cannot remove a mount point, a named
18593 stream, a working directory, or a last link to a file that is being
18594 executed.
18596 DOS variants cannot rename or remove open files, and do not
18597 support commands like @samp{rm foo >foo}, even though this is
18598 perfectly portable among Posix hosts.
18600 @item @command{rmdir}
18601 @c ------------------
18602 @prindex @command{rmdir}
18603 Just as with @command{rm}, some platforms refuse to remove a working
18604 directory.
18606 @anchor{sed}
18607 @item @command{sed}
18608 @c ----------------
18609 @prindex @command{sed}
18610 Patterns should not include the separator (unless escaped), even as part
18611 of a character class.  In conformance with Posix, the Cray
18612 @command{sed} rejects @samp{s/[^/]*$//}: use @samp{s%[^/]*$%%}.
18613 Even when escaped, patterns should not include separators that are also
18614 used as @command{sed} metacharacters.  For example, GNU sed 4.0.9 rejects
18615 @samp{s,x\@{1\,\@},,}, while sed 4.1 strips the backslash before the comma
18616 before evaluating the basic regular expression.
18618 Avoid empty patterns within parentheses (i.e., @samp{\(\)}).  Posix does
18619 not require support for empty patterns, and Unicos 9 @command{sed} rejects
18620 them.
18622 Unicos 9 @command{sed} loops endlessly on patterns like @samp{.*\n.*}.
18624 Sed scripts should not use branch labels longer than 7 characters and
18625 should not contain comments; AIX 5.3 @command{sed} rejects indented comments.
18626 HP-UX sed has a limit of 99 commands (not counting @samp{:} commands) and
18627 48 labels, which can not be circumvented by using more than one script
18628 file.  It can execute up to 19 reads with the @samp{r} command per cycle.
18629 Solaris @command{/usr/ucb/sed} rejects usages that exceed a limit of
18630 about 6000 bytes for the internal representation of commands.
18632 Avoid redundant @samp{;}, as some @command{sed} implementations, such as
18633 NetBSD 1.4.2's, incorrectly try to interpret the second
18634 @samp{;} as a command:
18636 @example
18637 $ @kbd{echo a | sed 's/x/x/;;s/x/x/'}
18638 sed: 1: "s/x/x/;;s/x/x/": invalid command code ;
18639 @end example
18641 Input should not have unreasonably long lines, since some @command{sed}
18642 implementations have an input buffer limited to 4000 bytes.  Likewise,
18643 not all @command{sed} implementations can handle embedded @code{NUL} or
18644 a missing trailing newline.
18646 Portable @command{sed} regular expressions should use @samp{\} only to escape
18647 characters in the string @samp{$()*.0123456789[\^n@{@}}.  For example,
18648 alternation, @samp{\|}, is common but Posix does not require its
18649 support, so it should be avoided in portable scripts.  Solaris
18650 @command{sed} does not support alternation; e.g., @samp{sed '/a\|b/d'}
18651 deletes only lines that contain the literal string @samp{a|b}.
18652 Similarly, @samp{\+} and @samp{\?} should be avoided.
18654 Anchors (@samp{^} and @samp{$}) inside groups are not portable.
18656 Nested parentheses in patterns (e.g., @samp{\(\(a*\)b*)\)}) are
18657 quite portable to current hosts, but was not supported by some ancient
18658 @command{sed} implementations like SVR3.
18660 Some @command{sed} implementations, e.g., Solaris, restrict the special
18661 role of the asterisk @samp{*} to one-character regular expressions and
18662 back-references, and the special role of interval expressions
18663 @samp{\@{@var{m}\@}}, @samp{\@{@var{m},\@}}, or @samp{\@{@var{m},@var{n}\@}}
18664 to one-character regular expressions.  This may lead to unexpected behavior:
18666 @example
18667 $ @kbd{echo '1*23*4' | /usr/bin/sed 's/\(.\)*/x/g'}
18668 x2x4
18669 $ @kbd{echo '1*23*4' | /usr/xpg4/bin/sed 's/\(.\)*/x/g'}
18671 @end example
18673 The @option{-e} option is mostly portable.
18674 However, its argument
18675 cannot start with @samp{a}, @samp{c}, or @samp{i},
18676 as this runs afoul of a Tru64 5.1 bug.
18677 Also, its argument cannot be empty, as this fails on AIX 5.3.
18678 Some people prefer to use @samp{-e}:
18680 @example
18681 sed -e '@var{command-1}' \
18682     -e '@var{command-2}'
18683 @end example
18685 @noindent
18686 as opposed to the equivalent:
18688 @example
18689 sed '
18690   @var{command-1}
18691   @var{command-2}
18693 @end example
18695 @noindent
18696 The following usage is sometimes equivalent:
18698 @example
18699 sed '@var{command-1};@var{command-2}'
18700 @end example
18702 but Posix says that this use of a semicolon has undefined effect if
18703 @var{command-1}'s verb is @samp{@{}, @samp{a}, @samp{b}, @samp{c},
18704 @samp{i}, @samp{r}, @samp{t}, @samp{w}, @samp{:}, or @samp{#}, so you
18705 should use semicolon only with simple scripts that do not use these
18706 verbs.
18708 Posix up to the 2008 revision requires the argument of the @option{-e}
18709 option to be a syntactically complete script.  GNU @command{sed} allows
18710 to pass multiple script fragments, each as argument of a separate
18711 @option{-e} option, that are then combined, with newlines between the
18712 fragments, and a future Posix revision may allow this as well.  This
18713 approach is not portable with script fragments ending in backslash; for
18714 example, the @command{sed} programs on Solaris 10, HP-UX 11, and AIX
18715 don't allow splitting in this case:
18717 @example
18718 $ @kbd{echo a | sed -n -e 'i\}
18719 @kbd{0'}
18721 $ @kbd{echo a | sed -n -e 'i\' -e 0}
18722 Unrecognized command: 0
18723 @end example
18725 @noindent
18726 In practice, however, this technique of joining fragments
18727 through @option{-e} works for multiple @command{sed} functions within
18728 @samp{@{} and @samp{@}}, even if that is not specified by Posix:
18730 @example
18731 @c The quote around the closing brace silences interactive zsh.
18732 $ @kbd{echo a | sed -n -e '/a/@{' -e s/a/b/ -e p -e '@}'}
18734 @end example
18736 Commands inside @{ @} brackets are further restricted.  Posix 2008 says that
18737 they cannot be preceded by addresses, @samp{!}, or @samp{;}, and that
18738 each command must be followed immediately by a newline, without any
18739 intervening blanks or semicolons.  The closing bracket must be alone on
18740 a line, other than white space preceding or following it.  However, a
18741 future version of Posix may standardize the use of addresses within brackets.
18743 Contrary to yet another urban legend, you may portably use @samp{&} in
18744 the replacement part of the @code{s} command to mean ``what was
18745 matched''.  All descendants of Unix version 7 @command{sed}
18746 (at least; we
18747 don't have first hand experience with older @command{sed} implementations) have
18748 supported it.
18750 Posix requires that you must not have any white space between
18751 @samp{!} and the following command.  It is OK to have blanks between
18752 the address and the @samp{!}.  For instance, on Solaris:
18754 @example
18755 $ @kbd{echo "foo" | sed -n '/bar/ ! p'}
18756 @error{}Unrecognized command: /bar/ ! p
18757 $ @kbd{echo "foo" | sed -n '/bar/! p'}
18758 @error{}Unrecognized command: /bar/! p
18759 $ @kbd{echo "foo" | sed -n '/bar/ !p'}
18761 @end example
18763 Posix also says that you should not combine @samp{!} and @samp{;}.  If
18764 you use @samp{!}, it is best to put it on a command that is delimited by
18765 newlines rather than @samp{;}.
18767 Also note that Posix requires that the @samp{b}, @samp{t}, @samp{r}, and
18768 @samp{w} commands be followed by exactly one space before their argument.
18769 On the other hand, no white space is allowed between @samp{:} and the
18770 subsequent label name.
18772 If a sed script is specified on the command line and ends in an
18773 @samp{a}, @samp{c}, or @samp{i} command, the last line of inserted text
18774 should be followed by a newline.  Otherwise some @command{sed}
18775 implementations (e.g., OpenBSD 3.9) do not append a newline to the
18776 inserted text.
18778 Many @command{sed} implementations (e.g., MacOS X 10.4,
18779 OpenBSD 3.9, Solaris 10
18780 @command{/usr/ucb/sed}) strip leading white space from the text of
18781 @samp{a}, @samp{c}, and @samp{i} commands.  Prepend a backslash to
18782 work around this incompatibility with Posix:
18784 @example
18785 $ @kbd{echo flushleft | sed 'a\}
18786 > @kbd{   indented}
18787 > @kbd{'}
18788 flushleft
18789 indented
18790 $ @kbd{echo foo | sed 'a\}
18791 > @kbd{\   indented}
18792 > @kbd{'}
18793 flushleft
18794    indented
18795 @end example
18797 Posix requires that with an empty regular expression, the last non-empty
18798 regular expression from either an address specification or substitution
18799 command is applied.  However, busybox 1.6.1 complains when using a
18800 substitution command with a replacement containing a back-reference to
18801 an empty regular expression; the workaround is repeating the regular
18802 expression.
18804 @example
18805 $ @kbd{echo abc | busybox sed '/a\(b\)c/ s//\1/'}
18806 sed: No previous regexp.
18807 $ @kbd{echo abc | busybox sed '/a\(b\)c/ s/a\(b\)c/\1/'}
18809 @end example
18812 @item @command{sed} (@samp{t})
18813 @c ---------------------------
18814 @prindex @command{sed} (@samp{t})
18815 Some old systems have @command{sed} that ``forget'' to reset their
18816 @samp{t} flag when starting a new cycle.  For instance on MIPS
18817 RISC/OS, and on IRIX 5.3, if you run the following @command{sed}
18818 script (the line numbers are not actual part of the texts):
18820 @example
18821 s/keep me/kept/g  # a
18822 t end             # b
18823 s/.*/deleted/g    # c
18824 :end              # d
18825 @end example
18827 @noindent
18830 @example
18831 delete me         # 1
18832 delete me         # 2
18833 keep me           # 3
18834 delete me         # 4
18835 @end example
18837 @noindent
18838 you get
18840 @example
18841 deleted
18842 delete me
18843 kept
18844 deleted
18845 @end example
18847 @noindent
18848 instead of
18850 @example
18851 deleted
18852 deleted
18853 kept
18854 deleted
18855 @end example
18857 Why?  When processing line 1, (c) matches, therefore sets the @samp{t}
18858 flag, and the output is produced.  When processing
18859 line 2, the @samp{t} flag is still set (this is the bug).  Command (a)
18860 fails to match, but @command{sed} is not supposed to clear the @samp{t}
18861 flag when a substitution fails.  Command (b) sees that the flag is set,
18862 therefore it clears it, and jumps to (d), hence you get @samp{delete me}
18863 instead of @samp{deleted}.  When processing line (3), @samp{t} is clear,
18864 (a) matches, so the flag is set, hence (b) clears the flags and jumps.
18865 Finally, since the flag is clear, line 4 is processed properly.
18867 There are two things one should remember about @samp{t} in @command{sed}.
18868 Firstly, always remember that @samp{t} jumps if @emph{some} substitution
18869 succeeded, not only the immediately preceding substitution.  Therefore,
18870 always use a fake @samp{t clear} followed by a @samp{:clear} on the next
18871 line, to reset the @samp{t} flag where needed.
18873 Secondly, you cannot rely on @command{sed} to clear the flag at each new
18874 cycle.
18876 One portable implementation of the script above is:
18878 @example
18879 t clear
18880 :clear
18881 s/keep me/kept/g
18882 t end
18883 s/.*/deleted/g
18884 :end
18885 @end example
18887 @item @command{sleep}
18888 @c ------------------
18889 @prindex @command{sleep}
18890 Using @command{sleep} is generally portable.  However, remember that
18891 adding a @command{sleep} to work around timestamp issues, with a minimum
18892 granularity of one second, doesn't scale well for parallel builds on
18893 modern machines with sub-second process completion.
18895 @item @command{sort}
18896 @c -----------------
18897 @prindex @command{sort}
18898 Remember that sort order is influenced by the current locale.  Inside
18899 @file{configure}, the C locale is in effect, but in Makefile snippets,
18900 you may need to specify @code{LC_ALL=C sort}.
18902 @item @command{tar}
18903 @c ----------------
18904 @prindex @command{tar}
18905 There are multiple file formats for @command{tar}; if you use Automake,
18906 the macro @code{AM_INIT_AUTOMAKE} has some options controlling which
18907 level of portability to use.
18909 @anchor{touch}
18910 @item @command{touch}
18911 @c ------------------
18912 @prindex @command{touch}
18913 @cindex timestamp resolution
18914 If you specify the desired timestamp (e.g., with the @option{-r}
18915 option), @command{touch} typically uses the @code{utime} or
18916 @code{utimes} system call, which can result in the same kind of
18917 timestamp truncation problems that @samp{cp -p} has.
18919 On ancient BSD systems, @command{touch} or any command that
18920 results in an empty file does not update the timestamps, so use a
18921 command like @command{echo} as a workaround.
18922 Also,
18923 GNU @command{touch} 3.16r (and presumably all before that)
18924 fails to work on SunOS 4.1.3 when the empty file is on an
18925 NFS-mounted 4.2 volume.
18926 However, these problems are no longer of practical concern.
18928 @item @command{tr}
18929 @c ---------------
18930 @prindex @command{tr}
18931 @cindex carriage return, deleting
18932 @cindex newline, deleting
18933 @cindex deleting carriage return
18934 Not all versions of @command{tr} handle all backslash character escapes.
18935 For example, Solaris 10 @command{/usr/ucb/tr} falls over, even though
18936 Solaris contains more modern @command{tr} in other locations.
18937 Using octal escapes is more portable for carriage returns, since
18938 @samp{\015} is the same for both ASCII and EBCDIC, and since use of
18939 literal carriage returns in scripts causes a number of other problems.
18940 But for other characters, like newline, using octal escapes ties the
18941 operation to ASCII, so it is better to use literal characters.
18943 @example
18944 $ @kbd{@{ echo moon; echo light; @} | /usr/ucb/tr -d '\n' ; echo}
18946 light
18947 $ @kbd{@{ echo moon; echo light; @} | /usr/bin/tr -d '\n' ; echo}
18948 moonlight
18949 $ @kbd{@{ echo moon; echo light; @} | /usr/ucb/tr -d '\012' ; echo}
18950 moonlight
18951 $ @kbd{nl='}
18952 @kbd{'; @{ echo moon; echo light; @} | /usr/ucb/tr -d "$nl" ; echo}
18953 moonlight
18954 @end example
18956 Not all versions of @command{tr} recognize ranges of characters: at
18957 least Solaris @command{/usr/bin/tr} still fails to do so.  But you can
18958 use @command{/usr/xpg4/bin/tr} instead.
18960 @example
18961 $ @kbd{echo "Hazy Fantazy" | LC_ALL=C /usr/bin/tr a-z A-Z}
18962 HAZy FAntAZy
18963 $ @kbd{echo "Hazy Fantazy" | LC_ALL=C /usr/xpg4/bin/tr a-z A-Z}
18964 HAZY FANTAZY
18965 @end example
18967 When providing two arguments, be sure the second string is at least as
18968 long as the first.
18970 @example
18971 $ @kbd{echo abc | /usr/xpg4/bin/tr bc d}
18973 $ @kbd{echo abc | coreutils/tr bc d}
18975 @end example
18977 Posix requires @command{tr} to operate on binary files.  But at least
18978 Solaris @command{/usr/ucb/tr} and @command{/usr/bin/tr} silently discard
18979 @code{NUL} in the input prior to doing any translation.  When using
18980 @command{tr} to process a binary file that may contain @code{NUL} bytes,
18981 it is necessary to use @command{/usr/xpg4/bin/tr} instead, or
18982 @command{/usr/xpg6/bin/tr} if that is available.
18984 @example
18985 $ @kbd{printf 'a\0b' | /usr/ucb/tr x x | od -An -tx1}
18986  61 62
18987 $ @kbd{printf 'a\0b' | /usr/bin/tr x x | od -An -tx1}
18988  61 62
18989 $ @kbd{printf 'a\0b' | /usr/xpg4/bin/tr x x | od -An -tx1}
18990  61 00 62
18991 @end example
18993 Solaris @command{/usr/ucb/tr} additionally fails to handle @samp{\0} as the
18994 octal escape for @code{NUL}.
18996 @example
18997 $ @kbd{printf 'abc' | /usr/ucb/tr 'bc' '\0d' | od -An -tx1}
18998  61 62 63
18999 $ @kbd{printf 'abc' | /usr/bin/tr 'bc' '\0d' | od -An -tx1}
19000  61 00 64
19001 $ @kbd{printf 'abc' | /usr/xpg4/bin/tr 'bc' '\0d' | od -An -tx1}
19002  61 00 64
19003 @end example
19005 @end table
19008 @node Portable Make
19009 @chapter Portable Make Programming
19010 @prindex @command{make}
19011 @cindex Limitations of @command{make}
19013 Writing portable makefiles is an art.  Since a makefile's commands are
19014 executed by the shell, you must consider the shell portability issues
19015 already mentioned.  However, other issues are specific to @command{make}
19016 itself.
19018 @menu
19019 * $< in Ordinary Make Rules::   $< in ordinary rules
19020 * Failure in Make Rules::       Failing portably in rules
19021 * Special Chars in Names::      Special Characters in Macro Names
19022 * Backslash-Newline-Newline::   Empty last lines in macro definitions
19023 * Backslash-Newline Comments::  Spanning comments across line boundaries
19024 * Long Lines in Makefiles::     Line length limitations
19025 * Macros and Submakes::         @code{make macro=value} and submakes
19026 * The Make Macro MAKEFLAGS::    @code{$(MAKEFLAGS)} portability issues
19027 * The Make Macro SHELL::        @code{$(SHELL)} portability issues
19028 * Parallel Make::               Parallel @command{make} quirks
19029 * Comments in Make Rules::      Other problems with Make comments
19030 * Newlines in Make Rules::      Using literal newlines in rules
19031 * obj/ and Make::               Don't name a subdirectory @file{obj}
19032 * make -k Status::              Exit status of @samp{make -k}
19033 * VPATH and Make::              @code{VPATH} woes
19034 * Single Suffix Rules::         Single suffix rules and separated dependencies
19035 * Timestamps and Make::         Subsecond timestamp resolution
19036 @end menu
19038 @node $< in Ordinary Make Rules
19039 @section @code{$<} in Ordinary Make Rules
19041 Posix says that the @samp{$<} construct in makefiles can be
19042 used only in inference rules and in the @samp{.DEFAULT} rule; its
19043 meaning in ordinary rules is unspecified.  Solaris @command{make}
19044 for instance replaces it with the empty string.  OpenBSD (3.0 and
19045 later) @command{make} diagnoses these uses and errors out.
19047 @node Failure in Make Rules
19048 @section Failure in Make Rules
19050 Posix 2008 requires that @command{make} must invoke each command with
19051 the equivalent of a @samp{sh -e -c} subshell, which causes the
19052 subshell to exit immediately if a subsidiary simple-command fails,
19053 although not all @command{make} implementations have historically
19054 followed this rule.  For
19055 example, the command @samp{touch T; rm -f U} may attempt to
19056 remove @file{U} even if the @command{touch} fails, although this is not
19057 permitted with Posix make.  One way to work around failures in simple
19058 commands is to reword them so that they always succeed, e.g., @samp{touch
19059 T || :; rm -f U}.
19060 However, even this approach can run into common bugs in BSD
19061 implementations of the @option{-e} option of @command{sh} and
19062 @command{set} (@pxref{set, , Limitations of Shell Builtins}), so if you
19063 are worried
19064 about porting to buggy BSD shells it may be simpler to migrate
19065 complicated @command{make} actions into separate scripts.
19067 @node Special Chars in Names
19068 @section Special Characters in Make Macro Names
19070 Posix limits macro names to nonempty strings containing only
19071 ASCII letters and digits, @samp{.}, and @samp{_}.  Many
19072 @command{make} implementations allow a wider variety of characters, but
19073 portable makefiles should avoid them.  It is portable to start a name
19074 with a special character, e.g., @samp{$(.FOO)}.
19076 Some ancient @command{make} implementations don't support leading
19077 underscores in macro names.  An example is NEWS-OS 4.2R.
19079 @example
19080 $ @kbd{cat Makefile}
19081 _am_include = #
19082 _am_quote =
19083 all:; @@echo this is test
19084 $ @kbd{make}
19085 Make: Must be a separator on rules line 2.  Stop.
19086 $ @kbd{cat Makefile2}
19087 am_include = #
19088 am_quote =
19089 all:; @@echo this is test
19090 $ @kbd{make -f Makefile2}
19091 this is test
19092 @end example
19094 @noindent
19095 However, this problem is no longer of practical concern.
19097 @node Backslash-Newline-Newline
19098 @section Backslash-Newline-Newline in Make Macro Values
19100 @c  This has been seen on ia64 hpux 11.20, and on one hppa hpux 10.20,
19101 @c  but another hppa hpux 10.20 didn't have it.  Bob Proulx
19102 @c  <bob@proulx.com> thinks it was in hpux 8.0 too.
19103 On some versions of HP-UX, @command{make} reads multiple newlines
19104 following a backslash, continuing to the next non-empty line.  For
19105 example,
19107 @example
19108 FOO = one \
19110 BAR = two
19112 test:
19113         : FOO is "$(FOO)"
19114         : BAR is "$(BAR)"
19115 @end example
19117 @noindent
19118 shows @code{FOO} equal to @code{one BAR = two}.  Other implementations
19119 sensibly let a backslash continue only to the immediately following
19120 line.
19122 @node Backslash-Newline Comments
19123 @section Backslash-Newline in Make Comments
19125 According to Posix, Make comments start with @code{#}
19126 and continue until an unescaped newline is reached.
19128 @example
19129 $ @kbd{cat Makefile}
19130 # A = foo \
19131       bar \
19132       baz
19134 all:
19135         @@echo ok
19136 $ @kbd{make}   # GNU make
19138 @end example
19140 @noindent
19141 However this is not always the case.  Some implementations
19142 discard everything from @code{#} through the end of the line, ignoring any
19143 trailing backslash.
19145 @example
19146 $ @kbd{pmake}  # BSD make
19147 "Makefile", line 3: Need an operator
19148 Fatal errors encountered -- cannot continue
19149 @end example
19151 @noindent
19152 Therefore, if you want to comment out a multi-line definition, prefix each
19153 line with @code{#}, not only the first.
19155 @example
19156 # A = foo \
19157 #     bar \
19158 #     baz
19159 @end example
19161 @node Long Lines in Makefiles
19162 @section Long Lines in Makefiles
19164 Tru64 5.1's @command{make} has been reported to crash when given a
19165 makefile with lines longer than around 20 kB.  Earlier versions are
19166 reported to exit with @code{Line too long} diagnostics.
19168 @node Macros and Submakes
19169 @section @code{make macro=value} and Submakes
19171 A command-line variable definition such as @code{foo=bar} overrides any
19172 definition of @code{foo} in a makefile.  Some @command{make}
19173 implementations (such as GNU @command{make}) propagate this
19174 override to subsidiary invocations of @command{make}.  Some other
19175 implementations do not pass the substitution along to submakes.
19177 @example
19178 $ @kbd{cat Makefile}
19179 foo = foo
19180 one:
19181         @@echo $(foo)
19182         $(MAKE) two
19183 two:
19184         @@echo $(foo)
19185 $ @kbd{make foo=bar}            # GNU make 3.79.1
19187 make two
19188 make[1]: Entering directory `/home/adl'
19190 make[1]: Leaving directory `/home/adl'
19191 $ @kbd{pmake foo=bar}           # BSD make
19193 pmake two
19195 @end example
19197 You have a few possibilities if you do want the @code{foo=bar} override
19198 to propagate to submakes.  One is to use the @option{-e}
19199 option, which causes all environment variables to have precedence over
19200 the makefile macro definitions, and declare foo as an environment
19201 variable:
19203 @example
19204 $ @kbd{env foo=bar make -e}
19205 @end example
19207 The @option{-e} option is propagated to submakes automatically,
19208 and since the environment is inherited between @command{make}
19209 invocations, the @code{foo} macro is overridden in
19210 submakes as expected.
19212 This syntax (@code{foo=bar make -e}) is portable only when used
19213 outside of a makefile, for instance from a script or from the
19214 command line.  When run inside a @command{make} rule, GNU
19215 @command{make} 3.80 and prior versions forget to propagate the
19216 @option{-e} option to submakes.
19218 Moreover, using @option{-e} could have unexpected side effects if your
19219 environment contains some other macros usually defined by the
19220 makefile.  (See also the note about @code{make -e} and @code{SHELL}
19221 below.)
19223 If you can foresee all macros that a user might want to override, then
19224 you can propagate them to submakes manually, from your makefile:
19226 @example
19227 foo = foo
19228 one:
19229         @@echo $(foo)
19230         $(MAKE) foo=$(foo) two
19231 two:
19232         @@echo $(foo)
19233 @end example
19235 Another way to propagate a variable to submakes in a portable way is to
19236 expand an extra variable in every invocation of @samp{$(MAKE)} within
19237 your makefile:
19239 @example
19240 foo = foo
19241 one:
19242         @@echo $(foo)
19243         $(MAKE) $(SUBMAKEFLAGS) two
19244 two:
19245         @@echo $(foo)
19246 @end example
19248 Users must be aware that this technique is in use to take advantage of
19249 it, e.g.@: with @code{make foo=bar SUBMAKEFLAGS='foo=bar'}, but it
19250 allows any macro to be overridden.  Makefiles generated by
19251 @command{automake} use this technique, expanding @code{$(AM_MAKEFLAGS)}
19252 on the command lines of submakes (@pxref{Subdirectories, , Automake,
19253 automake, GNU Automake}).
19255 @node The Make Macro MAKEFLAGS
19256 @section The Make Macro MAKEFLAGS
19257 @cindex @code{MAKEFLAGS} and @command{make}
19258 @cindex @command{make} and @code{MAKEFLAGS}
19260 Posix requires @command{make} to use @code{MAKEFLAGS} to affect the
19261 current and recursive invocations of make, but allows implementations
19262 several formats for the variable.  It is tricky to parse
19263 @code{$MAKEFLAGS} to determine whether @option{-s} for silent execution
19264 or @option{-k} for continued execution are in effect.  For example, you
19265 cannot assume that the first space-separated word in @code{$MAKEFLAGS}
19266 contains single-letter options, since in the Cygwin version of
19267 GNU @command{make} it is either @option{--unix} or
19268 @option{--win32} with the second word containing single-letter options.
19270 @example
19271 $ @kbd{cat Makefile}
19272 all:
19273         @@echo MAKEFLAGS = $(MAKEFLAGS)
19274 $ @kbd{make}
19275 MAKEFLAGS = --unix
19276 $ @kbd{make -k}
19277 MAKEFLAGS = --unix -k
19278 @end example
19280 @node The Make Macro SHELL
19281 @section The Make Macro @code{SHELL}
19282 @cindex @code{SHELL} and @command{make}
19283 @cindex @command{make} and @code{SHELL}
19285 Posix-compliant @command{make} internally uses the @code{$(SHELL)}
19286 macro to spawn shell processes and execute Make rules.  This
19287 is a builtin macro supplied by @command{make}, but it can be modified
19288 by a makefile or by a command-line argument.
19290 Not all @command{make} implementations define this @code{SHELL} macro.
19291 Tru64
19292 @command{make} is an example; this implementation always uses
19293 @code{/bin/sh}.  So it's a good idea to always define @code{SHELL} in
19294 your makefiles.  If you use Autoconf, do
19296 @example
19297 SHELL = @@SHELL@@
19298 @end example
19300 @noindent
19301 If you use Automake, this is done for you.
19303 Do not force @code{SHELL = /bin/sh} because that is not correct
19304 everywhere.  Remember, @file{/bin/sh} is not Posix compliant on many
19305 systems, such as FreeBSD 4, NetBSD 3, AIX 3, Solaris 10, or Tru64.
19306 Additionally, DJGPP lacks @code{/bin/sh}, and when its
19307 GNU @command{make} port sees such a setting it enters a
19308 special emulation mode where features like pipes and redirections are
19309 emulated on top of DOS's @command{command.com}.  Unfortunately this
19310 emulation is incomplete; for instance it does not handle command
19311 substitutions.  Using @code{@@SHELL@@} means that your makefile will
19312 benefit from the same improved shell, such as @command{bash} or
19313 @command{ksh}, that was discovered during @command{configure}, so that
19314 you aren't fighting two different sets of shell bugs between the two
19315 contexts.
19317 Posix-compliant @command{make} should never acquire the value of
19318 $(SHELL) from the environment, even when @code{make -e} is used
19319 (otherwise, think about what would happen to your rules if
19320 @code{SHELL=/bin/tcsh}).
19322 However not all @command{make} implementations have this exception.
19323 For instance it's not surprising that Tru64 @command{make} doesn't
19324 protect @code{SHELL}, since it doesn't use it.
19326 @example
19327 $ @kbd{cat Makefile}
19328 SHELL = /bin/sh
19329 FOO = foo
19330 all:
19331         @@echo $(SHELL)
19332         @@echo $(FOO)
19333 $ @kbd{env SHELL=/bin/tcsh FOO=bar make -e}   # Tru64 Make
19334 /bin/tcsh
19336 $ @kbd{env SHELL=/bin/tcsh FOO=bar gmake -e}  # GNU make
19337 /bin/sh
19339 @end example
19341 Conversely, @command{make} is not supposed to export any changes to the
19342 macro @code{SHELL} to child processes.  Again, many implementations
19343 break this rule:
19345 @example
19346 $ @kbd{cat Makefile}
19347 all:
19348         @@echo $(SHELL)
19349         @@printenv SHELL
19350 $ @kbd{env SHELL=sh make -e SHELL=/bin/ksh}   # BSD Make, GNU make 3.80
19351 /bin/ksh
19352 /bin/ksh
19353 $ @kbd{env SHELL=sh gmake -e SHELL=/bin/ksh}  # GNU make 3.81
19354 /bin/ksh
19356 @end example
19358 @node Parallel Make
19359 @section Parallel Make
19360 @cindex Parallel @command{make}
19362 Support for parallel execution in @command{make} implementation varies.
19363 Generally, using GNU make is your best bet.  When NetBSD
19364 @command{make} is invoked with @option{-j@var{N}}, it will reuse the
19365 same shell for multiple commands within one recipe.  This can have
19366 unexpected consequences.@footnote{Note that GNU make has
19367 heuristics to avoid spawning a shell at all if the command is deemed
19368 safe to be executed directly.} For example, change of directories or
19369 variables persist between commands:
19371 @example
19372 all:
19373         @@var=value; cd /; pwd; echo $$var; echo $$$$
19374         @@pwd; echo $$var; echo $$$$
19375 @end example
19377 @noindent
19378 may output the following with @code{make -j1}:
19380 @example
19381 --- all ---
19383 value
19384 32235
19386 value
19387 32235
19388 @end example
19390 while without @option{-j1}, or with @option{-B}, the output looks less
19391 surprising:
19393 @example
19395 value
19396 32238
19397 /tmp
19399 32239
19400 @end example
19402 Another consequence of this is that, if one command in a recipe uses
19403 @code{exit 0} to indicate a successful exit, the shell will be gone
19404 and the remaining commands of this recipe will not be executed.
19406 The above example also shows additional status output NetBSD
19407 @command{make} produces in parallel mode for targets being updated.
19409 Furthermore, parallel NetBSD @command{make} will route standard error
19410 from commands that it spawns into its own standard output, and may
19411 remove leading whitespace from output lines.
19413 You can avoid these issues by using the @option{-B} option to enable
19414 compatibility semantics.  However, that will effectively also disable
19415 all parallelism as that will cause prerequisites to be updated in the
19416 order they are listed in a rule.
19418 @node Comments in Make Rules
19419 @section Comments in Make Rules
19420 @cindex Comments in @file{Makefile} rules
19421 @cindex @file{Makefile} rules and comments
19423 Never put comments in a rule.
19425 Some @command{make} treat anything starting with a tab as a command for
19426 the current rule, even if the tab is immediately followed by a @code{#}.
19427 The @command{make} from Tru64 Unix V5.1 is one of them.  The following
19428 makefile runs @code{# foo} through the shell.
19430 @example
19431 all:
19432         # foo
19433 @end example
19435 As a workaround, you can use the @command{:} no-op command with a string
19436 argument that gets ignored:
19438 @example
19439 all:
19440         : "foo"
19441 @end example
19443 @node Newlines in Make Rules
19444 @section Newlines in Make Rules
19445 @cindex Newlines in @file{Makefile} rules
19446 @cindex @file{Makefile} rules and newlines
19448 In shell scripts, newlines can be used inside string literals.  But in
19449 the shell statements of @file{Makefile} rules, this is not possible:
19450 A newline not preceded by a backslash is a separator between shell
19451 statements.  Whereas a newline that is preceded by a backslash becomes
19452 part of the shell statement according to POSIX, but gets replaced,
19453 together with the backslash that precedes it, by a space in GNU
19454 @command{make} 3.80 and older.  So, how can a newline be used in a string
19455 literal?
19457 The trick is to set up a shell variable that contains a newline:
19459 @example
19460 nlinit=`echo 'nl="'; echo '"'`; eval "$$nlinit"
19461 @end example
19463 For example, in order to create a multiline @samp{sed} expression that
19464 inserts a blank line after every line of a file, this code can be used:
19466 @example
19467 nlinit=`echo 'nl="'; echo '"'`; eval "$$nlinit"; \
19468 sed -e "s/\$$/\\$$@{nl@}/" < input > output
19469 @end example
19471 @node obj/ and Make
19472 @section The @file{obj/} Subdirectory and Make
19473 @cindex @file{obj/}, subdirectory
19474 @cindex BSD @command{make} and @file{obj/}
19476 Never name one of your subdirectories @file{obj/} if you don't like
19477 surprises.
19479 If an @file{obj/} directory exists, BSD @command{make} enters it
19480 before reading the makefile.  Hence the makefile in the
19481 current directory is not read.
19483 @example
19484 $ @kbd{cat Makefile}
19485 all:
19486         echo Hello
19487 $ @kbd{cat obj/Makefile}
19488 all:
19489         echo World
19490 $ @kbd{make}      # GNU make
19491 echo Hello
19492 Hello
19493 $ @kbd{pmake}     # BSD make
19494 echo World
19495 World
19496 @end example
19498 @node make -k Status
19499 @section Exit Status of @code{make -k}
19500 @cindex @code{make -k}
19502 Do not rely on the exit status of @code{make -k}.  Some implementations
19503 reflect whether they encountered an error in their exit status; other
19504 implementations always succeed.
19506 @example
19507 $ @kbd{cat Makefile}
19508 all:
19509         false
19510 $ @kbd{make -k; echo exit status: $?}    # GNU make
19511 false
19512 make: *** [all] Error 1
19513 exit status: 2
19514 $ @kbd{pmake -k; echo exit status: $?}   # BSD make
19515 false
19516 *** Error code 1 (continuing)
19517 exit status: 0
19518 @end example
19520 @node VPATH and Make
19521 @section @code{VPATH} and Make
19522 @cindex @code{VPATH}
19524 Posix does not specify the semantics of @code{VPATH}.  Typically,
19525 @command{make} supports @code{VPATH}, but its implementation is not
19526 consistent.
19528 Autoconf and Automake support makefiles whose usages of @code{VPATH} are
19529 portable to recent-enough popular implementations of @command{make}, but
19530 to keep the resulting makefiles portable, a package's makefile
19531 prototypes must take the following issues into account.  These issues
19532 are complicated and are often poorly understood, and installers who use
19533 @code{VPATH} should expect to find many bugs in this area.  If you use
19534 @code{VPATH}, the simplest way to avoid these portability bugs is to
19535 stick with GNU @command{make}, since it is the most
19536 commonly-used @command{make} among Autoconf users.
19538 Here are some known issues with some @code{VPATH}
19539 implementations.
19541 @menu
19542 * Variables listed in VPATH::   @code{VPATH} must be literal on ancient hosts
19543 * VPATH and Double-colon::      Problems with @samp{::} on ancient hosts
19544 * $< in Explicit Rules::        @code{$<} does not work in ordinary rules
19545 * Automatic Rule Rewriting::    @code{VPATH} goes wild on Solaris
19546 * Tru64 Directory Magic::       @command{mkdir} goes wild on Tru64
19547 * Make Target Lookup::          More details about @code{VPATH} lookup
19548 @end menu
19550 @node Variables listed in VPATH
19551 @subsection Variables listed in @code{VPATH}
19552 @cindex @code{VPATH} and variables
19553 @cindex variables and @code{VPATH}
19555 Do not set @code{VPATH} to the value of another variable, for example
19556 @samp{VPATH = $(srcdir)}, because some ancient versions of
19557 @command{make} do not do variable substitutions on the value of
19558 @code{VPATH}.  For example, use this
19560 @example
19561 srcdir = @@srcdir@@
19562 VPATH = @@srcdir@@
19563 @end example
19565 @noindent
19566 rather than @samp{VPATH = $(srcdir)}.  Note that with GNU
19567 Automake, there is no need to set this yourself.
19569 @node VPATH and Double-colon
19570 @subsection @code{VPATH} and Double-colon Rules
19571 @cindex @code{VPATH} and double-colon rules
19572 @cindex double-colon rules and @code{VPATH}
19574 With ancient versions of Sun @command{make},
19575 any assignment to @code{VPATH} causes @command{make} to execute only
19576 the first set of double-colon rules.
19577 However, this problem is no longer of practical concern.
19579 @node $< in Explicit Rules
19580 @subsection @code{$<} Not Supported in Explicit Rules
19581 @cindex explicit rules, @code{$<}, and @code{VPATH}
19582 @cindex @code{$<}, explicit rules, and @code{VPATH}
19583 @cindex @code{VPATH}, explicit rules, and @code{$<}
19585 Using @code{$<} in explicit rules is not portable.
19586 The prerequisite file must be named explicitly in the rule.  If you want
19587 to find the prerequisite via a @code{VPATH} search, you have to code the
19588 whole thing manually.  @xref{Build Directories}.
19590 @node Automatic Rule Rewriting
19591 @subsection Automatic Rule Rewriting
19592 @cindex @code{VPATH} and automatic rule rewriting
19593 @cindex automatic rule rewriting and @code{VPATH}
19595 Some @command{make} implementations, such as Solaris and Tru64,
19596 search for prerequisites in @code{VPATH} and
19597 then rewrite each occurrence as a plain word in the rule.
19598 For instance:
19600 @example
19601 # This isn't portable to GNU make.
19602 VPATH = ../pkg/src
19603 f.c: if.c
19604         cp if.c f.c
19605 @end example
19607 @noindent
19608 executes @code{cp ../pkg/src/if.c f.c} if @file{if.c} is
19609 found in @file{../pkg/src}.
19611 However, this rule leads to real problems in practice.  For example, if
19612 the source directory contains an ordinary file named @file{test} that is
19613 used in a dependency, Solaris @command{make} rewrites commands like
19614 @samp{if test -r foo; @dots{}} to @samp{if ../pkg/src/test -r foo;
19615 @dots{}}, which is typically undesirable.  To avoid this problem,
19616 portable makefiles should never mention a source file whose name is that
19617 of a shell keyword like @file{until} or a shell command like
19618 @command{cat} or @command{gcc} or @command{test}.
19620 Because of these problems GNU @command{make} and many other
19621 @command{make} implementations do not rewrite commands, so portable
19622 makefiles should
19623 search @code{VPATH} manually.  It is tempting to write this:
19625 @smallexample
19626 # This isn't portable to Solaris make.
19627 VPATH = ../pkg/src
19628 f.c: if.c
19629         cp `test -f if.c || echo $(VPATH)/`if.c f.c
19630 @end smallexample
19632 @noindent
19633 However, the ``prerequisite rewriting'' still applies here.  So if
19634 @file{if.c} is in @file{../pkg/src}, Solaris and Tru64 @command{make}
19635 execute
19637 @smallexample
19638 cp `test -f ../pkg/src/if.c || echo ../pkg/src/`if.c f.c
19639 @end smallexample
19641 @noindent
19642 which reduces to
19644 @example
19645 cp if.c f.c
19646 @end example
19648 @noindent
19649 and thus fails.  Oops.
19651 A simple workaround, and good practice anyway, is to use @samp{$?} and
19652 @samp{$@@} when possible:
19654 @smallexample
19655 VPATH = ../pkg/src
19656 f.c: if.c
19657         cp $? $@@
19658 @end smallexample
19660 @noindent
19661 but this does not generalize well to commands with multiple
19662 prerequisites.  A more general workaround is to rewrite the rule so that
19663 the prerequisite @file{if.c} never appears as a plain word.  For
19664 example, these three rules would be safe, assuming @file{if.c} is in
19665 @file{../pkg/src} and the other files are in the working directory:
19667 @smallexample
19668 VPATH = ../pkg/src
19669 f.c: if.c f1.c
19670         cat `test -f ./if.c || echo $(VPATH)/`if.c f1.c >$@@
19671 g.c: if.c g1.c
19672         cat `test -f 'if.c' || echo $(VPATH)/`if.c g1.c >$@@
19673 h.c: if.c h1.c
19674         cat `test -f "if.c" || echo $(VPATH)/`if.c h1.c >$@@
19675 @end smallexample
19677 Things get worse when your prerequisites are in a macro.
19679 @example
19680 VPATH = ../pkg/src
19681 HEADERS = f.h g.h h.h
19682 install-HEADERS: $(HEADERS)
19683         for i in $(HEADERS); do \
19684           $(INSTALL) -m 644 \
19685             `test -f $$i || echo $(VPATH)/`$$i \
19686             $(DESTDIR)$(includedir)/$$i; \
19687 @c $$ restore font-lock
19688         done
19689 @end example
19691 The above @code{install-HEADERS} rule is not Solaris-proof because @code{for
19692 i in $(HEADERS);} is expanded to @code{for i in f.h g.h h.h;}
19693 where @code{f.h} and @code{g.h} are plain words and are hence
19694 subject to @code{VPATH} adjustments.
19696 If the three files are in @file{../pkg/src}, the rule is run as:
19698 @example
19699 for i in ../pkg/src/f.h ../pkg/src/g.h h.h; do \
19700   install -m 644 \
19701      `test -f $i || echo ../pkg/src/`$i \
19702      /usr/local/include/$i; \
19703 done
19704 @end example
19706 where the two first @command{install} calls fail.  For instance,
19707 consider the @code{f.h} installation:
19709 @example
19710 install -m 644 \
19711   `test -f ../pkg/src/f.h || \
19712     echo ../pkg/src/ \
19713   `../pkg/src/f.h \
19714   /usr/local/include/../pkg/src/f.h;
19715 @end example
19717 @noindent
19718 It reduces to:
19720 @example
19721 install -m 644 \
19722   ../pkg/src/f.h \
19723   /usr/local/include/../pkg/src/f.h;
19724 @end example
19726 Note that the manual @code{VPATH} search did not cause any problems here;
19727 however this command installs @file{f.h} in an incorrect directory.
19729 Trying to quote @code{$(HEADERS)} in some way, as we did for
19730 @code{foo.c} a few makefiles ago, does not help:
19732 @example
19733 install-HEADERS: $(HEADERS)
19734         headers='$(HEADERS)'; \
19735         for i in $$headers; do \
19736           $(INSTALL) -m 644 \
19737             `test -f $$i || echo $(VPATH)/`$$i \
19738             $(DESTDIR)$(includedir)/$$i; \
19739         done
19740 @end example
19742 Now, @code{headers='$(HEADERS)'} macro-expands to:
19744 @example
19745 headers='f.h g.h h.h'
19746 @end example
19748 @noindent
19749 but @code{g.h} is still a plain word.  (As an aside, the idiom
19750 @code{headers='$(HEADERS)'; for i in $$headers;} is a good
19751 idea if @code{$(HEADERS)} can be empty, because some shells diagnose a
19752 syntax error on @code{for i in;}.)
19754 One workaround is to strip this unwanted @file{../pkg/src/} prefix manually:
19756 @example
19757 VPATH = ../pkg/src
19758 HEADERS = f.h g.h h.h
19759 install-HEADERS: $(HEADERS)
19760         headers='$(HEADERS)'; \
19761         for i in $$headers; do \
19762           i=`expr "$$i" : '$(VPATH)/\(.*\)'`;
19763           $(INSTALL) -m 644 \
19764             `test -f $$i || echo $(VPATH)/`$$i \
19765             $(DESTDIR)$(includedir)/$$i; \
19766 @c $$ restore font-lock
19767         done
19768 @end example
19770 Automake does something similar.  However the above hack works only if
19771 the files listed in @code{HEADERS} are in the current directory or a
19772 subdirectory; they should not be in an enclosing directory.  If we had
19773 @code{HEADERS = ../f.h}, the above fragment would fail in a VPATH
19774 build with Tru64 @command{make}.  The reason is that not only does
19775 Tru64 @command{make} rewrite dependencies, but it also simplifies
19776 them.  Hence @code{../f.h} becomes @code{../pkg/f.h} instead of
19777 @code{../pkg/src/../f.h}.  This obviously defeats any attempt to strip
19778 a leading @file{../pkg/src/} component.
19780 The following example makes the behavior of Tru64 @command{make}
19781 more apparent.
19783 @example
19784 $ @kbd{cat Makefile}
19785 VPATH = sub
19786 all: ../foo
19787         echo ../foo
19788 $ @kbd{ls}
19789 Makefile foo
19790 $ @kbd{make}
19791 echo foo
19793 @end example
19795 @noindent
19796 Dependency @file{../foo} was found in @file{sub/../foo}, but Tru64
19797 @command{make} simplified it as @file{foo}.  (Note that the @file{sub/}
19798 directory does not even exist, this just means that the simplification
19799 occurred before the file was checked for.)
19801 For the record here is how SunOS 4 @command{make} behaves on this
19802 example.
19804 @smallexample
19805 $ @kbd{make}
19806 make: Fatal error: Don't know how to make target `../foo'
19807 $ @kbd{mkdir sub}
19808 $ @kbd{make}
19809 echo sub/../foo
19810 sub/../foo
19811 @end smallexample
19814 @node Tru64 Directory Magic
19815 @subsection Tru64 @command{make} Creates Prerequisite Directories Magically
19816 @cindex @code{VPATH} and prerequisite directories
19817 @cindex prerequisite directories and @code{VPATH}
19819 When a prerequisite is a subdirectory of @code{VPATH}, Tru64
19820 @command{make} creates it in the current directory.
19822 @example
19823 $ @kbd{mkdir -p foo/bar build}
19824 $ @kbd{cd build}
19825 $ @kbd{cat >Makefile <<END
19826 VPATH = ..
19827 all: foo/bar
19828 END}
19829 $ @kbd{make}
19830 mkdir foo
19831 mkdir foo/bar
19832 @end example
19834 This can yield unexpected results if a rule uses a manual @code{VPATH}
19835 search as presented before.
19837 @example
19838 VPATH = ..
19839 all : foo/bar
19840         command `test -d foo/bar || echo ../`foo/bar
19841 @end example
19843 The above @command{command} is run on the empty @file{foo/bar}
19844 directory that was created in the current directory.
19846 @node Make Target Lookup
19847 @subsection Make Target Lookup
19848 @cindex @code{VPATH}, resolving target pathnames
19850 GNU @command{make} uses a complex algorithm to decide when it
19851 should use files found via a @code{VPATH} search.  @xref{Search
19852 Algorithm, , How Directory Searches are Performed, make, The GNU Make
19853 Manual}.
19855 If a target needs to be rebuilt, GNU @command{make} discards the
19856 file name found during the @code{VPATH} search for this target, and
19857 builds the file locally using the file name given in the makefile.
19858 If a target does not need to be rebuilt, GNU @command{make} uses the
19859 file name found during the @code{VPATH} search.
19861 Other @command{make} implementations, like NetBSD @command{make}, are
19862 easier to describe: the file name found during the @code{VPATH} search
19863 is used whether the target needs to be rebuilt or not.  Therefore
19864 new files are created locally, but existing files are updated at their
19865 @code{VPATH} location.
19867 OpenBSD and FreeBSD @command{make}, however,
19868 never perform a
19869 @code{VPATH} search for a dependency that has an explicit rule.
19870 This is extremely annoying.
19872 When attempting a @code{VPATH} build for an autoconfiscated package
19873 (e.g., @code{mkdir build && cd build && ../configure}), this means
19875 @command{make} builds everything locally in the @file{build}
19876 directory, while BSD @command{make} builds new files locally and
19877 updates existing files in the source directory.
19879 @example
19880 $ @kbd{cat Makefile}
19881 VPATH = ..
19882 all: foo.x bar.x
19883 foo.x bar.x: newer.x
19884         @@echo Building $@@
19885 $ @kbd{touch ../bar.x}
19886 $ @kbd{touch ../newer.x}
19887 $ @kbd{make}        # GNU make
19888 Building foo.x
19889 Building bar.x
19890 $ @kbd{pmake}       # NetBSD make
19891 Building foo.x
19892 Building ../bar.x
19893 $ @kbd{fmake}       # FreeBSD make, OpenBSD make
19894 Building foo.x
19895 Building bar.x
19896 $ @kbd{tmake}       # Tru64 make
19897 Building foo.x
19898 Building bar.x
19899 $ @kbd{touch ../bar.x}
19900 $ @kbd{make}        # GNU make
19901 Building foo.x
19902 $ @kbd{pmake}       # NetBSD make
19903 Building foo.x
19904 $ @kbd{fmake}       # FreeBSD make, OpenBSD make
19905 Building foo.x
19906 Building bar.x
19907 $ @kbd{tmake}       # Tru64 make
19908 Building foo.x
19909 Building bar.x
19910 @end example
19912 Note how NetBSD @command{make} updates @file{../bar.x} in its
19913 VPATH location, and how FreeBSD, OpenBSD, and Tru64
19914 @command{make} always
19915 update @file{bar.x}, even when @file{../bar.x} is up to date.
19917 Another point worth mentioning is that once GNU @command{make} has
19918 decided to ignore a @code{VPATH} file name (e.g., it ignored
19919 @file{../bar.x} in the above example) it continues to ignore it when
19920 the target occurs as a prerequisite of another rule.
19922 The following example shows that GNU @command{make} does not look up
19923 @file{bar.x} in @code{VPATH} before performing the @code{.x.y} rule,
19924 because it ignored the @code{VPATH} result of @file{bar.x} while running
19925 the @code{bar.x: newer.x} rule.
19927 @example
19928 $ @kbd{cat Makefile}
19929 VPATH = ..
19930 all: bar.y
19931 bar.x: newer.x
19932         @@echo Building $@@
19933 .SUFFIXES: .x .y
19934 .x.y:
19935         cp $< $@@
19936 $ @kbd{touch ../bar.x}
19937 $ @kbd{touch ../newer.x}
19938 $ @kbd{make}        # GNU make
19939 Building bar.x
19940 cp bar.x bar.y
19941 cp: cannot stat `bar.x': No such file or directory
19942 make: *** [bar.y] Error 1
19943 $ @kbd{pmake}       # NetBSD make
19944 Building ../bar.x
19945 cp ../bar.x bar.y
19946 $ @kbd{rm bar.y}
19947 $ @kbd{fmake}       # FreeBSD make, OpenBSD make
19948 echo Building bar.x
19949 cp bar.x bar.y
19950 cp: cannot stat `bar.x': No such file or directory
19951 *** Error code 1
19952 $ @kbd{tmake}       # Tru64 make
19953 Building bar.x
19954 cp: bar.x: No such file or directory
19955 *** Exit 1
19956 @end example
19958 Note that if you drop away the command from the @code{bar.x: newer.x}
19959 rule, GNU @command{make} magically starts to work: it
19960 knows that @code{bar.x} hasn't been updated, therefore it doesn't
19961 discard the result from @code{VPATH} (@file{../bar.x}) in succeeding
19962 uses.  Tru64 also works, but FreeBSD and OpenBSD
19963 still don't.
19965 @example
19966 $ @kbd{cat Makefile}
19967 VPATH = ..
19968 all: bar.y
19969 bar.x: newer.x
19970 .SUFFIXES: .x .y
19971 .x.y:
19972         cp $< $@@
19973 $ @kbd{touch ../bar.x}
19974 $ @kbd{touch ../newer.x}
19975 $ @kbd{make}        # GNU make
19976 cp ../bar.x bar.y
19977 $ @kbd{rm bar.y}
19978 $ @kbd{pmake}       # NetBSD make
19979 cp ../bar.x bar.y
19980 $ @kbd{rm bar.y}
19981 $ @kbd{fmake}       # FreeBSD make, OpenBSD make
19982 cp bar.x bar.y
19983 cp: cannot stat `bar.x': No such file or directory
19984 *** Error code 1
19985 $ @kbd{tmake}       # Tru64 make
19986 cp ../bar.x bar.y
19987 @end example
19989 It seems the sole solution that would please every @command{make}
19990 implementation is to never rely on @code{VPATH} searches for targets.
19991 In other words, @code{VPATH} should be reserved to unbuilt sources.
19994 @node Single Suffix Rules
19995 @section Single Suffix Rules and Separated Dependencies
19996 @cindex Single Suffix Inference Rule
19997 @cindex Rule, Single Suffix Inference
19998 A @dfn{Single Suffix Rule} is basically a usual suffix (inference) rule
19999 (@samp{.from.to:}), but which @emph{destination} suffix is empty
20000 (@samp{.from:}).
20002 @cindex Separated Dependencies
20003 @dfn{Separated dependencies} simply refers to listing the prerequisite
20004 of a target, without defining a rule.  Usually one can list on the one
20005 hand side, the rules, and on the other hand side, the dependencies.
20007 Solaris @command{make} does not support separated dependencies for
20008 targets defined by single suffix rules:
20010 @example
20011 $ @kbd{cat Makefile}
20012 .SUFFIXES: .in
20013 foo: foo.in
20014 .in:
20015         cp $< $@@
20016 $ @kbd{touch foo.in}
20017 $ @kbd{make}
20018 $ @kbd{ls}
20019 Makefile  foo.in
20020 @end example
20022 @noindent
20023 while GNU Make does:
20025 @example
20026 $ @kbd{gmake}
20027 cp foo.in foo
20028 $ @kbd{ls}
20029 Makefile  foo       foo.in
20030 @end example
20032 Note it works without the @samp{foo: foo.in} dependency.
20034 @example
20035 $ @kbd{cat Makefile}
20036 .SUFFIXES: .in
20037 .in:
20038         cp $< $@@
20039 $ @kbd{make foo}
20040 cp foo.in foo
20041 @end example
20043 @noindent
20044 and it works with double suffix inference rules:
20046 @example
20047 $ @kbd{cat Makefile}
20048 foo.out: foo.in
20049 .SUFFIXES: .in .out
20050 .in.out:
20051         cp $< $@@
20052 $ @kbd{make}
20053 cp foo.in foo.out
20054 @end example
20056 As a result, in such a case, you have to write target rules.
20058 @node Timestamps and Make
20059 @section Timestamp Resolution and Make
20060 @cindex timestamp resolution
20061 Traditionally, file timestamps had 1-second resolution, and
20062 @command{make} used those timestamps to determine whether one file was
20063 newer than the other.  However, many modern file systems have
20064 timestamps with 1-nanosecond resolution.  Some @command{make}
20065 implementations look at the entire timestamp; others ignore the
20066 fractional part, which can lead to incorrect results.  Normally this
20067 is not a problem, but in some extreme cases you may need to use tricks
20068 like @samp{sleep 1} to work around timestamp truncation bugs.
20070 Commands like @samp{cp -p} and @samp{touch -r} typically do not copy
20071 file timestamps to their full resolutions (@pxref{touch, , Limitations of Usual
20072 Tools}).  Hence you should be wary of rules like this:
20074 @example
20075 dest: src
20076         cp -p src dest
20077 @end example
20079 as @file{dest} often appears to be older than @file{src} after the
20080 timestamp is truncated, and this can cause @command{make} to do
20081 needless rework the next time it is invoked.  To work around this
20082 problem, you can use a timestamp file, e.g.:
20084 @example
20085 dest-stamp: src
20086         cp -p src dest
20087         date >dest-stamp
20088 @end example
20093 @c ======================================== Portable C and C++ Programming
20095 @node Portable C and C++
20096 @chapter Portable C and C++ Programming
20097 @cindex Portable C and C++ programming
20099 C and C++ programs often use low-level features of the underlying
20100 system, and therefore are often more difficult to make portable to other
20101 platforms.
20103 Several standards have been developed to help make your programs more
20104 portable.  If you write programs with these standards in mind, you can
20105 have greater confidence that your programs work on a wide variety
20106 of systems.
20107 @ifhtml
20108 @uref{http://@/gcc.gnu.org/@/onlinedocs/@/gcc/@/Standards.html, Language
20109 Standards Supported by GCC}
20110 @end ifhtml
20111 @ifnothtml
20112 @xref{Standards, , Language Standards Supported by
20113 GCC, gcc, Using the GNU Compiler Collection
20114 (GCC)},
20115 @end ifnothtml
20116 for a list of C-related standards.  Many programs also assume the
20117 @uref{http://@/www.opengroup.org/@/susv3, Posix standard}.
20119 Some old code is written to be portable to K&R C, which predates any C
20120 standard.  K&R C compilers are no longer of practical interest, though,
20121 and the rest of section assumes at least C89, the first C standard.
20123 Program portability is a huge topic, and this section can only briefly
20124 introduce common pitfalls.  @xref{System Portability, , Portability
20125 between System Types, standards, The GNU Coding Standards}, for
20126 more information.
20128 @menu
20129 * Varieties of Unportability::  How to make your programs unportable
20130 * Integer Overflow::            When integers get too large
20131 * Preprocessor Arithmetic::     @code{#if} expression problems
20132 * Null Pointers::               Properties of null pointers
20133 * Buffer Overruns::             Subscript errors and the like
20134 * Volatile Objects::            @code{volatile} and signals
20135 * Floating Point Portability::  Portable floating-point arithmetic
20136 * Exiting Portably::            Exiting and the exit status
20137 @end menu
20139 @node Varieties of Unportability
20140 @section Varieties of Unportability
20141 @cindex portability
20143 Autoconf tests and ordinary programs often need to test what is allowed
20144 on a system, and therefore they may need to deliberately exceed the
20145 boundaries of what the standards allow, if only to see whether an
20146 optional feature is present.  When you write such a program, you should
20147 keep in mind the difference between constraints, unspecified behavior,
20148 and undefined behavior.
20150 In C, a @dfn{constraint} is a rule that the compiler must enforce.  An
20151 example constraint is that C programs must not declare a bit-field with
20152 negative width.  Tests can therefore reliably assume that programs with
20153 negative-width bit-fields are rejected by a compiler that conforms
20154 to the standard.
20156 @dfn{Unspecified behavior} is valid behavior, where the standard allows
20157 multiple possibilities.  For example, the order of evaluation of
20158 function arguments is unspecified.  Some unspecified behavior is
20159 @dfn{implementation-defined}, i.e., documented by the implementation,
20160 but since Autoconf tests cannot read the documentation they cannot
20161 distinguish between implementation-defined and other unspecified
20162 behavior.  It is common for Autoconf tests to probe implementations to
20163 determine otherwise-unspecified behavior.
20165 @dfn{Undefined behavior} is invalid behavior, where the standard allows
20166 the implementation to do anything it pleases.  For example,
20167 dereferencing a null pointer leads to undefined behavior.  If possible,
20168 test programs should avoid undefined behavior, since a program with
20169 undefined behavior might succeed on a test that should fail.
20171 The above rules apply to programs that are intended to conform to the
20172 standard.  However, strictly-conforming programs are quite rare, since
20173 the standards are so limiting.  A major goal of Autoconf is to support
20174 programs that use implementation features not described by the standard,
20175 and it is fairly common for test programs to violate the above rules, if
20176 the programs work well enough in practice.
20178 @node Integer Overflow
20179 @section Integer Overflow
20180 @cindex integer overflow
20181 @cindex overflow, signed integer
20182 @cindex signed integer overflow
20183 @cindex wraparound arithmetic
20185 In practice many portable C programs assume that signed integer overflow wraps
20186 around reliably using two's complement arithmetic.  Yet the C standard
20187 says that program behavior is undefined on overflow, and in a few cases
20188 C programs do not work on some modern implementations because their
20189 overflows do not wrap around as their authors expected.  Conversely, in
20190 signed integer remainder, the C standard requires overflow
20191 behavior that is commonly not implemented.
20193 @menu
20194 * Integer Overflow Basics::      Why integer overflow is a problem
20195 * Signed Overflow Examples::     Examples of code assuming wraparound
20196 * Optimization and Wraparound::  Optimizations that break uses of wraparound
20197 * Signed Overflow Advice::       Practical advice for signed overflow issues
20198 * Signed Integer Division::      @code{INT_MIN / -1} and @code{INT_MIN % -1}
20199 @end menu
20201 @node Integer Overflow Basics
20202 @subsection Basics of Integer Overflow
20203 @cindex integer overflow
20204 @cindex overflow, signed integer
20205 @cindex signed integer overflow
20206 @cindex wraparound arithmetic
20208 In languages like C, unsigned integer overflow reliably wraps around;
20209 e.g., @code{UINT_MAX + 1} yields zero.
20210 This is guaranteed by the C standard and is
20211 portable in practice, unless you specify aggressive,
20212 nonstandard optimization options
20213 suitable only for special applications.
20215 In contrast, the C standard says that signed integer overflow leads to
20216 undefined behavior where a program can do anything, including dumping
20217 core or overrunning a buffer.  The misbehavior can even precede the
20218 overflow.  Such an overflow can occur during addition, subtraction,
20219 multiplication, division, and left shift.
20221 Despite this requirement of the standard, many C programs and Autoconf
20222 tests assume that signed integer overflow silently wraps around modulo a
20223 power of two, using two's complement arithmetic, so long as you cast the
20224 resulting value to a signed integer type or store it into a signed
20225 integer variable.  If you use conservative optimization flags, such
20226 programs are generally portable to the vast majority of modern
20227 platforms, with a few exceptions discussed later.
20229 For historical reasons the C standard also allows implementations with
20230 ones' complement or signed magnitude arithmetic, but it is safe to
20231 assume two's complement nowadays.
20233 Also, overflow can occur when converting an out-of-range value to a
20234 signed integer type.  Here a standard implementation must define what
20235 happens, but this might include raising an exception.  In practice all
20236 known implementations support silent wraparound in this case, so you need
20237 not worry about other possibilities.
20239 @node Signed Overflow Examples
20240 @subsection Examples of Code Assuming Wraparound Overflow
20241 @cindex integer overflow
20242 @cindex overflow, signed integer
20243 @cindex signed integer overflow
20244 @cindex wraparound arithmetic
20246 There has long been a tension between what the C standard requires for
20247 signed integer overflow, and what C programs commonly assume.  The
20248 standard allows aggressive optimizations based on assumptions that
20249 overflow never occurs, but many practical C programs rely on overflow
20250 wrapping around.  These programs do not conform to the standard, but
20251 they commonly work in practice because compiler writers are
20252 understandably reluctant to implement optimizations that would break
20253 many programs, unless perhaps a user specifies aggressive optimization.
20255 The C Standard says that if a program has signed integer overflow its
20256 behavior is undefined, and the undefined behavior can even precede the
20257 overflow.  To take an extreme example:
20259 @c Inspired by Robert Dewar's example in
20260 @c <http://gcc.gnu.org/ml/gcc/2007-01/msg00038.html> (2007-01-01).
20261 @example
20262 if (password == expected_password)
20263   allow_superuser_privileges ();
20264 else if (counter++ == INT_MAX)
20265   abort ();
20266 else
20267   printf ("%d password mismatches\n", counter);
20268 @end example
20270 @noindent
20271 If the @code{int} variable @code{counter} equals @code{INT_MAX},
20272 @code{counter++} must overflow and the behavior is undefined, so the C
20273 standard allows the compiler to optimize away the test against
20274 @code{INT_MAX} and the @code{abort} call.
20275 Worse, if an earlier bug in the program lets the compiler deduce that
20276 @code{counter == INT_MAX} or that @code{counter} previously overflowed,
20277 the C standard allows the compiler to optimize away the password test
20278 and generate code that allows superuser privileges unconditionally.
20280 Despite this requirement by the standard, it has long been common for C
20281 code to assume wraparound arithmetic after signed overflow, and all
20282 known practical C implementations support some C idioms that assume
20283 wraparound signed arithmetic, even if the idioms do not conform
20284 strictly to the standard.  If your code looks like the following
20285 examples it will almost surely work with real-world compilers.
20287 Here is an example derived from the 7th Edition Unix implementation of
20288 @code{atoi} (1979-01-10):
20290 @example
20291 char *p;
20292 int f, n;
20293 @dots{}
20294 while (*p >= '0' && *p <= '9')
20295   n = n * 10 + *p++ - '0';
20296 return (f ? -n : n);
20297 @end example
20299 @noindent
20300 Even if the input string is in range, on most modern machines this has
20301 signed overflow when computing the most negative integer (the @code{-n}
20302 overflows) or a value near an extreme integer (the first @code{+}
20303 overflows).
20305 Here is another example, derived from the 7th Edition implementation of
20306 @code{rand} (1979-01-10).  Here the programmer expects both
20307 multiplication and addition to wrap on overflow:
20309 @example
20310 static long int randx = 1;
20311 @dots{}
20312 randx = randx * 1103515245 + 12345;
20313 return (randx >> 16) & 077777;
20314 @end example
20316 In the following example, derived from the GNU C Library 2.5
20317 implementation of @code{mktime} (2006-09-09), the code assumes
20318 wraparound arithmetic in @code{+} to detect signed overflow:
20320 @example
20321 time_t t, t1, t2;
20322 int sec_requested, sec_adjustment;
20323 @dots{}
20324 t1 = t + sec_requested;
20325 t2 = t1 + sec_adjustment;
20326 if (((t1 < t) != (sec_requested < 0))
20327     | ((t2 < t1) != (sec_adjustment < 0)))
20328   return -1;
20329 @end example
20331 If your code looks like these examples, it is probably safe even though
20332 it does not strictly conform to the C standard.  This might lead one to
20333 believe that one can generally assume wraparound on overflow, but that
20334 is not always true, as can be seen in the next section.
20336 @node Optimization and Wraparound
20337 @subsection Optimizations That Break Wraparound Arithmetic
20338 @cindex loop induction
20340 Compilers sometimes generate code that is incompatible with wraparound
20341 integer arithmetic.  A simple example is an algebraic simplification: a
20342 compiler might translate @code{(i * 2000) / 1000} to @code{i * 2}
20343 because it assumes that @code{i * 2000} does not overflow.  The
20344 translation is not equivalent to the original when overflow occurs:
20345 e.g., in the typical case of 32-bit signed two's complement wraparound
20346 @code{int}, if @code{i} has type @code{int} and value @code{1073742},
20347 the original expression returns @minus{}2147483 but the optimized
20348 version returns the mathematically correct value 2147484.
20350 More subtly, loop induction optimizations often exploit the undefined
20351 behavior of signed overflow.  Consider the following contrived function
20352 @code{sumc}:
20354 @example
20356 sumc (int lo, int hi)
20358   int sum = 0;
20359   int i;
20360   for (i = lo; i <= hi; i++)
20361     sum ^= i * 53;
20362   return sum;
20364 @end example
20366 @noindent
20367 To avoid multiplying by 53 each time through the loop, an optimizing
20368 compiler might internally transform @code{sumc} to the equivalent of the
20369 following:
20371 @example
20373 transformed_sumc (int lo, int hi)
20375   int sum = 0;
20376   int hic = hi * 53;
20377   int ic;
20378   for (ic = lo * 53; ic <= hic; ic += 53)
20379     sum ^= ic;
20380   return sum;
20382 @end example
20384 @noindent
20385 This transformation is allowed by the C standard, but it is invalid for
20386 wraparound arithmetic when @code{INT_MAX / 53 < hi}, because then the
20387 overflow in computing expressions like @code{hi * 53} can cause the
20388 expression @code{i <= hi} to yield a different value from the
20389 transformed expression @code{ic <= hic}.
20391 For this reason, compilers that use loop induction and similar
20392 techniques often do not support reliable wraparound arithmetic when a
20393 loop induction variable like @code{ic} is involved.  Since loop
20394 induction variables are generated by the compiler, and are not visible
20395 in the source code, it is not always trivial to say whether the problem
20396 affects your code.
20398 Hardly any code actually depends on wraparound arithmetic in cases like
20399 these, so in practice these loop induction optimizations are almost
20400 always useful.  However, edge cases in this area can cause problems.
20401 For example:
20403 @example
20404 int j;
20405 for (j = 1; 0 < j; j *= 2)
20406   test (j);
20407 @end example
20409 @noindent
20410 Here, the loop attempts to iterate through all powers of 2 that
20411 @code{int} can represent, but the C standard allows a compiler to
20412 optimize away the comparison and generate an infinite loop,
20413 under the argument that behavior is undefined on overflow.  As of this
20414 writing this optimization is not done by any production version of
20415 GCC with @option{-O2}, but it might be performed by other
20416 compilers, or by more aggressive GCC optimization options,
20417 and the GCC developers have not decided whether it will
20418 continue to work with GCC and @option{-O2}.
20420 @node Signed Overflow Advice
20421 @subsection Practical Advice for Signed Overflow Issues
20422 @cindex integer overflow
20423 @cindex overflow, signed integer
20424 @cindex signed integer overflow
20425 @cindex wraparound arithmetic
20427 Ideally the safest approach is to avoid signed integer overflow
20428 entirely.  For example, instead of multiplying two signed integers, you
20429 can convert them to unsigned integers, multiply the unsigned values,
20430 then test whether the result is in signed range.
20432 Rewriting code in this way will be inconvenient, though, particularly if
20433 the signed values might be negative.  Also, it may hurt
20434 performance.  Using unsigned arithmetic to check for overflow is
20435 particularly painful to do portably and efficiently when dealing with an
20436 integer type like @code{uid_t} whose width and signedness vary from
20437 platform to platform.
20439 Furthermore, many C applications pervasively assume wraparound behavior
20440 and typically it is not easy to find and remove all these assumptions.
20441 Hence it is often useful to maintain nonstandard code that assumes
20442 wraparound on overflow, instead of rewriting the code.  The rest of this
20443 section attempts to give practical advice for this situation.
20445 If your code wants to detect signed integer overflow in @code{sum = a +
20446 b}, it is generally safe to use an expression like @code{(sum < a) != (b
20447 < 0)}.
20449 If your code uses a signed loop index, make sure that the index cannot
20450 overflow, along with all signed expressions derived from the index.
20451 Here is a contrived example of problematic code with two instances of
20452 overflow.
20454 @example
20455 for (i = INT_MAX - 10; i <= INT_MAX; i++)
20456   if (i + 1 < 0)
20457     @{
20458       report_overflow ();
20459       break;
20460     @}
20461 @end example
20463 @noindent
20464 Because of the two overflows, a compiler might optimize away or
20465 transform the two comparisons in a way that is incompatible with the
20466 wraparound assumption.
20468 If your code uses an expression like @code{(i * 2000) / 1000} and you
20469 actually want the multiplication to wrap around on overflow, use
20470 unsigned arithmetic
20471 to do it, e.g., @code{((int) (i * 2000u)) / 1000}.
20473 If your code assumes wraparound behavior and you want to insulate it
20474 against any GCC optimizations that would fail to support that
20475 behavior, you should use GCC's @option{-fwrapv} option, which
20476 causes signed overflow to wrap around reliably (except for division and
20477 remainder, as discussed in the next section).
20479 If you need to port to platforms where signed integer overflow does not
20480 reliably wrap around (e.g., due to hardware overflow checking, or to
20481 highly aggressive optimizations), you should consider debugging with
20482 GCC's @option{-ftrapv} option, which causes signed overflow to
20483 raise an exception.
20485 @node Signed Integer Division
20486 @subsection Signed Integer Division and Integer Overflow
20487 @cindex division, integer
20489 Overflow in signed
20490 integer division is not always harmless: for example, on CPUs of the
20491 i386 family, dividing @code{INT_MIN} by @code{-1} yields a SIGFPE signal
20492 which by default terminates the program.  Worse, taking the remainder
20493 of these two values typically yields the same signal on these CPUs,
20494 even though the C standard requires @code{INT_MIN % -1} to yield zero
20495 because the expression does not overflow.
20497 @node Preprocessor Arithmetic
20498 @section Preprocessor Arithmetic
20499 @cindex preprocessor arithmetic
20501 In C99, preprocessor arithmetic, used for @code{#if} expressions, must
20502 be evaluated as if all signed values are of type @code{intmax_t} and all
20503 unsigned values of type @code{uintmax_t}.  Many compilers are buggy in
20504 this area, though.  For example, as of 2007, Sun C mishandles @code{#if
20505 LLONG_MIN < 0} on a platform with 32-bit @code{long int} and 64-bit
20506 @code{long long int}.  Also, some older preprocessors mishandle
20507 constants ending in @code{LL}.  To work around these problems, you can
20508 compute the value of expressions like @code{LONG_MAX < LLONG_MAX} at
20509 @code{configure}-time rather than at @code{#if}-time.
20511 @node Null Pointers
20512 @section Properties of Null Pointers
20513 @cindex null pointers
20515 Most modern hosts reliably fail when you attempt to dereference a null
20516 pointer.
20518 On almost all modern hosts, null pointers use an all-bits-zero internal
20519 representation, so you can reliably use @code{memset} with 0 to set all
20520 the pointers in an array to null values.
20522 If @code{p} is a null pointer to an object type, the C expression
20523 @code{p + 0} always evaluates to @code{p} on modern hosts, even though
20524 the standard says that it has undefined behavior.
20526 @node Buffer Overruns
20527 @section Buffer Overruns and Subscript Errors
20528 @cindex buffer overruns
20530 Buffer overruns and subscript errors are the most common dangerous
20531 errors in C programs.  They result in undefined behavior because storing
20532 outside an array typically modifies storage that is used by some other
20533 object, and most modern systems lack runtime checks to catch these
20534 errors.  Programs should not rely on buffer overruns being caught.
20536 There is one exception to the usual rule that a portable program cannot
20537 address outside an array.  In C, it is valid to compute the address just
20538 past an object, e.g., @code{&a[N]} where @code{a} has @code{N} elements,
20539 so long as you do not dereference the resulting pointer.  But it is not
20540 valid to compute the address just before an object, e.g., @code{&a[-1]};
20541 nor is it valid to compute two past the end, e.g., @code{&a[N+1]}.  On
20542 most platforms @code{&a[-1] < &a[0] && &a[N] < &a[N+1]}, but this is not
20543 reliable in general, and it is usually easy enough to avoid the
20544 potential portability problem, e.g., by allocating an extra unused array
20545 element at the start or end.
20547 @uref{http://@/valgrind.org/, Valgrind} can catch many overruns.
20549 users might also consider using the @option{-fmudflap} option to catch
20550 overruns.
20552 Buffer overruns are usually caused by off-by-one errors, but there are
20553 more subtle ways to get them.
20555 Using @code{int} values to index into an array or compute array sizes
20556 causes problems on typical 64-bit hosts where an array index might
20557 be @math{2^31} or larger.  Index values of type @code{size_t} avoid this
20558 problem, but cannot be negative.  Index values of type @code{ptrdiff_t}
20559 are signed, and are wide enough in practice.
20561 If you add or multiply two numbers to calculate an array size, e.g.,
20562 @code{malloc (x * sizeof y + z)}, havoc ensues if the addition or
20563 multiplication overflows.
20565 Many implementations of the @code{alloca} function silently misbehave
20566 and can generate buffer overflows if given sizes that are too large.
20567 The size limits are implementation dependent, but are at least 4000
20568 bytes on all platforms that we know about.
20570 The standard functions @code{asctime}, @code{asctime_r}, @code{ctime},
20571 @code{ctime_r}, and @code{gets} are prone to buffer overflows, and
20572 portable code should not use them unless the inputs are known to be
20573 within certain limits.  The time-related functions can overflow their
20574 buffers if given timestamps out of range (e.g., a year less than -999
20575 or greater than 9999).  Time-related buffer overflows cannot happen with
20576 recent-enough versions of the GNU C library, but are possible
20577 with other
20578 implementations.  The @code{gets} function is the worst, since it almost
20579 invariably overflows its buffer when presented with an input line larger
20580 than the buffer.
20582 @node Volatile Objects
20583 @section Volatile Objects
20584 @cindex volatile objects
20586 The keyword @code{volatile} is often misunderstood in portable code.
20587 Its use inhibits some memory-access optimizations, but programmers often
20588 wish that it had a different meaning than it actually does.
20590 @code{volatile} was designed for code that accesses special objects like
20591 memory-mapped device registers whose contents spontaneously change.
20592 Such code is inherently low-level, and it is difficult to specify
20593 portably what @code{volatile} means in these cases.  The C standard
20594 says, ``What constitutes an access to an object that has
20595 volatile-qualified type is implementation-defined,'' so in theory each
20596 implementation is supposed to fill in the gap by documenting what
20597 @code{volatile} means for that implementation.  In practice, though,
20598 this documentation is usually absent or incomplete.
20600 One area of confusion is the distinction between objects defined with
20601 volatile types, and volatile lvalues.  From the C standard's point of
20602 view, an object defined with a volatile type has externally visible
20603 behavior.  You can think of such objects as having little oscilloscope
20604 probes attached to them, so that the user can observe some properties of
20605 accesses to them, just as the user can observe data written to output
20606 files.  However, the standard does not make it clear whether users can
20607 observe accesses by volatile lvalues to ordinary objects.  For example:
20609 @example
20610 /* Declare and access a volatile object.
20611    Accesses to X are "visible" to users.  */
20612 static int volatile x;
20613 x = 1;
20615 /* Access two ordinary objects via a volatile lvalue.
20616    It's not clear whether accesses to *P are "visible".  */
20617 int y;
20618 int *z = malloc (sizeof (int));
20619 int volatile *p;
20620 p = &y;
20621 *p = 1;
20622 p = z;
20623 *p = 1;
20624 @end example
20626 Programmers often wish that @code{volatile} meant ``Perform the memory
20627 access here and now, without merging several memory accesses, without
20628 changing the memory word size, and without reordering.''  But the C
20629 standard does not require this.  For objects defined with a volatile
20630 type, accesses must be done before the next sequence point; but
20631 otherwise merging, reordering, and word-size change is allowed.  Worse,
20632 it is not clear from the standard whether volatile lvalues provide more
20633 guarantees in general than nonvolatile lvalues, if the underlying
20634 objects are ordinary.
20636 Even when accessing objects defined with a volatile type,
20637 the C standard allows only
20638 extremely limited signal handlers: the behavior is undefined if a signal
20639 handler reads any nonlocal object, or writes to any nonlocal object
20640 whose type is not @code{sig_atomic_t volatile}, or calls any standard
20641 library function other than @code{abort}, @code{signal}, and (if C99)
20642 @code{_Exit}.  Hence C compilers need not worry about a signal handler
20643 disturbing ordinary computation, unless the computation accesses a
20644 @code{sig_atomic_t volatile} lvalue that is not a local variable.
20645 (There is an obscure exception for accesses via a pointer to a volatile
20646 character, since it may point into part of a @code{sig_atomic_t
20647 volatile} object.)  Posix
20648 adds to the list of library functions callable from a portable signal
20649 handler, but otherwise is like the C standard in this area.
20651 Some C implementations allow memory-access optimizations within each
20652 translation unit, such that actual behavior agrees with the behavior
20653 required by the standard only when calling a function in some other
20654 translation unit, and a signal handler acts like it was called from a
20655 different translation unit.  The C standard hints that in these
20656 implementations, objects referred to by signal handlers ``would require
20657 explicit specification of @code{volatile} storage, as well as other
20658 implementation-defined restrictions.''  But unfortunately even for this
20659 special case these other restrictions are often not documented well.
20660 @xref{Volatiles, , When is a Volatile Object Accessed?, gcc, Using the
20661 GNU Compiler Collection (GCC)}, for some
20662 restrictions imposed by GCC.  @xref{Defining Handlers, ,
20663 Defining Signal Handlers, libc, The GNU C Library}, for some
20664 restrictions imposed by the GNU C library.  Restrictions
20665 differ on other platforms.
20667 If possible, it is best to use a signal handler that fits within the
20668 limits imposed by the C and Posix standards.
20670 If this is not practical, you can try the following rules of thumb.  A
20671 signal handler should access only volatile lvalues, preferably lvalues
20672 that refer to objects defined with a volatile type, and should not
20673 assume that the accessed objects have an internally consistent state
20674 if they are larger than a machine word.  Furthermore, installers
20675 should employ compilers and compiler options that are commonly used
20676 for building operating system kernels, because kernels often need more
20677 from @code{volatile} than the C Standard requires, and installers who
20678 compile an application in a similar environment can sometimes benefit
20679 from the extra constraints imposed by kernels on compilers.
20680 Admittedly we are handwaving somewhat here, as there are few
20681 guarantees in this area; the rules of thumb may help to fix some bugs
20682 but there is a good chance that they will not fix them all.
20684 For @code{volatile}, C++ has the same problems that C does.
20685 Multithreaded applications have even more problems with @code{volatile},
20686 but they are beyond the scope of this section.
20688 The bottom line is that using @code{volatile} typically hurts
20689 performance but should not hurt correctness.  In some cases its use
20690 does help correctness, but these cases are often so poorly understood
20691 that all too often adding @code{volatile} to a data structure merely
20692 alleviates some symptoms of a bug while not fixing the bug in general.
20694 @node Floating Point Portability
20695 @section Floating Point Portability
20696 @cindex floating point
20698 Almost all modern systems use IEEE-754 floating point, and it is safe to
20699 assume IEEE-754 in most portable code these days.  For more information,
20700 please see David Goldberg's classic paper
20701 @uref{http://@/www.validlab.com/@/goldberg/@/paper.pdf, What Every Computer
20702 Scientist Should Know About Floating-Point Arithmetic}.
20704 @node Exiting Portably
20705 @section Exiting Portably
20706 @cindex exiting portably
20708 A C or C++ program can exit with status @var{N} by returning
20709 @var{N} from the @code{main} function.  Portable programs are supposed
20710 to exit either with status 0 or @code{EXIT_SUCCESS} to succeed, or with
20711 status @code{EXIT_FAILURE} to fail, but in practice it is portable to
20712 fail by exiting with status 1, and test programs that assume Posix can
20713 fail by exiting with status values from 1 through 255.  Programs on
20714 SunOS 2.0 (1985) through 3.5.2 (1988) incorrectly exited with zero
20715 status when @code{main} returned nonzero, but ancient systems like these
20716 are no longer of practical concern.
20718 A program can also exit with status @var{N} by passing @var{N} to the
20719 @code{exit} function, and a program can fail by calling the @code{abort}
20720 function.  If a program is specialized to just some platforms, it can fail
20721 by calling functions specific to those platforms, e.g., @code{_exit}
20722 (Posix) and @code{_Exit} (C99).  However, like other functions, an exit
20723 function should be declared, typically by including a header.  For
20724 example, if a C program calls @code{exit}, it should include @file{stdlib.h}
20725 either directly or via the default includes (@pxref{Default Includes}).
20727 A program can fail due to undefined behavior such as dereferencing a null
20728 pointer, but this is not recommended as undefined behavior allows an
20729 implementation to do whatever it pleases and this includes exiting
20730 successfully.
20733 @c ================================================== Manual Configuration
20735 @node Manual Configuration
20736 @chapter Manual Configuration
20738 A few kinds of features can't be guessed automatically by running test
20739 programs.  For example, the details of the object-file format, or
20740 special options that need to be passed to the compiler or linker.  You
20741 can check for such features using ad-hoc means, such as having
20742 @command{configure} check the output of the @code{uname} program, or
20743 looking for libraries that are unique to particular systems.  However,
20744 Autoconf provides a uniform method for handling unguessable features.
20746 @menu
20747 * Specifying Target Triplets::  Specifying target triplets
20748 * Canonicalizing::              Getting the canonical system type
20749 * Using System Type::           What to do with the system type
20750 @end menu
20752 @node Specifying Target Triplets
20753 @section Specifying target triplets
20754 @cindex System type
20755 @cindex Target triplet
20756 @c This node used to be named Specifying Names.  The @anchor allows old
20757 @c links to still work.
20758 @anchor{Specifying Names}
20760 Autoconf-generated
20761 @command{configure} scripts can make decisions based on a canonical name
20762 for the system type, or @dfn{target triplet}, which has the form:
20763 @samp{@var{cpu}-@var{vendor}-@var{os}}, where @var{os} can be
20764 @samp{@var{system}} or @samp{@var{kernel}-@var{system}}
20766 @command{configure} can usually guess the canonical name for the type of
20767 system it's running on.  To do so it runs a script called
20768 @command{config.guess}, which infers the name using the @code{uname}
20769 command or symbols predefined by the C preprocessor.
20771 Alternately, the user can specify the system type with command line
20772 arguments to @command{configure} (@pxref{System Type}.  Doing so is
20773 necessary when
20774 cross-compiling.  In the most complex case of cross-compiling, three
20775 system types are involved.  The options to specify them are:
20777 @table @option
20778 @item --build=@var{build-type}
20779 the type of system on which the package is being configured and
20780 compiled.  It defaults to the result of running @command{config.guess}.
20782 @item --host=@var{host-type}
20783 the type of system on which the package runs.  By default it is the
20784 same as the build machine.  Specifying it enables the cross-compilation
20785 mode.
20787 @item --target=@var{target-type}
20788 the type of system for which any compiler tools in the package
20789 produce code (rarely needed).  By default, it is the same as host.
20790 @end table
20792 If you mean to override the result of @command{config.guess}, use
20793 @option{--build}, not @option{--host}, since the latter enables
20794 cross-compilation.  For historical reasons,
20795 whenever you specify @option{--host},
20796 be sure to specify @option{--build} too; this will be fixed in the
20797 future.  So, to enter cross-compilation mode, use a command like this
20799 @example
20800 ./configure --build=i686-pc-linux-gnu --host=m68k-coff
20801 @end example
20803 @noindent
20804 Note that if you do not specify @option{--host}, @command{configure}
20805 fails if it can't run the code generated by the specified compiler.  For
20806 example, configuring as follows fails:
20808 @example
20809 ./configure CC=m68k-coff-gcc
20810 @end example
20812 When cross-compiling, @command{configure} will warn about any tools
20813 (compilers, linkers, assemblers) whose name is not prefixed with the
20814 host type.  This is an aid to users performing cross-compilation.
20815 Continuing the example above, if a cross-compiler named @command{cc} is
20816 used with a native @command{pkg-config}, then libraries found by
20817 @command{pkg-config} will likely cause subtle build failures; but using
20818 the names @command{m68k-coff-cc} and @command{m68k-coff-pkg-config}
20819 avoids any confusion.  Avoiding the warning is as simple as creating the
20820 correct symlinks naming the cross tools.
20822 @cindex @command{config.sub}
20823 @command{configure} recognizes short aliases for many system types; for
20824 example, @samp{decstation} can be used instead of
20825 @samp{mips-dec-ultrix4.2}.  @command{configure} runs a script called
20826 @command{config.sub} to canonicalize system type aliases.
20828 This section deliberately omits the description of the obsolete
20829 interface; see @ref{Hosts and Cross-Compilation}.
20832 @node Canonicalizing
20833 @section Getting the Canonical System Type
20834 @cindex System type
20835 @cindex Canonical system type
20837 The following macros make the system type available to @command{configure}
20838 scripts.
20840 @ovindex build_alias
20841 @ovindex host_alias
20842 @ovindex target_alias
20844 The variables @samp{build_alias}, @samp{host_alias}, and
20845 @samp{target_alias} are always exactly the arguments of @option{--build},
20846 @option{--host}, and @option{--target}; in particular, they are left empty
20847 if the user did not use them, even if the corresponding
20848 @code{AC_CANONICAL} macro was run.  Any configure script may use these
20849 variables anywhere.  These are the variables that should be used when in
20850 interaction with the user.
20852 If you need to recognize some special environments based on their system
20853 type, run the following macros to get canonical system names.  These
20854 variables are not set before the macro call.
20856 If you use these macros, you must distribute @command{config.guess} and
20857 @command{config.sub} along with your source code.  @xref{Output}, for
20858 information about the @code{AC_CONFIG_AUX_DIR} macro which you can use
20859 to control in which directory @command{configure} looks for those scripts.
20862 @defmac AC_CANONICAL_BUILD
20863 @acindex{CANONICAL_BUILD}
20864 @ovindex build
20865 @ovindex build_cpu
20866 @ovindex build_vendor
20867 @ovindex build_os
20868 Compute the canonical build-system type variable, @code{build}, and its
20869 three individual parts @code{build_cpu}, @code{build_vendor}, and
20870 @code{build_os}.
20872 If @option{--build} was specified, then @code{build} is the
20873 canonicalization of @code{build_alias} by @command{config.sub},
20874 otherwise it is determined by the shell script @command{config.guess}.
20875 @end defmac
20877 @defmac AC_CANONICAL_HOST
20878 @acindex{CANONICAL_HOST}
20879 @ovindex host
20880 @ovindex host_cpu
20881 @ovindex host_vendor
20882 @ovindex host_os
20883 Compute the canonical host-system type variable, @code{host}, and its
20884 three individual parts @code{host_cpu}, @code{host_vendor}, and
20885 @code{host_os}.
20887 If @option{--host} was specified, then @code{host} is the
20888 canonicalization of @code{host_alias} by @command{config.sub},
20889 otherwise it defaults to @code{build}.
20890 @end defmac
20892 @defmac AC_CANONICAL_TARGET
20893 @acindex{CANONICAL_TARGET}
20894 @ovindex target
20895 @ovindex target_cpu
20896 @ovindex target_vendor
20897 @ovindex target_os
20898 Compute the canonical target-system type variable, @code{target}, and its
20899 three individual parts @code{target_cpu}, @code{target_vendor}, and
20900 @code{target_os}.
20902 If @option{--target} was specified, then @code{target} is the
20903 canonicalization of @code{target_alias} by @command{config.sub},
20904 otherwise it defaults to @code{host}.
20905 @end defmac
20907 Note that there can be artifacts due to the backward compatibility
20908 code.  See @xref{Hosts and Cross-Compilation}, for more.
20910 @node Using System Type
20911 @section Using the System Type
20913 In @file{configure.ac} the system type is generally used by one or more
20914 @code{case} statements to select system-specifics.  Shell wildcards can
20915 be used to match a group of system types.
20917 For example, an extra assembler code object file could be chosen, giving
20918 access to a CPU cycle counter register.  @code{$(CYCLE_OBJ)} in the
20919 following would be used in a makefile to add the object to a
20920 program or library.
20922 @example
20923 AS_CASE([$host],
20924   [alpha*-*-*], [CYCLE_OBJ=rpcc.o],
20925   [i?86-*-*],   [CYCLE_OBJ=rdtsc.o],
20926   [CYCLE_OBJ=""]
20928 AC_SUBST([CYCLE_OBJ])
20929 @end example
20931 @code{AC_CONFIG_LINKS} (@pxref{Configuration Links}) is another good way
20932 to select variant source files, for example optimized code for some
20933 CPUs.  The configured CPU type doesn't always indicate exact CPU types,
20934 so some runtime capability checks may be necessary too.
20936 @example
20937 case $host in
20938   alpha*-*-*)   AC_CONFIG_LINKS([dither.c:alpha/dither.c]) ;;
20939   powerpc*-*-*) AC_CONFIG_LINKS([dither.c:powerpc/dither.c]) ;;
20940   *-*-*)        AC_CONFIG_LINKS([dither.c:generic/dither.c]) ;;
20941 esac
20942 @end example
20944 The host system type can also be used to find cross-compilation tools
20945 with @code{AC_CHECK_TOOL} (@pxref{Generic Programs}).
20947 The above examples all show @samp{$host}, since this is where the code
20948 is going to run.  Only rarely is it necessary to test @samp{$build}
20949 (which is where the build is being done).
20951 Whenever you're tempted to use @samp{$host} it's worth considering
20952 whether some sort of probe would be better.  New system types come along
20953 periodically or previously missing features are added.  Well-written
20954 probes can adapt themselves to such things, but hard-coded lists of
20955 names can't.  Here are some guidelines,
20957 @itemize @bullet
20958 @item
20959 Availability of libraries and library functions should always be checked
20960 by probing.
20961 @item
20962 Variant behavior of system calls is best identified with runtime tests
20963 if possible, but bug workarounds or obscure difficulties might have to
20964 be driven from @samp{$host}.
20965 @item
20966 Assembler code is inevitably highly CPU-specific and is best selected
20967 according to @samp{$host_cpu}.
20968 @item
20969 Assembler variations like underscore prefix on globals or ELF versus
20970 COFF type directives are however best determined by probing, perhaps
20971 even examining the compiler output.
20972 @end itemize
20974 @samp{$target} is for use by a package creating a compiler or similar.
20975 For ordinary packages it's meaningless and should not be used.  It
20976 indicates what the created compiler should generate code for, if it can
20977 cross-compile.  @samp{$target} generally selects various hard-coded CPU
20978 and system conventions, since usually the compiler or tools under
20979 construction themselves determine how the target works.
20982 @c ===================================================== Site Configuration.
20984 @node Site Configuration
20985 @chapter Site Configuration
20987 @command{configure} scripts support several kinds of local configuration
20988 decisions.  There are ways for users to specify where external software
20989 packages are, include or exclude optional features, install programs
20990 under modified names, and set default values for @command{configure}
20991 options.
20993 @menu
20994 * Help Formatting::             Customizing @samp{configure --help}
20995 * External Software::           Working with other optional software
20996 * Package Options::             Selecting optional features
20997 * Pretty Help Strings::         Formatting help string
20998 * Option Checking::             Controlling checking of @command{configure} options
20999 * Site Details::                Configuring site details
21000 * Transforming Names::          Changing program names when installing
21001 * Site Defaults::               Giving @command{configure} local defaults
21002 @end menu
21004 @node Help Formatting
21005 @section Controlling Help Output
21007 Users consult @samp{configure --help} to learn of configuration
21008 decisions specific to your package.  By default, @command{configure}
21009 breaks this output into sections for each type of option; within each
21010 section, help strings appear in the order @file{configure.ac} defines
21011 them:
21013 @example
21014 Optional Features:
21015   @dots{}
21016   --enable-bar            include bar
21018 Optional Packages:
21019   @dots{}
21020   --with-foo              use foo
21021 @end example
21023 @defmac AC_PRESERVE_HELP_ORDER
21024 @acindex{PRESERVE_HELP_ORDER}
21026 Request an alternate @option{--help} format, in which options of all
21027 types appear together, in the order defined.  Call this macro before any
21028 @code{AC_ARG_ENABLE} or @code{AC_ARG_WITH}.
21030 @example
21031 Optional Features and Packages:
21032   @dots{}
21033   --enable-bar            include bar
21034   --with-foo              use foo
21035 @end example
21037 @end defmac
21039 @node External Software
21040 @section Working With External Software
21041 @cindex External software
21043 Some packages require, or can optionally use, other software packages
21044 that are already installed.  The user can give @command{configure}
21045 command line options to specify which such external software to use.
21046 The options have one of these forms:
21048 @c FIXME: Can't use @ovar here, Texinfo 4.0 goes lunatic and emits something
21049 @c awful.
21050 @example
21051 --with-@var{package}@r{[}=@var{arg}@r{]}
21052 --without-@var{package}
21053 @end example
21055 For example, @option{--with-gnu-ld} means work with the GNU linker
21056 instead of some other linker.  @option{--with-x} means work with The X
21057 Window System.
21059 The user can give an argument by following the package name with
21060 @samp{=} and the argument.  Giving an argument of @samp{no} is for
21061 packages that are used by default; it says to @emph{not} use the
21062 package.  An argument that is neither @samp{yes} nor @samp{no} could
21063 include a name or number of a version of the other package, to specify
21064 more precisely which other package this program is supposed to work
21065 with.  If no argument is given, it defaults to @samp{yes}.
21066 @option{--without-@var{package}} is equivalent to
21067 @option{--with-@var{package}=no}.
21069 Normally @command{configure} scripts complain about
21070 @option{--with-@var{package}} options that they do not support.
21071 @xref{Option Checking}, for details, and for how to override the
21072 defaults.
21074 For each external software package that may be used, @file{configure.ac}
21075 should call @code{AC_ARG_WITH} to detect whether the @command{configure}
21076 user asked to use it.  Whether each package is used or not by default,
21077 and which arguments are valid, is up to you.
21079 @anchor{AC_ARG_WITH}
21080 @defmac AC_ARG_WITH (@var{package}, @var{help-string}, @
21081   @ovar{action-if-given}, @ovar{action-if-not-given})
21082 @acindex{ARG_WITH}
21083 If the user gave @command{configure} the option @option{--with-@var{package}}
21084 or @option{--without-@var{package}}, run shell commands
21085 @var{action-if-given}.  If neither option was given, run shell commands
21086 @var{action-if-not-given}.  The name @var{package} indicates another
21087 software package that this program should work with.  It should consist
21088 only of alphanumeric characters, dashes, plus signs, and dots.
21090 The option's argument is available to the shell commands
21091 @var{action-if-given} in the shell variable @code{withval}, which is
21092 actually just the value of the shell variable named
21093 @code{with_@var{package}}, with any non-alphanumeric characters in
21094 @var{package} changed into @samp{_}.  You may use that variable instead,
21095 if you wish.
21097 The argument @var{help-string} is a description of the option that
21098 looks like this:
21099 @example
21100   --with-readline         support fancy command line editing
21101 @end example
21103 @noindent
21104 @var{help-string} may be more than one line long, if more detail is
21105 needed.  Just make sure the columns line up in @samp{configure
21106 --help}.  Avoid tabs in the help string.  The easiest way to provide the
21107 proper leading whitespace is to format your @var{help-string} with the macro
21108 @code{AS_HELP_STRING} (@pxref{Pretty Help Strings}).
21110 The following example shows how to use the @code{AC_ARG_WITH} macro in
21111 a common situation.  You want to let the user decide whether to enable
21112 support for an external library (e.g., the readline library); if the user
21113 specified neither @option{--with-readline} nor @option{--without-readline},
21114 you want to enable support for readline only if the library is available
21115 on the system.
21117 @c FIXME: Remove AS_IF when the problem of AC_REQUIRE within `if' is solved.
21118 @example
21119 AC_ARG_WITH([readline],
21120   [AS_HELP_STRING([--with-readline],
21121     [support fancy command line editing @@<:@@default=check@@:>@@])],
21122   [],
21123   [with_readline=check])
21125 LIBREADLINE=
21126 AS_IF([test "x$with_readline" != xno],
21127   [AC_CHECK_LIB([readline], [main],
21128     [AC_SUBST([LIBREADLINE], ["-lreadline -lncurses"])
21129      AC_DEFINE([HAVE_LIBREADLINE], [1],
21130                [Define if you have libreadline])
21131     ],
21132     [if test "x$with_readline" != xcheck; then
21133        AC_MSG_FAILURE(
21134          [--with-readline was given, but test for readline failed])
21135      fi
21136     ], -lncurses)])
21137 @end example
21139 The next example shows how to use @code{AC_ARG_WITH} to give the user the
21140 possibility to enable support for the readline library, in case it is still
21141 experimental and not well tested, and is therefore disabled by default.
21143 @c FIXME: Remove AS_IF when the problem of AC_REQUIRE within `if' is solved.
21144 @example
21145 AC_ARG_WITH([readline],
21146   [AS_HELP_STRING([--with-readline],
21147     [enable experimental support for readline])],
21148   [],
21149   [with_readline=no])
21151 LIBREADLINE=
21152 AS_IF([test "x$with_readline" != xno],
21153   [AC_CHECK_LIB([readline], [main],
21154     [AC_SUBST([LIBREADLINE], ["-lreadline -lncurses"])
21155      AC_DEFINE([HAVE_LIBREADLINE], [1],
21156                [Define if you have libreadline])
21157     ],
21158     [AC_MSG_FAILURE(
21159        [--with-readline was given, but test for readline failed])],
21160     [-lncurses])])
21161 @end example
21163 The last example shows how to use @code{AC_ARG_WITH} to give the user the
21164 possibility to disable support for the readline library, given that it is
21165 an important feature and that it should be enabled by default.
21167 @c FIXME: Remove AS_IF when the problem of AC_REQUIRE within `if' is solved.
21168 @example
21169 AC_ARG_WITH([readline],
21170   [AS_HELP_STRING([--without-readline],
21171     [disable support for readline])],
21172   [],
21173   [with_readline=yes])
21175 LIBREADLINE=
21176 AS_IF([test "x$with_readline" != xno],
21177   [AC_CHECK_LIB([readline], [main],
21178     [AC_SUBST([LIBREADLINE], ["-lreadline -lncurses"])
21179      AC_DEFINE([HAVE_LIBREADLINE], [1],
21180                [Define if you have libreadline])
21181     ],
21182     [AC_MSG_FAILURE(
21183        [readline test failed (--without-readline to disable)])],
21184     [-lncurses])])
21185 @end example
21187 These three examples can be easily adapted to the case where
21188 @code{AC_ARG_ENABLE} should be preferred to @code{AC_ARG_WITH} (see
21189 @ref{Package Options}).
21190 @end defmac
21192 @node Package Options
21193 @section Choosing Package Options
21194 @cindex Package options
21195 @cindex Options, package
21197 If a software package has optional compile-time features, the user can
21198 give @command{configure} command line options to specify whether to
21199 compile them.  The options have one of these forms:
21201 @c FIXME: Can't use @ovar here, Texinfo 4.0 goes lunatic and emits something
21202 @c awful.
21203 @example
21204 --enable-@var{feature}@r{[}=@var{arg}@r{]}
21205 --disable-@var{feature}
21206 @end example
21208 These options allow users to choose which optional features to build and
21209 install.  @option{--enable-@var{feature}} options should never make a
21210 feature behave differently or cause one feature to replace another.
21211 They should only cause parts of the program to be built rather than left
21212 out.
21214 The user can give an argument by following the feature name with
21215 @samp{=} and the argument.  Giving an argument of @samp{no} requests
21216 that the feature @emph{not} be made available.  A feature with an
21217 argument looks like @option{--enable-debug=stabs}.  If no argument is
21218 given, it defaults to @samp{yes}.  @option{--disable-@var{feature}} is
21219 equivalent to @option{--enable-@var{feature}=no}.
21221 Normally @command{configure} scripts complain about
21222 @option{--enable-@var{package}} options that they do not support.
21223 @xref{Option Checking}, for details, and for how to override the
21224 defaults.
21226 For each optional feature, @file{configure.ac} should call
21227 @code{AC_ARG_ENABLE} to detect whether the @command{configure} user asked
21228 to include it.  Whether each feature is included or not by default, and
21229 which arguments are valid, is up to you.
21231 @anchor{AC_ARG_ENABLE}
21232 @defmac AC_ARG_ENABLE (@var{feature}, @var{help-string}, @
21233   @ovar{action-if-given}, @ovar{action-if-not-given})
21234 @acindex{ARG_ENABLE}
21235 If the user gave @command{configure} the option
21236 @option{--enable-@var{feature}} or @option{--disable-@var{feature}}, run
21237 shell commands @var{action-if-given}.  If neither option was given, run
21238 shell commands @var{action-if-not-given}.  The name @var{feature}
21239 indicates an optional user-level facility.  It should consist only of
21240 alphanumeric characters, dashes, plus signs, and dots.
21242 The option's argument is available to the shell commands
21243 @var{action-if-given} in the shell variable @code{enableval}, which is
21244 actually just the value of the shell variable named
21245 @code{enable_@var{feature}}, with any non-alphanumeric characters in
21246 @var{feature} changed into @samp{_}.  You may use that variable instead,
21247 if you wish.  The @var{help-string} argument is like that of
21248 @code{AC_ARG_WITH} (@pxref{External Software}).
21250 You should format your @var{help-string} with the macro
21251 @code{AS_HELP_STRING} (@pxref{Pretty Help Strings}).
21253 See the examples suggested with the definition of @code{AC_ARG_WITH}
21254 (@pxref{External Software}) to get an idea of possible applications of
21255 @code{AC_ARG_ENABLE}.
21256 @end defmac
21258 @node Pretty Help Strings
21259 @section Making Your Help Strings Look Pretty
21260 @cindex Help strings
21262 Properly formatting the @samp{help strings} which are used in
21263 @code{AC_ARG_WITH} (@pxref{External Software}) and @code{AC_ARG_ENABLE}
21264 (@pxref{Package Options}) can be challenging.  Specifically, you want
21265 your own @samp{help strings} to line up in the appropriate columns of
21266 @samp{configure --help} just like the standard Autoconf @samp{help
21267 strings} do.  This is the purpose of the @code{AS_HELP_STRING} macro.
21269 @anchor{AS_HELP_STRING}
21270 @defmac AS_HELP_STRING (@var{left-hand-side}, @var{right-hand-side} @
21271   @dvar{indent-column, 26}, @dvar{wrap-column, 79})
21272 @asindex{HELP_STRING}
21274 Expands into a help string that looks pretty when the user executes
21275 @samp{configure --help}.  It is typically used in @code{AC_ARG_WITH}
21276 (@pxref{External Software}) or @code{AC_ARG_ENABLE} (@pxref{Package
21277 Options}).  The following example makes this clearer.
21279 @example
21280 AC_ARG_WITH([foo],
21281   [AS_HELP_STRING([--with-foo],
21282      [use foo (default is no)])],
21283   [use_foo=$withval],
21284   [use_foo=no])
21285 @end example
21287 Then the last few lines of @samp{configure --help} appear like
21288 this:
21290 @example
21291 --enable and --with options recognized:
21292   --with-foo              use foo (default is no)
21293 @end example
21295 Macro expansion is performed on the first argument.  However, the second
21296 argument of @code{AS_HELP_STRING} is treated as a whitespace separated
21297 list of text to be reformatted, and is not subject to macro expansion.
21298 Since it is not expanded, it should not be double quoted.
21299 @xref{Autoconf Language}, for a more detailed explanation.
21301 The @code{AS_HELP_STRING} macro is particularly helpful when the
21302 @var{left-hand-side} and/or @var{right-hand-side} are composed of macro
21303 arguments, as shown in the following example.  Be aware that
21304 @var{left-hand-side} may not expand to unbalanced quotes,
21305 although quadrigraphs can be used.
21307 @example
21308 AC_DEFUN([MY_ARG_WITH],
21309   [AC_ARG_WITH(m4_translit([[$1]], [_], [-]),
21310      [AS_HELP_STRING([--with-m4_translit([$1], [_], [-])],
21311                      [use $1 (default is $2)])],
21312      [use_[]$1=$withval],
21313      [use_[]$1=$2])])
21314 MY_ARG_WITH([a_b], [no])
21315 @end example
21316 @noindent
21317 Here, the last few lines of @samp{configure --help} will include:
21319 @example
21320 --enable and --with options recognized:
21321   --with-a-b              use a_b (default is no)
21322 @end example
21324 The parameters @var{indent-column} and @var{wrap-column} were introduced
21325 in Autoconf 2.62.  Generally, they should not be specified; they exist
21326 for fine-tuning of the wrapping.
21327 @example
21328 AS_HELP_STRING([--option], [description of option])
21329 @result{}  --option                description of option
21330 AS_HELP_STRING([--option], [description of option], [15], [30])
21331 @result{}  --option     description of
21332 @result{}               option
21333 @end example
21334 @end defmac
21337 @node Option Checking
21338 @section Controlling Checking of @command{configure} Options
21339 @cindex Options, Package
21341 The @command{configure} script checks its command-line options against a
21342 list of known options, like @option{--help} or @option{--config-cache}.
21343 An unknown option ordinarily indicates a mistake by the user and
21344 @command{configure} halts with an error.  However, by default unknown
21345 @option{--with-@var{package}} and @option{--enable-@var{feature}}
21346 options elicit only a warning, to support configuring entire source
21347 trees.
21349 Source trees often contain multiple packages with a top-level
21350 @command{configure} script that uses the @code{AC_CONFIG_SUBDIRS} macro
21351 (@pxref{Subdirectories}).  Because the packages generally support
21352 different @option{--with-@var{package}} and
21353 @option{--enable-@var{feature}} options, the GNU Coding
21354 Standards say they must accept unrecognized options without halting.
21355 Even a warning message is undesirable here, so @code{AC_CONFIG_SUBDIRS}
21356 automatically disables the warnings.
21358 This default behavior may be modified in two ways.  First, the installer
21359 can invoke @code{configure --disable-option-checking} to disable
21360 these warnings, or invoke @code{configure --enable-option-checking=fatal}
21361 options to turn them into fatal errors, respectively.  Second, the
21362 maintainer can use @code{AC_DISABLE_OPTION_CHECKING}.
21364 @defmac AC_DISABLE_OPTION_CHECKING
21365 @acindex{DISABLE_OPTION_CHECKING}
21367 By default, disable warnings related to any unrecognized
21368 @option{--with-@var{package}} or @option{--enable-@var{feature}}
21369 options.  This is implied by @code{AC_CONFIG_SUBDIRS}.
21371 The installer can override this behavior by passing
21372 @option{--enable-option-checking} (enable warnings) or
21373 @option{--enable-option-checking=fatal} (enable errors) to
21374 @command{configure}.
21375 @end defmac
21378 @node Site Details
21379 @section Configuring Site Details
21380 @cindex Site details
21382 Some software packages require complex site-specific information.  Some
21383 examples are host names to use for certain services, company names, and
21384 email addresses to contact.  Since some configuration scripts generated
21385 by Metaconfig ask for such information interactively, people sometimes
21386 wonder how to get that information in Autoconf-generated configuration
21387 scripts, which aren't interactive.
21389 Such site configuration information should be put in a file that is
21390 edited @emph{only by users}, not by programs.  The location of the file
21391 can either be based on the @code{prefix} variable, or be a standard
21392 location such as the user's home directory.  It could even be specified
21393 by an environment variable.  The programs should examine that file at
21394 runtime, rather than at compile time.  Runtime configuration is more
21395 convenient for users and makes the configuration process simpler than
21396 getting the information while configuring.  @xref{Directory Variables, ,
21397 Variables for Installation Directories, standards, The GNU Coding
21398 Standards}, for more information on where to put data files.
21400 @node Transforming Names
21401 @section Transforming Program Names When Installing
21402 @cindex Transforming program names
21403 @cindex Program names, transforming
21405 Autoconf supports changing the names of programs when installing them.
21406 In order to use these transformations, @file{configure.ac} must call the
21407 macro @code{AC_ARG_PROGRAM}.
21409 @defmac AC_ARG_PROGRAM
21410 @acindex{ARG_PROGRAM}
21411 @ovindex program_transform_name
21412 Place in output variable @code{program_transform_name} a sequence of
21413 @code{sed} commands for changing the names of installed programs.
21415 If any of the options described below are given to @command{configure},
21416 program names are transformed accordingly.  Otherwise, if
21417 @code{AC_CANONICAL_TARGET} has been called and a @option{--target} value
21418 is given, the target type followed by a dash is used as a prefix.
21419 Otherwise, no program name transformation is done.
21420 @end defmac
21422 @menu
21423 * Transformation Options::      @command{configure} options to transform names
21424 * Transformation Examples::     Sample uses of transforming names
21425 * Transformation Rules::        Makefile uses of transforming names
21426 @end menu
21428 @node Transformation Options
21429 @subsection Transformation Options
21431 You can specify name transformations by giving @command{configure} these
21432 command line options:
21434 @table @option
21435 @item --program-prefix=@var{prefix}
21436 prepend @var{prefix} to the names;
21438 @item --program-suffix=@var{suffix}
21439 append @var{suffix} to the names;
21441 @item --program-transform-name=@var{expression}
21442 perform @code{sed} substitution @var{expression} on the names.
21443 @end table
21445 @node Transformation Examples
21446 @subsection Transformation Examples
21448 These transformations are useful with programs that can be part of a
21449 cross-compilation development environment.  For example, a
21450 cross-assembler running on a Sun 4 configured with
21451 @option{--target=i960-vxworks} is normally installed as
21452 @file{i960-vxworks-as}, rather than @file{as}, which could be confused
21453 with a native Sun 4 assembler.
21455 You can force a program name to begin with @file{g}, if you don't want
21456 GNU programs installed on your system to shadow other programs with
21457 the same name.  For example, if you configure GNU @code{diff} with
21458 @option{--program-prefix=g}, then when you run @samp{make install} it is
21459 installed as @file{/usr/local/bin/gdiff}.
21461 As a more sophisticated example, you could use
21463 @example
21464 --program-transform-name='s/^/g/; s/^gg/g/; s/^gless/less/'
21465 @end example
21466 @noindent
21468 to prepend @samp{g} to most of the program names in a source tree,
21469 excepting those like @code{gdb} that already have one and those like
21470 @code{less} and @code{lesskey} that aren't GNU programs.  (That is
21471 assuming that you have a source tree containing those programs that is
21472 set up to use this feature.)
21474 One way to install multiple versions of some programs simultaneously is
21475 to append a version number to the name of one or both.  For example, if
21476 you want to keep Autoconf version 1 around for awhile, you can configure
21477 Autoconf version 2 using @option{--program-suffix=2} to install the
21478 programs as @file{/usr/local/bin/autoconf2},
21479 @file{/usr/local/bin/autoheader2}, etc.  Nevertheless, pay attention
21480 that only the binaries are renamed, therefore you'd have problems with
21481 the library files which might overlap.
21483 @node Transformation Rules
21484 @subsection Transformation Rules
21486 Here is how to use the variable @code{program_transform_name} in a
21487 @file{Makefile.in}:
21489 @example
21490 PROGRAMS = cp ls rm
21491 transform = @@program_transform_name@@
21492 install:
21493         for p in $(PROGRAMS); do \
21494           $(INSTALL_PROGRAM) $$p $(DESTDIR)$(bindir)/`echo $$p | \
21495                                               sed '$(transform)'`; \
21496         done
21498 uninstall:
21499         for p in $(PROGRAMS); do \
21500           rm -f $(DESTDIR)$(bindir)/`echo $$p | sed '$(transform)'`; \
21501 @c $$ restore font-lock
21502         done
21503 @end example
21505 It is guaranteed that @code{program_transform_name} is never empty, and
21506 that there are no useless separators.  Therefore you may safely embed
21507 @code{program_transform_name} within a sed program using @samp{;}:
21509 @example
21510 transform = @@program_transform_name@@
21511 transform_exe = s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/
21512 @end example
21514 Whether to do the transformations on documentation files (Texinfo or
21515 @code{man}) is a tricky question; there seems to be no perfect answer,
21516 due to the several reasons for name transforming.  Documentation is not
21517 usually particular to a specific architecture, and Texinfo files do not
21518 conflict with system documentation.  But they might conflict with
21519 earlier versions of the same files, and @code{man} pages sometimes do
21520 conflict with system documentation.  As a compromise, it is probably
21521 best to do name transformations on @code{man} pages but not on Texinfo
21522 manuals.
21524 @node Site Defaults
21525 @section Setting Site Defaults
21526 @cindex Site defaults
21527 @cindex config.site
21529 Autoconf-generated @command{configure} scripts allow your site to provide
21530 default values for some configuration values.  You do this by creating
21531 site- and system-wide initialization files.
21533 @evindex CONFIG_SITE
21534 If the environment variable @code{CONFIG_SITE} is set, @command{configure}
21535 uses its value as the name of a shell script to read; it is recommended
21536 that this be an absolute file name.  Otherwise, it
21537 reads the shell script @file{@var{prefix}/share/config.site} if it exists,
21538 then @file{@var{prefix}/etc/config.site} if it exists.  Thus,
21539 settings in machine-specific files override those in machine-independent
21540 ones in case of conflict.
21542 Site files can be arbitrary shell scripts, but only certain kinds of
21543 code are really appropriate to be in them.  Because @command{configure}
21544 reads any cache file after it has read any site files, a site file can
21545 define a default cache file to be shared between all Autoconf-generated
21546 @command{configure} scripts run on that system (@pxref{Cache Files}).  If
21547 you set a default cache file in a site file, it is a good idea to also
21548 set the output variable @code{CC} in that site file, because the cache
21549 file is only valid for a particular compiler, but many systems have
21550 several available.
21552 You can examine or override the value set by a command line option to
21553 @command{configure} in a site file; options set shell variables that have
21554 the same names as the options, with any dashes turned into underscores.
21555 The exceptions are that @option{--without-} and @option{--disable-} options
21556 are like giving the corresponding @option{--with-} or @option{--enable-}
21557 option and the value @samp{no}.  Thus, @option{--cache-file=localcache}
21558 sets the variable @code{cache_file} to the value @samp{localcache};
21559 @option{--enable-warnings=no} or @option{--disable-warnings} sets the variable
21560 @code{enable_warnings} to the value @samp{no}; @option{--prefix=/usr} sets the
21561 variable @code{prefix} to the value @samp{/usr}; etc.
21563 Site files are also good places to set default values for other output
21564 variables, such as @code{CFLAGS}, if you need to give them non-default
21565 values: anything you would normally do, repetitively, on the command
21566 line.  If you use non-default values for @var{prefix} or
21567 @var{exec_prefix} (wherever you locate the site file), you can set them
21568 in the site file if you specify it with the @code{CONFIG_SITE}
21569 environment variable.
21571 You can set some cache values in the site file itself.  Doing this is
21572 useful if you are cross-compiling, where it is impossible to check features
21573 that require running a test program.  You could ``prime the cache'' by
21574 setting those values correctly for that system in
21575 @file{@var{prefix}/etc/config.site}.  To find out the names of the cache
21576 variables you need to set, see the documentation of the respective
21577 Autoconf macro.  If the variables or their semantics are undocumented,
21578 you may need to look for shell variables with @samp{_cv_} in their names
21579 in the affected @command{configure} scripts, or in the Autoconf M4
21580 source code for those macros; but in that case, their name or semantics
21581 may change in a future Autoconf version.
21583 The cache file is careful to not override any variables set in the site
21584 files.  Similarly, you should not override command-line options in the
21585 site files.  Your code should check that variables such as @code{prefix}
21586 and @code{cache_file} have their default values (as set near the top of
21587 @command{configure}) before changing them.
21589 Here is a sample file @file{/usr/share/local/@/gnu/share/@/config.site}.  The
21590 command @samp{configure --prefix=/usr/share/local/gnu} would read this
21591 file (if @code{CONFIG_SITE} is not set to a different file).
21593 @example
21594 # /usr/share/local/gnu/share/config.site for configure
21596 # Change some defaults.
21597 test "$prefix" = NONE && prefix=/usr/share/local/gnu
21598 test "$exec_prefix" = NONE && exec_prefix=/usr/local/gnu
21599 test "$sharedstatedir" = '$@{prefix@}/com' && sharedstatedir=/var
21600 test "$localstatedir" = '$@{prefix@}/var' && localstatedir=/var
21602 # Give Autoconf 2.x generated configure scripts a shared default
21603 # cache file for feature test results, architecture-specific.
21604 if test "$cache_file" = /dev/null; then
21605   cache_file="$prefix/var/config.cache"
21606   # A cache file is only valid for one C compiler.
21607   CC=gcc
21609 @end example
21611 @cindex Filesystem Hierarchy Standard
21612 @cindex FHS
21614 Another use of @file{config.site} is for priming the directory variables
21615 in a manner consistent with the Filesystem Hierarchy Standard
21616 (FHS).  Once the following file is installed at
21617 @file{/usr/share/config.site}, a user can execute simply
21618 @code{./configure --prefix=/usr} to get all the directories chosen in
21619 the locations recommended by FHS.
21621 @example
21622 # /usr/share/config.site for FHS defaults when installing below /usr,
21623 # and the respective settings were not changed on the command line.
21624 if test "$prefix" = /usr; then
21625   test "$sysconfdir" = '$@{prefix@}/etc' && sysconfdir=/etc
21626   test "$sharedstatedir" = '$@{prefix@}/com' && sharedstatedir=/var
21627   test "$localstatedir" = '$@{prefix@}/var' && localstatedir=/var
21629 @end example
21631 @cindex lib64
21632 @cindex 64-bit libraries
21633 Likewise, on platforms where 64-bit libraries are built by default, then
21634 installed in @file{/usr/local/@/lib64} instead of @file{/usr/local/@/lib},
21635 it is appropriate to install @file{/usr/local/@/share/config.site}:
21637 @example
21638 # /usr/local/share/config.site for platforms that prefer
21639 # the directory /usr/local/lib64 over /usr/local/lib.
21640 test "$libdir" = '$@{exec_prefix@}/lib' && libdir='$@{exec_prefix@}/lib64'
21641 @end example
21644 @c ============================================== Running configure Scripts.
21646 @node Running configure Scripts
21647 @chapter Running @command{configure} Scripts
21648 @cindex @command{configure}
21650 Below are instructions on how to configure a package that uses a
21651 @command{configure} script, suitable for inclusion as an @file{INSTALL}
21652 file in the package.  A plain-text version of @file{INSTALL} which you
21653 may use comes with Autoconf.
21655 @menu
21656 * Basic Installation::          Instructions for typical cases
21657 * Compilers and Options::       Selecting compilers and optimization
21658 * Multiple Architectures::      Compiling for multiple architectures at once
21659 * Installation Names::          Installing in different directories
21660 * Optional Features::           Selecting optional features
21661 * Particular Systems::          Particular systems
21662 * System Type::                 Specifying the system type
21663 * Sharing Defaults::            Setting site-wide defaults for @command{configure}
21664 * Defining Variables::          Specifying the compiler etc.
21665 * configure Invocation::        Changing how @command{configure} runs
21666 @end menu
21668 @set autoconf
21669 @include install.texi
21672 @c ============================================== config.status Invocation
21674 @node config.status Invocation
21675 @chapter config.status Invocation
21676 @cindex @command{config.status}
21678 The @command{configure} script creates a file named @file{config.status},
21679 which actually configures, @dfn{instantiates}, the template files.  It
21680 also records the configuration options that were specified when the
21681 package was last configured in case reconfiguring is needed.
21683 Synopsis:
21684 @example
21685 ./config.status @ovar{option}@dots{} @ovar{tag}@dots{}
21686 @end example
21688 It configures each @var{tag}; if none are specified, all the templates
21689 are instantiated.  A @var{tag} refers to a file or other tag associated
21690 with a configuration action, as specified by an @code{AC_CONFIG_@var{ITEMS}}
21691 macro (@pxref{Configuration Actions}).  The files must be specified
21692 without their dependencies, as in
21694 @example
21695 ./config.status foobar
21696 @end example
21698 @noindent
21701 @example
21702 ./config.status foobar:foo.in:bar.in
21703 @end example
21705 The supported options are:
21707 @table @option
21708 @item --help
21709 @itemx -h
21710 Print a summary of the command line options, the list of the template
21711 files, and exit.
21713 @item --version
21714 @itemx -V
21715 Print the version number of Autoconf and the configuration settings,
21716 and exit.
21718 @item --config
21719 Print the configuration settings in reusable way, quoted for the shell,
21720 and exit.  For example, for a debugging build that otherwise reuses the
21721 configuration from a different build directory @var{build-dir} of a
21722 package in @var{src-dir}, you could use the following:
21724 @example
21725 args=`@var{build-dir}/config.status --config`
21726 eval @var{src-dir}/configure "$args" CFLAGS=-g --srcdir=@var{src-dir}
21727 @end example
21729 @noindent
21730 Note that it may be necessary to override a @option{--srcdir} setting
21731 that was saved in the configuration, if the arguments are used in a
21732 different build directory.
21734 @item --silent
21735 @itemx --quiet
21736 @itemx -q
21737 Do not print progress messages.
21739 @item --debug
21740 @itemx -d
21741 Don't remove the temporary files.
21743 @item --file=@var{file}[:@var{template}]
21744 Require that @var{file} be instantiated as if
21745 @samp{AC_CONFIG_FILES(@var{file}:@var{template})} was used.  Both
21746 @var{file} and @var{template} may be @samp{-} in which case the standard
21747 output and/or standard input, respectively, is used.  If a
21748 @var{template} file name is relative, it is first looked for in the build
21749 tree, and then in the source tree.  @xref{Configuration Actions}, for
21750 more details.
21752 This option and the following ones provide one way for separately
21753 distributed packages to share the values computed by @command{configure}.
21754 Doing so can be useful if some of the packages need a superset of the
21755 features that one of them, perhaps a common library, does.  These
21756 options allow a @file{config.status} file to create files other than the
21757 ones that its @file{configure.ac} specifies, so it can be used for a
21758 different package, or for extracting a subset of values.  For example,
21760 @example
21761 echo '@@CC@@' | ./config.status --file=-
21762 @end example
21764 @noindent
21765 provides the value of @code{@@CC@@} on standard output.
21767 @item --header=@var{file}[:@var{template}]
21768 Same as @option{--file} above, but with @samp{AC_CONFIG_HEADERS}.
21770 @item --recheck
21771 Ask @file{config.status} to update itself and exit (no instantiation).
21772 This option is useful if you change @command{configure}, so that the
21773 results of some tests might be different from the previous run.  The
21774 @option{--recheck} option reruns @command{configure} with the same arguments
21775 you used before, plus the @option{--no-create} option, which prevents
21776 @command{configure} from running @file{config.status} and creating
21777 @file{Makefile} and other files, and the @option{--no-recursion} option,
21778 which prevents @command{configure} from running other @command{configure}
21779 scripts in subdirectories.  (This is so other Make rules can
21780 run @file{config.status} when it changes; @pxref{Automatic Remaking},
21781 for an example).
21782 @end table
21784 @file{config.status} checks several optional environment variables that
21785 can alter its behavior:
21787 @anchor{CONFIG_SHELL}
21788 @defvar CONFIG_SHELL
21789 @evindex CONFIG_SHELL
21790 The shell with which to run @command{configure} for the @option{--recheck}
21791 option.  It must be Bourne-compatible.  The default is a shell that
21792 supports @code{LINENO} if available, and @file{/bin/sh} otherwise.
21793 Invoking @command{configure} by hand bypasses this setting, so you may
21794 need to use a command like @samp{CONFIG_SHELL=/bin/bash /bin/bash ./configure}
21795 to insure that the same shell is used everywhere.  The absolute name of the
21796 shell should be passed.
21797 @end defvar
21799 @defvar CONFIG_STATUS
21800 @evindex CONFIG_STATUS
21801 The file name to use for the shell script that records the
21802 configuration.  The default is @file{./config.status}.  This variable is
21803 useful when one package uses parts of another and the @command{configure}
21804 scripts shouldn't be merged because they are maintained separately.
21805 @end defvar
21807 You can use @file{./config.status} in your makefiles.  For example, in
21808 the dependencies given above (@pxref{Automatic Remaking}),
21809 @file{config.status} is run twice when @file{configure.ac} has changed.
21810 If that bothers you, you can make each run only regenerate the files for
21811 that rule:
21812 @example
21813 @group
21814 config.h: stamp-h
21815 stamp-h: config.h.in config.status
21816         ./config.status config.h
21817         echo > stamp-h
21819 Makefile: Makefile.in config.status
21820         ./config.status Makefile
21821 @end group
21822 @end example
21824 The calling convention of @file{config.status} has changed; see
21825 @ref{Obsolete config.status Use}, for details.
21828 @c =================================================== Obsolete Constructs
21830 @node Obsolete Constructs
21831 @chapter Obsolete Constructs
21832 @cindex Obsolete constructs
21834 Autoconf changes, and throughout the years some constructs have been
21835 obsoleted.  Most of the changes involve the macros, but in some cases
21836 the tools themselves, or even some concepts, are now considered
21837 obsolete.
21839 You may completely skip this chapter if you are new to Autoconf.  Its
21840 intention is mainly to help maintainers updating their packages by
21841 understanding how to move to more modern constructs.
21843 @menu
21844 * Obsolete config.status Use::  Obsolete convention for @command{config.status}
21845 * acconfig Header::             Additional entries in @file{config.h.in}
21846 * autoupdate Invocation::       Automatic update of @file{configure.ac}
21847 * Obsolete Macros::             Backward compatibility macros
21848 * Autoconf 1::                  Tips for upgrading your files
21849 * Autoconf 2.13::               Some fresher tips
21850 @end menu
21852 @node Obsolete config.status Use
21853 @section Obsolete @file{config.status} Invocation
21855 @file{config.status} now supports arguments to specify the files to
21856 instantiate; see @ref{config.status Invocation}, for more details.
21857 Before, environment variables had to be used.
21859 @defvar CONFIG_COMMANDS
21860 @evindex CONFIG_COMMANDS
21861 The tags of the commands to execute.  The default is the arguments given
21862 to @code{AC_OUTPUT} and @code{AC_CONFIG_COMMANDS} in
21863 @file{configure.ac}.
21864 @end defvar
21866 @defvar CONFIG_FILES
21867 @evindex CONFIG_FILES
21868 The files in which to perform @samp{@@@var{variable}@@} substitutions.
21869 The default is the arguments given to @code{AC_OUTPUT} and
21870 @code{AC_CONFIG_FILES} in @file{configure.ac}.
21871 @end defvar
21873 @defvar CONFIG_HEADERS
21874 @evindex CONFIG_HEADERS
21875 The files in which to substitute C @code{#define} statements.  The
21876 default is the arguments given to @code{AC_CONFIG_HEADERS}; if that
21877 macro was not called, @file{config.status} ignores this variable.
21878 @end defvar
21880 @defvar CONFIG_LINKS
21881 @evindex CONFIG_LINKS
21882 The symbolic links to establish.  The default is the arguments given to
21883 @code{AC_CONFIG_LINKS}; if that macro was not called,
21884 @file{config.status} ignores this variable.
21885 @end defvar
21887 In @ref{config.status Invocation}, using this old interface, the example
21888 would be:
21890 @example
21891 @group
21892 config.h: stamp-h
21893 stamp-h: config.h.in config.status
21894         CONFIG_COMMANDS= CONFIG_LINKS= CONFIG_FILES= \
21895           CONFIG_HEADERS=config.h ./config.status
21896         echo > stamp-h
21898 Makefile: Makefile.in config.status
21899         CONFIG_COMMANDS= CONFIG_LINKS= CONFIG_HEADERS= \
21900           CONFIG_FILES=Makefile ./config.status
21901 @end group
21902 @end example
21904 @noindent
21905 (If @file{configure.ac} does not call @code{AC_CONFIG_HEADERS}, there is
21906 no need to set @code{CONFIG_HEADERS} in the @command{make} rules.  Equally
21907 for @code{CONFIG_COMMANDS}, etc.)
21910 @node acconfig Header
21911 @section @file{acconfig.h}
21913 @cindex @file{acconfig.h}
21914 @cindex @file{config.h.top}
21915 @cindex @file{config.h.bot}
21917 In order to produce @file{config.h.in}, @command{autoheader} needs to
21918 build or to find templates for each symbol.  Modern releases of Autoconf
21919 use @code{AH_VERBATIM} and @code{AH_TEMPLATE} (@pxref{Autoheader
21920 Macros}), but in older releases a file, @file{acconfig.h}, contained the
21921 list of needed templates.  @command{autoheader} copied comments and
21922 @code{#define} and @code{#undef} statements from @file{acconfig.h} in
21923 the current directory, if present.  This file used to be mandatory if
21924 you @code{AC_DEFINE} any additional symbols.
21926 Modern releases of Autoconf also provide @code{AH_TOP} and
21927 @code{AH_BOTTOM} if you need to prepend/append some information to
21928 @file{config.h.in}.  Ancient versions of Autoconf had a similar feature:
21929 if @file{./acconfig.h} contains the string @samp{@@TOP@@},
21930 @command{autoheader} copies the lines before the line containing
21931 @samp{@@TOP@@} into the top of the file that it generates.  Similarly,
21932 if @file{./acconfig.h} contains the string @samp{@@BOTTOM@@},
21933 @command{autoheader} copies the lines after that line to the end of the
21934 file it generates.  Either or both of those strings may be omitted.  An
21935 even older alternate way to produce the same effect in ancient versions
21936 of Autoconf is to create the files @file{@var{file}.top} (typically
21937 @file{config.h.top}) and/or @file{@var{file}.bot} in the current
21938 directory.  If they exist, @command{autoheader} copies them to the
21939 beginning and end, respectively, of its output.
21941 In former versions of Autoconf, the files used in preparing a software
21942 package for distribution were:
21943 @example
21944 @group
21945 configure.ac --.   .------> autoconf* -----> configure
21946                +---+
21947 [aclocal.m4] --+   `---.
21948 [acsite.m4] ---'       |
21949                        +--> [autoheader*] -> [config.h.in]
21950 [acconfig.h] ----.     |
21951                  +-----'
21952 [config.h.top] --+
21953 [config.h.bot] --'
21954 @end group
21955 @end example
21957 Using only the @code{AH_} macros, @file{configure.ac} should be
21958 self-contained, and should not depend upon @file{acconfig.h} etc.
21961 @node autoupdate Invocation
21962 @section Using @command{autoupdate} to Modernize @file{configure.ac}
21963 @cindex @command{autoupdate}
21965 The @command{autoupdate} program updates a @file{configure.ac} file that
21966 calls Autoconf macros by their old names to use the current macro names.
21967 In version 2 of Autoconf, most of the macros were renamed to use a more
21968 uniform and descriptive naming scheme.  @xref{Macro Names}, for a
21969 description of the new scheme.  Although the old names still work
21970 (@pxref{Obsolete Macros}, for a list of the old macros and the corresponding
21971 new names), you can make your @file{configure.ac} files more readable
21972 and make it easier to use the current Autoconf documentation if you
21973 update them to use the new macro names.
21975 @evindex SIMPLE_BACKUP_SUFFIX
21976 If given no arguments, @command{autoupdate} updates @file{configure.ac},
21977 backing up the original version with the suffix @file{~} (or the value
21978 of the environment variable @code{SIMPLE_BACKUP_SUFFIX}, if that is
21979 set).  If you give @command{autoupdate} an argument, it reads that file
21980 instead of @file{configure.ac} and writes the updated file to the
21981 standard output.
21983 @noindent
21984 @command{autoupdate} accepts the following options:
21986 @table @option
21987 @item --help
21988 @itemx -h
21989 Print a summary of the command line options and exit.
21991 @item --version
21992 @itemx -V
21993 Print the version number of Autoconf and exit.
21995 @item --verbose
21996 @itemx -v
21997 Report processing steps.
21999 @item --debug
22000 @itemx -d
22001 Don't remove the temporary files.
22003 @item --force
22004 @itemx -f
22005 Force the update even if the file has not changed.  Disregard the cache.
22007 @item --include=@var{dir}
22008 @itemx -I @var{dir}
22009 Also look for input files in @var{dir}.  Multiple invocations accumulate.
22010 Directories are browsed from last to first.
22012 @item --prepend-include=@var{dir}
22013 @itemx -B @var{dir}
22014 Prepend directory @var{dir} to the search path.  This is used to include
22015 the language-specific files before any third-party macros.
22016 @end table
22018 @node Obsolete Macros
22019 @section Obsolete Macros
22021 Several macros are obsoleted in Autoconf, for various reasons (typically
22022 they failed to quote properly, couldn't be extended for more recent
22023 issues, etc.).  They are still supported, but deprecated: their use
22024 should be avoided.
22026 During the jump from Autoconf version 1 to version 2, most of the
22027 macros were renamed to use a more uniform and descriptive naming scheme,
22028 but their signature did not change.  @xref{Macro Names}, for a
22029 description of the new naming scheme.  Below, if there is just the mapping
22030 from old names to new names for these macros, the reader is invited to
22031 refer to the definition of the new macro for the signature and the
22032 description.
22034 @defmac AC_AIX
22035 @acindex{AIX}
22036 @cvindex _ALL_SOURCE
22037 This macro is a platform-specific subset of
22038 @code{AC_USE_SYSTEM_EXTENSIONS} (@pxref{AC_USE_SYSTEM_EXTENSIONS}).
22039 @end defmac
22041 @defmac AC_ALLOCA
22042 @acindex{ALLOCA}
22043 Replaced by @code{AC_FUNC_ALLOCA} (@pxref{AC_FUNC_ALLOCA}).
22044 @end defmac
22046 @defmac AC_ARG_ARRAY
22047 @acindex{ARG_ARRAY}
22048 Removed because of limited usefulness.
22049 @end defmac
22051 @defmac AC_C_CROSS
22052 @acindex{C_CROSS}
22053 This macro is obsolete; it does nothing.
22054 @end defmac
22056 @defmac AC_C_LONG_DOUBLE
22057 @acindex{C_LONG_DOUBLE}
22058 @cvindex HAVE_LONG_DOUBLE
22059 If the C compiler supports a working @code{long double} type with more
22060 range or precision than the @code{double} type, define
22061 @code{HAVE_LONG_DOUBLE}.
22063 You should use @code{AC_TYPE_LONG_DOUBLE} or
22064 @code{AC_TYPE_LONG_DOUBLE_WIDER} instead.  @xref{Particular Types}.
22065 @end defmac
22067 @defmac AC_CANONICAL_SYSTEM
22068 @acindex{CANONICAL_SYSTEM}
22069 Determine the system type and set output variables to the names of the
22070 canonical system types.  @xref{Canonicalizing}, for details about the
22071 variables this macro sets.
22073 The user is encouraged to use either @code{AC_CANONICAL_BUILD}, or
22074 @code{AC_CANONICAL_HOST}, or @code{AC_CANONICAL_TARGET}, depending on
22075 the needs.  Using @code{AC_CANONICAL_TARGET} is enough to run the two
22076 other macros (@pxref{Canonicalizing}).
22077 @end defmac
22079 @defmac AC_CHAR_UNSIGNED
22080 @acindex{CHAR_UNSIGNED}
22081 Replaced by @code{AC_C_CHAR_UNSIGNED} (@pxref{AC_C_CHAR_UNSIGNED}).
22082 @end defmac
22084 @defmac AC_CHECK_TYPE (@var{type}, @var{default})
22085 @acindex{CHECK_TYPE}
22086 Autoconf, up to 2.13, used to provide this version of
22087 @code{AC_CHECK_TYPE}, deprecated because of its flaws.  First, although
22088 it is a member of the @code{CHECK} clan, it does
22089 more than just checking.  Secondly, missing types are defined
22090 using @code{#define}, not @code{typedef}, and this can lead to
22091 problems in the case of pointer types.
22093 This use of @code{AC_CHECK_TYPE} is obsolete and discouraged; see
22094 @ref{Generic Types}, for the description of the current macro.
22096 If the type @var{type} is not defined, define it to be the C (or C++)
22097 builtin type @var{default}, e.g., @samp{short int} or @samp{unsigned int}.
22099 This macro is equivalent to:
22101 @example
22102 AC_CHECK_TYPE([@var{type}], [],
22103   [AC_DEFINE_UNQUOTED([@var{type}], [@var{default}],
22104      [Define to `@var{default}'
22105       if <sys/types.h> does not define.])])
22106 @end example
22108 In order to keep backward compatibility, the two versions of
22109 @code{AC_CHECK_TYPE} are implemented, selected using these heuristics:
22111 @enumerate
22112 @item
22113 If there are three or four arguments, the modern version is used.
22115 @item
22116 If the second argument appears to be a C or C++ type, then the
22117 obsolete version is used.  This happens if the argument is a C or C++
22118 @emph{builtin} type or a C identifier ending in @samp{_t}, optionally
22119 followed by one of @samp{[(* } and then by a string of zero or more
22120 characters taken from the set @samp{[]()* _a-zA-Z0-9}.
22122 @item
22123 If the second argument is spelled with the alphabet of valid C and C++
22124 types, the user is warned and the modern version is used.
22126 @item
22127 Otherwise, the modern version is used.
22128 @end enumerate
22130 @noindent
22131 You are encouraged either to use a valid builtin type, or to use the
22132 equivalent modern code (see above), or better yet, to use
22133 @code{AC_CHECK_TYPES} together with
22135 @example
22136 #ifndef HAVE_LOFF_T
22137 typedef loff_t off_t;
22138 #endif
22139 @end example
22140 @end defmac
22141 @c end of AC_CHECK_TYPE
22143 @defmac AC_CHECKING (@var{feature-description})
22144 @acindex{CHECKING}
22145 Same as
22147 @example
22148 AC_MSG_NOTICE([checking @var{feature-description}@dots{}]
22149 @end example
22151 @noindent
22152 @xref{AC_MSG_NOTICE}.
22153 @end defmac
22155 @defmac AC_COMPILE_CHECK (@var{echo-text}, @var{includes}, @
22156   @var{function-body}, @var{action-if-true}, @ovar{action-if-false})
22157 @acindex{COMPILE_CHECK}
22158 This is an obsolete version of @code{AC_TRY_COMPILE} itself replaced by
22159 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}), with the
22160 addition that it prints @samp{checking for @var{echo-text}} to the
22161 standard output first, if @var{echo-text} is non-empty.  Use
22162 @code{AC_MSG_CHECKING} and @code{AC_MSG_RESULT} instead to print
22163 messages (@pxref{Printing Messages}).
22164 @end defmac
22166 @defmac AC_CONST
22167 @acindex{CONST}
22168 Replaced by @code{AC_C_CONST} (@pxref{AC_C_CONST}).
22169 @end defmac
22171 @defmac AC_CROSS_CHECK
22172 @acindex{CROSS_CHECK}
22173 Same as @code{AC_C_CROSS}, which is obsolete too, and does nothing
22174 @code{:-)}.
22175 @end defmac
22177 @defmac AC_CYGWIN
22178 @acindex{CYGWIN}
22179 @evindex CYGWIN
22180 Check for the Cygwin environment in which case the shell variable
22181 @code{CYGWIN} is set to @samp{yes}.  Don't use this macro, the dignified
22182 means to check the nature of the host is using @code{AC_CANONICAL_HOST}
22183 (@pxref{Canonicalizing}).  As a matter of fact this macro is defined as:
22185 @example
22186 AC_REQUIRE([AC_CANONICAL_HOST])[]dnl
22187 case $host_os in
22188   *cygwin* ) CYGWIN=yes;;
22189          * ) CYGWIN=no;;
22190 esac
22191 @end example
22193 Beware that the variable @env{CYGWIN} has a special meaning when
22194 running Cygwin, and should not be changed.  That's yet another reason
22195 not to use this macro.
22196 @end defmac
22198 @defmac AC_DECL_SYS_SIGLIST
22199 @acindex{DECL_SYS_SIGLIST}
22200 @cvindex SYS_SIGLIST_DECLARED
22201 Same as:
22203 @example
22204 AC_CHECK_DECLS([sys_siglist], [], [],
22205 [#include <signal.h>
22206 /* NetBSD declares sys_siglist in unistd.h.  */
22207 #ifdef HAVE_UNISTD_H
22208 # include <unistd.h>
22209 #endif
22211 @end example
22213 @noindent
22214 @xref{AC_CHECK_DECLS}.
22215 @end defmac
22217 @defmac AC_DECL_YYTEXT
22218 @acindex{DECL_YYTEXT}
22219 Does nothing, now integrated in @code{AC_PROG_LEX} (@pxref{AC_PROG_LEX}).
22220 @end defmac
22222 @defmac AC_DIR_HEADER
22223 @acindex{DIR_HEADER}
22224 @cvindex DIRENT
22225 @cvindex SYSNDIR
22226 @cvindex SYSDIR
22227 @cvindex NDIR
22228 Like calling @code{AC_FUNC_CLOSEDIR_VOID}
22229 (@pxref{AC_FUNC_CLOSEDIR_VOID}) and @code{AC_HEADER_DIRENT}
22230 (@pxref{AC_HEADER_DIRENT}),
22231 but defines a different set of C preprocessor macros to indicate which
22232 header file is found:
22234 @multitable {@file{sys/ndir.h}} {Old Symbol} {@code{HAVE_SYS_NDIR_H}}
22235 @item Header            @tab Old Symbol     @tab New Symbol
22236 @item @file{dirent.h}   @tab @code{DIRENT}  @tab @code{HAVE_DIRENT_H}
22237 @item @file{sys/ndir.h} @tab @code{SYSNDIR} @tab @code{HAVE_SYS_NDIR_H}
22238 @item @file{sys/dir.h}  @tab @code{SYSDIR}  @tab @code{HAVE_SYS_DIR_H}
22239 @item @file{ndir.h}     @tab @code{NDIR}    @tab @code{HAVE_NDIR_H}
22240 @end multitable
22241 @end defmac
22243 @defmac AC_DYNIX_SEQ
22244 @acindex{DYNIX_SEQ}
22245 If on DYNIX/ptx, add @option{-lseq} to output variable
22246 @code{LIBS}.  This macro used to be defined as
22248 @example
22249 AC_CHECK_LIB([seq], [getmntent], [LIBS="-lseq $LIBS"])
22250 @end example
22252 @noindent
22253 now it is just @code{AC_FUNC_GETMNTENT} (@pxref{AC_FUNC_GETMNTENT}).
22254 @end defmac
22256 @defmac AC_EXEEXT
22257 @acindex{EXEEXT}
22258 @ovindex EXEEXT
22259 Defined the output variable @code{EXEEXT} based on the output of the
22260 compiler, which is now done automatically.  Typically set to empty
22261 string if Posix and @samp{.exe} if a DOS variant.
22262 @end defmac
22264 @defmac AC_EMXOS2
22265 @acindex{EMXOS2}
22266 Similar to @code{AC_CYGWIN} but checks for the EMX environment on OS/2
22267 and sets @code{EMXOS2}.  Don't use this macro, the dignified means to
22268 check the nature of the host is using @code{AC_CANONICAL_HOST}
22269 (@pxref{Canonicalizing}).
22270 @end defmac
22272 @defmac AC_ENABLE (@var{feature}, @var{action-if-given}, @
22273   @ovar{action-if-not-given})
22274 @acindex{ENABLE}
22275 This is an obsolete version of @code{AC_ARG_ENABLE} that does not
22276 support providing a help string (@pxref{AC_ARG_ENABLE}).
22277 @end defmac
22279 @defmac AC_ERROR
22280 @acindex{ERROR}
22281 Replaced by @code{AC_MSG_ERROR} (@pxref{AC_MSG_ERROR}).
22282 @end defmac
22284 @defmac AC_FIND_X
22285 @acindex{FIND_X}
22286 Replaced by @code{AC_PATH_X} (@pxref{AC_PATH_X}).
22287 @end defmac
22289 @defmac AC_FIND_XTRA
22290 @acindex{FIND_XTRA}
22291 Replaced by @code{AC_PATH_XTRA} (@pxref{AC_PATH_XTRA}).
22292 @end defmac
22294 @defmac AC_FOREACH
22295 @acindex{FOREACH}
22296 Replaced by @code{m4_foreach_w} (@pxref{m4_foreach_w}).
22297 @end defmac
22299 @defmac AC_FUNC_CHECK
22300 @acindex{FUNC_CHECK}
22301 Replaced by @code{AC_CHECK_FUNC} (@pxref{AC_CHECK_FUNC}).
22302 @end defmac
22304 @anchor{AC_FUNC_SETVBUF_REVERSED}
22305 @defmac AC_FUNC_SETVBUF_REVERSED
22306 @acindex{FUNC_SETVBUF_REVERSED}
22307 @cvindex SETVBUF_REVERSED
22308 @c @fuindex setvbuf
22309 @prindex @code{setvbuf}
22310 Do nothing.  Formerly, this macro checked whether @code{setvbuf} takes
22311 the buffering type as its second argument and the buffer pointer as the
22312 third, instead of the other way around, and defined
22313 @code{SETVBUF_REVERSED}.  However, the last systems to have the problem
22314 were those based on SVR2, which became obsolete in 1987, and the macro
22315 is no longer needed.
22316 @end defmac
22318 @defmac AC_FUNC_WAIT3
22319 @acindex{FUNC_WAIT3}
22320 @cvindex HAVE_WAIT3
22321 @c @fuindex wait3
22322 @prindex @code{wait3}
22323 If @code{wait3} is found and fills in the contents of its third argument
22324 (a @samp{struct rusage *}), which HP-UX does not do, define
22325 @code{HAVE_WAIT3}.
22327 These days portable programs should use @code{waitpid}, not
22328 @code{wait3}, as @code{wait3} has been removed from Posix.
22329 @end defmac
22331 @defmac AC_GCC_TRADITIONAL
22332 @acindex{GCC_TRADITIONAL}
22333 Replaced by @code{AC_PROG_GCC_TRADITIONAL} (@pxref{AC_PROG_GCC_TRADITIONAL}).
22334 @end defmac
22336 @defmac AC_GETGROUPS_T
22337 @acindex{GETGROUPS_T}
22338 Replaced by @code{AC_TYPE_GETGROUPS} (@pxref{AC_TYPE_GETGROUPS}).
22339 @end defmac
22341 @defmac AC_GETLOADAVG
22342 @acindex{GETLOADAVG}
22343 Replaced by @code{AC_FUNC_GETLOADAVG} (@pxref{AC_FUNC_GETLOADAVG}).
22344 @end defmac
22346 @defmac AC_GNU_SOURCE
22347 @acindex{GNU_SOURCE}
22348 @cvindex _GNU_SOURCE
22349 This macro is a platform-specific subset of
22350 @code{AC_USE_SYSTEM_EXTENSIONS} (@pxref{AC_USE_SYSTEM_EXTENSIONS}).
22351 @end defmac
22353 @defmac AC_HAVE_FUNCS
22354 @acindex{HAVE_FUNCS}
22355 Replaced by @code{AC_CHECK_FUNCS} (@pxref{AC_CHECK_FUNCS}).
22356 @end defmac
22358 @defmac AC_HAVE_HEADERS
22359 @acindex{HAVE_HEADERS}
22360 Replaced by @code{AC_CHECK_HEADERS} (@pxref{AC_CHECK_HEADERS}).
22361 @end defmac
22363 @defmac AC_HAVE_LIBRARY (@var{library}, @ovar{action-if-found}, @
22364   @ovar{action-if-not-found}, @ovar{other-libraries})
22365 @acindex{HAVE_LIBRARY}
22366 This macro is equivalent to calling @code{AC_CHECK_LIB} with a
22367 @var{function} argument of @code{main}.  In addition, @var{library} can
22368 be written as any of @samp{foo}, @option{-lfoo}, or @samp{libfoo.a}.  In
22369 all of those cases, the compiler is passed @option{-lfoo}.  However,
22370 @var{library} cannot be a shell variable; it must be a literal name.
22371 @xref{AC_CHECK_LIB}.
22372 @end defmac
22374 @defmac AC_HAVE_POUNDBANG
22375 @acindex{HAVE_POUNDBANG}
22376 Replaced by @code{AC_SYS_INTERPRETER} (@pxref{AC_SYS_INTERPRETER}).
22377 @end defmac
22379 @defmac AC_HEADER_CHECK
22380 @acindex{HEADER_CHECK}
22381 Replaced by @code{AC_CHECK_HEADER} (@pxref{AC_CHECK_HEADER}).
22382 @end defmac
22384 @defmac AC_HEADER_EGREP
22385 @acindex{HEADER_EGREP}
22386 Replaced by @code{AC_EGREP_HEADER} (@pxref{AC_EGREP_HEADER}).
22387 @end defmac
22389 @defmac AC_HELP_STRING
22390 @acindex{HELP_STRING}
22391 Replaced by @code{AS_HELP_STRING} (@pxref{AS_HELP_STRING}).
22392 @end defmac
22394 @defmac AC_INIT (@var{unique-file-in-source-dir})
22395 @acindex{INIT}
22396 Formerly @code{AC_INIT} used to have a single argument, and was
22397 equivalent to:
22399 @example
22400 AC_INIT
22401 AC_CONFIG_SRCDIR(@var{unique-file-in-source-dir})
22402 @end example
22403 See @ref{AC_INIT} and @ref{AC_CONFIG_SRCDIR}.
22404 @end defmac
22406 @defmac AC_INLINE
22407 @acindex{INLINE}
22408 Replaced by @code{AC_C_INLINE} (@pxref{AC_C_INLINE}).
22409 @end defmac
22411 @defmac AC_INT_16_BITS
22412 @acindex{INT_16_BITS}
22413 @cvindex INT_16_BITS
22414 If the C type @code{int} is 16 bits wide, define @code{INT_16_BITS}.
22415 Use @samp{AC_CHECK_SIZEOF(int)} instead (@pxref{AC_CHECK_SIZEOF}).
22416 @end defmac
22418 @defmac AC_IRIX_SUN
22419 @acindex{IRIX_SUN}
22420 If on IRIX (Silicon Graphics Unix), add @option{-lsun} to output
22421 @code{LIBS}.  If you were using it to get @code{getmntent}, use
22422 @code{AC_FUNC_GETMNTENT} instead.  If you used it for the NIS versions
22423 of the password and group functions, use @samp{AC_CHECK_LIB(sun,
22424 getpwnam)}.  Up to Autoconf 2.13, it used to be
22426 @example
22427 AC_CHECK_LIB([sun], [getmntent], [LIBS="-lsun $LIBS"])
22428 @end example
22430 @noindent
22431 now it is defined as
22433 @example
22434 AC_FUNC_GETMNTENT
22435 AC_CHECK_LIB([sun], [getpwnam])
22436 @end example
22438 @noindent
22439 See @ref{AC_FUNC_GETMNTENT} and @ref{AC_CHECK_LIB}.
22440 @end defmac
22442 @defmac AC_ISC_POSIX
22443 @acindex{ISC_POSIX}
22444 @ovindex LIBS
22445 This macro adds @option{-lcposix} to output variable @code{LIBS} if
22446 necessary for Posix facilities.  Sun dropped support for the obsolete
22447 INTERACTIVE Systems Corporation Unix on 2006-07-23.  New programs
22448 need not use this macro.  It is implemented as
22449 @code{AC_SEARCH_LIBS([strerror], [cposix])} (@pxref{AC_SEARCH_LIBS}).
22450 @end defmac
22452 @defmac AC_LANG_C
22453 @acindex{LANG_C}
22454 Same as @samp{AC_LANG([C])} (@pxref{AC_LANG}).
22455 @end defmac
22457 @defmac AC_LANG_CPLUSPLUS
22458 @acindex{LANG_CPLUSPLUS}
22459 Same as @samp{AC_LANG([C++])} (@pxref{AC_LANG}).
22460 @end defmac
22462 @defmac AC_LANG_FORTRAN77
22463 @acindex{LANG_FORTRAN77}
22464 Same as @samp{AC_LANG([Fortran 77])} (@pxref{AC_LANG}).
22465 @end defmac
22467 @defmac AC_LANG_RESTORE
22468 @acindex{LANG_RESTORE}
22469 Select the @var{language} that is saved on the top of the stack, as set
22470 by @code{AC_LANG_SAVE}, remove it from the stack, and call
22471 @code{AC_LANG(@var{language})}.  @xref{Language Choice}, for the
22472 preferred way to change languages.
22473 @end defmac
22475 @defmac AC_LANG_SAVE
22476 @acindex{LANG_SAVE}
22477 Remember the current language (as set by @code{AC_LANG}) on a stack.
22478 The current language does not change.  @code{AC_LANG_PUSH} is preferred
22479 (@pxref{AC_LANG_PUSH}).
22480 @end defmac
22482 @defmac AC_LINK_FILES (@var{source}@dots{}, @var{dest}@dots{})
22483 @acindex{LINK_FILES}
22484 This is an obsolete version of @code{AC_CONFIG_LINKS}
22485 (@pxref{AC_CONFIG_LINKS}.  An updated version of:
22487 @example
22488 AC_LINK_FILES(config/$machine.h config/$obj_format.h,
22489               host.h            object.h)
22490 @end example
22492 @noindent
22495 @example
22496 AC_CONFIG_LINKS([host.h:config/$machine.h
22497                 object.h:config/$obj_format.h])
22498 @end example
22499 @end defmac
22501 @defmac AC_LN_S
22502 @acindex{LN_S}
22503 Replaced by @code{AC_PROG_LN_S} (@pxref{AC_PROG_LN_S}).
22504 @end defmac
22506 @defmac AC_LONG_64_BITS
22507 @acindex{LONG_64_BITS}
22508 @cvindex LONG_64_BITS
22509 Define @code{LONG_64_BITS} if the C type @code{long int} is 64 bits wide.
22510 Use the generic macro @samp{AC_CHECK_SIZEOF([long int])} instead
22511 (@pxref{AC_CHECK_SIZEOF}).
22512 @end defmac
22514 @defmac AC_LONG_DOUBLE
22515 @acindex{LONG_DOUBLE}
22516 If the C compiler supports a working @code{long double} type with more
22517 range or precision than the @code{double} type, define
22518 @code{HAVE_LONG_DOUBLE}.
22520 You should use @code{AC_TYPE_LONG_DOUBLE} or
22521 @code{AC_TYPE_LONG_DOUBLE_WIDER} instead.  @xref{Particular Types}.
22522 @end defmac
22524 @defmac AC_LONG_FILE_NAMES
22525 @acindex{LONG_FILE_NAMES}
22526 Replaced by
22527 @example
22528 AC_SYS_LONG_FILE_NAMES
22529 @end example
22530 @noindent
22531 @xref{AC_SYS_LONG_FILE_NAMES}.
22532 @end defmac
22534 @defmac AC_MAJOR_HEADER
22535 @acindex{MAJOR_HEADER}
22536 Replaced by @code{AC_HEADER_MAJOR} (@pxref{AC_HEADER_MAJOR}).
22537 @end defmac
22539 @defmac AC_MEMORY_H
22540 @acindex{MEMORY_H}
22541 @cvindex NEED_MEMORY_H
22542 Used to define @code{NEED_MEMORY_H} if the @code{mem} functions were
22543 defined in @file{memory.h}.  Today it is equivalent to
22544 @samp{AC_CHECK_HEADERS([memory.h])} (@pxref{AC_CHECK_HEADERS}).  Adjust
22545 your code to depend upon
22546 @code{HAVE_MEMORY_H}, not @code{NEED_MEMORY_H}; see @ref{Standard
22547 Symbols}.
22548 @end defmac
22550 @defmac AC_MINGW32
22551 @acindex{MINGW32}
22552 Similar to @code{AC_CYGWIN} but checks for the MinGW compiler
22553 environment and sets @code{MINGW32}.  Don't use this macro, the
22554 dignified means to check the nature of the host is using
22555 @code{AC_CANONICAL_HOST} (@pxref{Canonicalizing}).
22556 @end defmac
22558 @defmac AC_MINIX
22559 @acindex{MINIX}
22560 @cvindex _MINIX
22561 @cvindex _POSIX_SOURCE
22562 @cvindex _POSIX_1_SOURCE
22563 This macro is a platform-specific subset of
22564 @code{AC_USE_SYSTEM_EXTENSIONS} (@pxref{AC_USE_SYSTEM_EXTENSIONS}).
22565 @end defmac
22567 @defmac AC_MINUS_C_MINUS_O
22568 @acindex{MINUS_C_MINUS_O}
22569 Replaced by @code{AC_PROG_CC_C_O} (@pxref{AC_PROG_CC_C_O}).
22570 @end defmac
22572 @defmac AC_MMAP
22573 @acindex{MMAP}
22574 Replaced by @code{AC_FUNC_MMAP} (@pxref{AC_FUNC_MMAP}).
22575 @end defmac
22577 @defmac AC_MODE_T
22578 @acindex{MODE_T}
22579 Replaced by @code{AC_TYPE_MODE_T} (@pxref{AC_TYPE_MODE_T}).
22580 @end defmac
22582 @defmac AC_OBJEXT
22583 @acindex{OBJEXT}
22584 @ovindex OBJEXT
22585 Defined the output variable @code{OBJEXT} based on the output of the
22586 compiler, after .c files have been excluded.  Typically set to @samp{o}
22587 if Posix, @samp{obj} if a DOS variant.
22588 Now the compiler checking macros handle
22589 this automatically.
22590 @end defmac
22592 @defmac AC_OBSOLETE (@var{this-macro-name}, @ovar{suggestion})
22593 @acindex{OBSOLETE}
22594 Make M4 print a message to the standard error output warning that
22595 @var{this-macro-name} is obsolete, and giving the file and line number
22596 where it was called.  @var{this-macro-name} should be the name of the
22597 macro that is calling @code{AC_OBSOLETE}.  If @var{suggestion} is given,
22598 it is printed at the end of the warning message; for example, it can be
22599 a suggestion for what to use instead of @var{this-macro-name}.
22601 For instance
22603 @example
22604 AC_OBSOLETE([$0], [; use AC_CHECK_HEADERS(unistd.h) instead])dnl
22605 @end example
22607 @noindent
22608 You are encouraged to use @code{AU_DEFUN} instead, since it gives better
22609 services to the user (@pxref{AU_DEFUN}).
22610 @end defmac
22612 @defmac AC_OFF_T
22613 @acindex{OFF_T}
22614 Replaced by @code{AC_TYPE_OFF_T} (@pxref{AC_TYPE_OFF_T}).
22615 @end defmac
22617 @defmac AC_OUTPUT (@ovar{file}@dots{}, @ovar{extra-cmds}, @ovar{init-cmds})
22618 @acindex{OUTPUT}
22619 The use of @code{AC_OUTPUT} with arguments is deprecated.  This obsoleted
22620 interface is equivalent to:
22622 @example
22623 @group
22624 AC_CONFIG_FILES(@var{file}@dots{})
22625 AC_CONFIG_COMMANDS([default],
22626                    @var{extra-cmds}, @var{init-cmds})
22627 AC_OUTPUT
22628 @end group
22629 @end example
22631 @noindent
22632 See @ref{AC_CONFIG_FILES}, @ref{AC_CONFIG_COMMANDS}, and @ref{AC_OUTPUT}.
22633 @end defmac
22635 @defmac AC_OUTPUT_COMMANDS (@var{extra-cmds}, @ovar{init-cmds})
22636 @acindex{OUTPUT_COMMANDS}
22637 Specify additional shell commands to run at the end of
22638 @file{config.status}, and shell commands to initialize any variables
22639 from @command{configure}.  This macro may be called multiple times.  It is
22640 obsolete, replaced by @code{AC_CONFIG_COMMANDS} (@pxref{AC_CONFIG_COMMANDS}).
22642 Here is an unrealistic example:
22644 @example
22645 fubar=27
22646 AC_OUTPUT_COMMANDS([echo this is extra $fubar, and so on.],
22647                    [fubar=$fubar])
22648 AC_OUTPUT_COMMANDS([echo this is another, extra, bit],
22649                    [echo init bit])
22650 @end example
22652 Aside from the fact that @code{AC_CONFIG_COMMANDS} requires an
22653 additional key, an important difference is that
22654 @code{AC_OUTPUT_COMMANDS} is quoting its arguments twice, unlike
22655 @code{AC_CONFIG_COMMANDS}.  This means that @code{AC_CONFIG_COMMANDS}
22656 can safely be given macro calls as arguments:
22658 @example
22659 AC_CONFIG_COMMANDS(foo, [my_FOO()])
22660 @end example
22662 @noindent
22663 Conversely, where one level of quoting was enough for literal strings
22664 with @code{AC_OUTPUT_COMMANDS}, you need two with
22665 @code{AC_CONFIG_COMMANDS}.  The following lines are equivalent:
22667 @example
22668 @group
22669 AC_OUTPUT_COMMANDS([echo "Square brackets: []"])
22670 AC_CONFIG_COMMANDS([default], [[echo "Square brackets: []"]])
22671 @end group
22672 @end example
22673 @end defmac
22675 @defmac AC_PID_T
22676 @acindex{PID_T}
22677 Replaced by @code{AC_TYPE_PID_T} (@pxref{AC_TYPE_PID_T}).
22678 @end defmac
22680 @defmac AC_PREFIX
22681 @acindex{PREFIX}
22682 Replaced by @code{AC_PREFIX_PROGRAM} (@pxref{AC_PREFIX_PROGRAM}).
22683 @end defmac
22685 @defmac AC_PROGRAMS_CHECK
22686 @acindex{PROGRAMS_CHECK}
22687 Replaced by @code{AC_CHECK_PROGS} (@pxref{AC_CHECK_PROGS}).
22688 @end defmac
22690 @defmac AC_PROGRAMS_PATH
22691 @acindex{PROGRAMS_PATH}
22692 Replaced by @code{AC_PATH_PROGS} (@pxref{AC_PATH_PROGS}).
22693 @end defmac
22695 @defmac AC_PROGRAM_CHECK
22696 @acindex{PROGRAM_CHECK}
22697 Replaced by @code{AC_CHECK_PROG} (@pxref{AC_CHECK_PROG}).
22698 @end defmac
22700 @defmac AC_PROGRAM_EGREP
22701 @acindex{PROGRAM_EGREP}
22702 Replaced by @code{AC_EGREP_CPP} (@pxref{AC_EGREP_CPP}).
22703 @end defmac
22705 @defmac AC_PROGRAM_PATH
22706 @acindex{PROGRAM_PATH}
22707 Replaced by @code{AC_PATH_PROG} (@pxref{AC_PATH_PROG}).
22708 @end defmac
22710 @defmac AC_REMOTE_TAPE
22711 @acindex{REMOTE_TAPE}
22712 Removed because of limited usefulness.
22713 @end defmac
22715 @defmac AC_RESTARTABLE_SYSCALLS
22716 @acindex{RESTARTABLE_SYSCALLS}
22717 This macro was renamed @code{AC_SYS_RESTARTABLE_SYSCALLS}.  However,
22718 these days portable programs should use @code{sigaction} with
22719 @code{SA_RESTART} if they want restartable system calls.  They should
22720 not rely on @code{HAVE_RESTARTABLE_SYSCALLS}, since nowadays whether a
22721 system call is restartable is a dynamic issue, not a configuration-time
22722 issue.
22723 @end defmac
22725 @defmac AC_RETSIGTYPE
22726 @acindex{RETSIGTYPE}
22727 Replaced by @code{AC_TYPE_SIGNAL} (@pxref{AC_TYPE_SIGNAL}), which itself
22728 is obsolete when assuming C89 or better.
22729 @end defmac
22731 @defmac AC_RSH
22732 @acindex{RSH}
22733 Removed because of limited usefulness.
22734 @end defmac
22736 @defmac AC_SCO_INTL
22737 @acindex{SCO_INTL}
22738 @ovindex LIBS
22739 If on SCO Unix, add @option{-lintl} to output variable @code{LIBS}.  This
22740 macro used to do this:
22742 @example
22743 AC_CHECK_LIB([intl], [strftime], [LIBS="-lintl $LIBS"])
22744 @end example
22746 @noindent
22747 Now it just calls @code{AC_FUNC_STRFTIME} instead (@pxref{AC_FUNC_STRFTIME}).
22748 @end defmac
22750 @defmac AC_SETVBUF_REVERSED
22751 @acindex{SETVBUF_REVERSED}
22752 Replaced by
22753 @example
22754 AC_FUNC_SETVBUF_REVERSED
22755 @end example
22756 @noindent
22757 @xref{AC_FUNC_SETVBUF_REVERSED}.
22758 @end defmac
22760 @defmac AC_SET_MAKE
22761 @acindex{SET_MAKE}
22762 Replaced by @code{AC_PROG_MAKE_SET} (@pxref{AC_PROG_MAKE_SET}).
22763 @end defmac
22765 @defmac AC_SIZEOF_TYPE
22766 @acindex{SIZEOF_TYPE}
22767 Replaced by @code{AC_CHECK_SIZEOF} (@pxref{AC_CHECK_SIZEOF}).
22768 @end defmac
22770 @defmac AC_SIZE_T
22771 @acindex{SIZE_T}
22772 Replaced by @code{AC_TYPE_SIZE_T} (@pxref{AC_TYPE_SIZE_T}).
22773 @end defmac
22775 @defmac AC_STAT_MACROS_BROKEN
22776 @acindex{STAT_MACROS_BROKEN}
22777 Replaced by @code{AC_HEADER_STAT} (@pxref{AC_HEADER_STAT}).
22778 @end defmac
22780 @defmac AC_STDC_HEADERS
22781 @acindex{STDC_HEADERS}
22782 Replaced by @code{AC_HEADER_STDC} (@pxref{AC_HEADER_STDC}).
22783 @end defmac
22785 @defmac AC_STRCOLL
22786 @acindex{STRCOLL}
22787 Replaced by @code{AC_FUNC_STRCOLL} (@pxref{AC_FUNC_STRCOLL}).
22788 @end defmac
22790 @defmac AC_STRUCT_ST_BLKSIZE
22791 @acindex{STRUCT_ST_BLKSIZE}
22792 @cvindex HAVE_STRUCT_STAT_ST_BLKSIZE
22793 @cvindex HAVE_ST_BLKSIZE
22794 If @code{struct stat} contains an @code{st_blksize} member, define
22795 @code{HAVE_STRUCT_STAT_ST_BLKSIZE}.  The former name,
22796 @code{HAVE_ST_BLKSIZE} is to be avoided, as its support will cease in
22797 the future.  This macro is obsoleted, and should be replaced by
22799 @example
22800 AC_CHECK_MEMBERS([struct stat.st_blksize])
22801 @end example
22802 @noindent
22803 @xref{AC_CHECK_MEMBERS}.
22804 @end defmac
22806 @defmac AC_STRUCT_ST_RDEV
22807 @acindex{STRUCT_ST_RDEV}
22808 @cvindex HAVE_ST_RDEV
22809 @cvindex HAVE_STRUCT_STAT_ST_RDEV
22810 If @code{struct stat} contains an @code{st_rdev} member, define
22811 @code{HAVE_STRUCT_STAT_ST_RDEV}.  The former name for this macro,
22812 @code{HAVE_ST_RDEV}, is to be avoided as it will cease to be supported
22813 in the future.  Actually, even the new macro is obsolete and should be
22814 replaced by:
22815 @example
22816 AC_CHECK_MEMBERS([struct stat.st_rdev])
22817 @end example
22818 @noindent
22819 @xref{AC_CHECK_MEMBERS}.
22820 @end defmac
22822 @defmac AC_ST_BLKSIZE
22823 @acindex{ST_BLKSIZE}
22824 Replaced by @code{AC_CHECK_MEMBERS} (@pxref{AC_CHECK_MEMBERS}).
22825 @end defmac
22827 @defmac AC_ST_BLOCKS
22828 @acindex{ST_BLOCKS}
22829 Replaced by @code{AC_STRUCT_ST_BLOCKS} (@pxref{AC_STRUCT_ST_BLOCKS}).
22830 @end defmac
22832 @defmac AC_ST_RDEV
22833 @acindex{ST_RDEV}
22834 Replaced by @code{AC_CHECK_MEMBERS} (@pxref{AC_CHECK_MEMBERS}).
22835 @end defmac
22837 @defmac AC_SYS_RESTARTABLE_SYSCALLS
22838 @acindex{SYS_RESTARTABLE_SYSCALLS}
22839 @cvindex HAVE_RESTARTABLE_SYSCALLS
22840 If the system automatically restarts a system call that is interrupted
22841 by a signal, define @code{HAVE_RESTARTABLE_SYSCALLS}.  This macro does
22842 not check whether system calls are restarted in general---it checks whether a
22843 signal handler installed with @code{signal} (but not @code{sigaction})
22844 causes system calls to be restarted.  It does not check whether system calls
22845 can be restarted when interrupted by signals that have no handler.
22847 These days portable programs should use @code{sigaction} with
22848 @code{SA_RESTART} if they want restartable system calls.  They should
22849 not rely on @code{HAVE_RESTARTABLE_SYSCALLS}, since nowadays whether a
22850 system call is restartable is a dynamic issue, not a configuration-time
22851 issue.
22852 @end defmac
22854 @defmac AC_SYS_SIGLIST_DECLARED
22855 @acindex{SYS_SIGLIST_DECLARED}
22856 This macro was renamed @code{AC_DECL_SYS_SIGLIST}.  However, even that
22857 name is obsolete, as the same functionality is now acheived via
22858 @code{AC_CHECK_DECLS} (@pxref{AC_CHECK_DECLS}).
22859 @end defmac
22861 @defmac AC_TEST_CPP
22862 @acindex{TEST_CPP}
22863 This macro was renamed @code{AC_TRY_CPP}, which in turn was replaced by
22864 @code{AC_PREPROC_IFELSE} (@pxref{AC_PREPROC_IFELSE}).
22865 @end defmac
22867 @defmac AC_TEST_PROGRAM
22868 @acindex{TEST_PROGRAM}
22869 This macro was renamed @code{AC_TRY_RUN}, which in turn was replaced by
22870 @code{AC_RUN_IFELSE} (@pxref{AC_RUN_IFELSE}).
22871 @end defmac
22873 @defmac AC_TIMEZONE
22874 @acindex{TIMEZONE}
22875 Replaced by @code{AC_STRUCT_TIMEZONE} (@pxref{AC_STRUCT_TIMEZONE}).
22876 @end defmac
22878 @defmac AC_TIME_WITH_SYS_TIME
22879 @acindex{TIME_WITH_SYS_TIME}
22880 Replaced by @code{AC_HEADER_TIME} (@pxref{AC_HEADER_TIME}).
22881 @end defmac
22883 @defmac AC_TRY_COMPILE (@var{includes}, @var{function-body}, @
22884   @ovar{action-if-true}, @ovar{action-if-false})
22885 @acindex{TRY_COMPILE}
22886 Same as:
22888 @example
22889 AC_COMPILE_IFELSE(
22890   [AC_LANG_PROGRAM([[@var{includes}]],
22891      [[@var{function-body}]])],
22892   [@var{action-if-true}],
22893   [@var{action-if-false}])
22894 @end example
22896 @noindent
22897 @xref{Running the Compiler}.
22899 This macro double quotes both @var{includes} and @var{function-body}.
22901 For C and C++, @var{includes} is any @code{#include} statements needed
22902 by the code in @var{function-body} (@var{includes} is ignored if
22903 the currently selected language is Fortran or Fortran 77).  The compiler
22904 and compilation flags are determined by the current language
22905 (@pxref{Language Choice}).
22906 @end defmac
22908 @defmac AC_TRY_CPP (@var{input}, @ovar{action-if-true}, @ovar{action-if-false})
22909 @acindex{TRY_CPP}
22910 Same as:
22912 @example
22913 AC_PREPROC_IFELSE(
22914   [AC_LANG_SOURCE([[@var{input}]])],
22915   [@var{action-if-true}],
22916   [@var{action-if-false}])
22917 @end example
22919 @noindent
22920 @xref{Running the Preprocessor}.
22922 This macro double quotes the @var{input}.
22923 @end defmac
22925 @defmac AC_TRY_LINK (@var{includes}, @var{function-body}, @
22926   @ovar{action-if-true}, @ovar{action-if-false})
22927 @acindex{TRY_LINK}
22928 Same as:
22930 @example
22931 AC_LINK_IFELSE(
22932   [AC_LANG_PROGRAM([[@var{includes}]],
22933      [[@var{function-body}]])],
22934   [@var{action-if-true}],
22935   [@var{action-if-false}])
22936 @end example
22938 @noindent
22939 @xref{Running the Compiler}.
22941 This macro double quotes both @var{includes} and @var{function-body}.
22943 Depending on the current language (@pxref{Language Choice}), create a
22944 test program to see whether a function whose body consists of
22945 @var{function-body} can be compiled and linked.  If the file compiles
22946 and links successfully, run shell commands @var{action-if-found},
22947 otherwise run @var{action-if-not-found}.
22949 This macro double quotes both @var{includes} and @var{function-body}.
22951 For C and C++, @var{includes} is any @code{#include} statements needed
22952 by the code in @var{function-body} (@var{includes} is ignored if
22953 the currently selected language is Fortran or Fortran 77).  The compiler
22954 and compilation flags are determined by the current language
22955 (@pxref{Language Choice}), and in addition @code{LDFLAGS} and
22956 @code{LIBS} are used for linking.
22957 @end defmac
22959 @defmac AC_TRY_LINK_FUNC (@var{function}, @ovar{action-if-found}, @
22960   @ovar{action-if-not-found})
22961 @acindex{TRY_LINK_FUNC}
22962 This macro is equivalent to
22963 @example
22964 AC_LINK_IFELSE([AC_LANG_CALL([], [@var{function}])],
22965   [@var{action-if-found}], [@var{action-if-not-found}])
22966 @end example
22967 @noindent
22968 @xref{AC_LINK_IFELSE}.
22969 @end defmac
22971 @defmac AC_TRY_RUN (@var{program}, @ovar{action-if-true}, @
22972   @ovar{action-if-false}, @ovar{action-if-cross-compiling})
22973 @acindex{TRY_RUN}
22974 Same as:
22976 @example
22977 AC_RUN_IFELSE(
22978   [AC_LANG_SOURCE([[@var{program}]])],
22979   [@var{action-if-true}],
22980   [@var{action-if-false}],
22981   [@var{action-if-cross-compiling}])
22982 @end example
22984 @noindent
22985 @xref{Runtime}.
22986 @end defmac
22988 @anchor{AC_TYPE_SIGNAL}
22989 @defmac AC_TYPE_SIGNAL
22990 @acindex{TYPE_SIGNAL}
22991 @cvindex RETSIGTYPE
22992 @hdrindex{signal.h}
22993 If @file{signal.h} declares @code{signal} as returning a pointer to a
22994 function returning @code{void}, define @code{RETSIGTYPE} to be
22995 @code{void}; otherwise, define it to be @code{int}.  These days, it is
22996 portable to assume C89, and that signal handlers return @code{void},
22997 without needing to use this macro or @code{RETSIGTYPE}.
22999 When targetting older K&R C, it is possible to define signal handlers as
23000 returning type @code{RETSIGTYPE}, and omit a return statement:
23002 @example
23003 @group
23004 RETSIGTYPE
23005 hup_handler ()
23007 @dots{}
23009 @end group
23010 @end example
23011 @end defmac
23013 @defmac AC_UID_T
23014 @acindex{UID_T}
23015 Replaced by @code{AC_TYPE_UID_T} (@pxref{AC_TYPE_UID_T}).
23016 @end defmac
23018 @defmac AC_UNISTD_H
23019 @acindex{UNISTD_H}
23020 Same as @samp{AC_CHECK_HEADERS([unistd.h])} (@pxref{AC_CHECK_HEADERS}).
23021 @end defmac
23023 @defmac AC_USG
23024 @acindex{USG}
23025 @cvindex USG
23026 Define @code{USG} if the BSD string functions are defined in
23027 @file{strings.h}.  You should no longer depend upon @code{USG}, but on
23028 @code{HAVE_STRING_H}; see @ref{Standard Symbols}.
23029 @end defmac
23031 @defmac AC_UTIME_NULL
23032 @acindex{UTIME_NULL}
23033 Replaced by @code{AC_FUNC_UTIME_NULL} (@pxref{AC_FUNC_UTIME_NULL}).
23034 @end defmac
23036 @defmac AC_VALIDATE_CACHED_SYSTEM_TUPLE (@ovar{cmd})
23037 @acindex{VALIDATE_CACHED_SYSTEM_TUPLE}
23038 If the cache file is inconsistent with the current host, target and
23039 build system types, it used to execute @var{cmd} or print a default
23040 error message.  This is now handled by default.
23041 @end defmac
23043 @defmac AC_VERBOSE (@var{result-description})
23044 @acindex{VERBOSE}
23045 Replaced by @code{AC_MSG_RESULT} (@pxref{AC_MSG_RESULT}).
23046 @end defmac
23048 @defmac AC_VFORK
23049 @acindex{VFORK}
23050 Replaced by @code{AC_FUNC_FORK} (@pxref{AC_FUNC_FORK}).
23051 @end defmac
23053 @defmac AC_VPRINTF
23054 @acindex{VPRINTF}
23055 Replaced by @code{AC_FUNC_VPRINTF} (@pxref{AC_FUNC_VPRINTF}).
23056 @end defmac
23058 @defmac AC_WAIT3
23059 @acindex{WAIT3}
23060 This macro was renamed @code{AC_FUNC_WAIT3}.  However, these days
23061 portable programs should use @code{waitpid}, not @code{wait3}, as
23062 @code{wait3} has been removed from Posix.
23063 @end defmac
23065 @defmac AC_WARN
23066 @acindex{WARN}
23067 Replaced by @code{AC_MSG_WARN} (@pxref{AC_MSG_WARN}).
23068 @end defmac
23070 @defmac AC_WITH (@var{package}, @var{action-if-given}, @
23071   @ovar{action-if-not-given})
23072 @acindex{WITH}
23073 This is an obsolete version of @code{AC_ARG_WITH} that does not
23074 support providing a help string (@pxref{AC_ARG_WITH}).
23075 @end defmac
23077 @defmac AC_WORDS_BIGENDIAN
23078 @acindex{WORDS_BIGENDIAN}
23079 Replaced by @code{AC_C_BIGENDIAN} (@pxref{AC_C_BIGENDIAN}).
23080 @end defmac
23082 @defmac AC_XENIX_DIR
23083 @acindex{XENIX_DIR}
23084 @ovindex LIBS
23085 This macro used to add @option{-lx} to output variable @code{LIBS} if on
23086 Xenix.  Also, if @file{dirent.h} is being checked for, added
23087 @option{-ldir} to @code{LIBS}.  Now it is merely an alias of
23088 @code{AC_HEADER_DIRENT} instead, plus some code to detect whether
23089 running XENIX on which you should not depend:
23091 @example
23092 AC_MSG_CHECKING([for Xenix])
23093 AC_EGREP_CPP([yes],
23094 [#if defined M_XENIX && !defined M_UNIX
23095   yes
23096 #endif],
23097              [AC_MSG_RESULT([yes]); XENIX=yes],
23098              [AC_MSG_RESULT([no]); XENIX=])
23099 @end example
23100 @noindent
23101 Don't use this macro, the dignified means to check the nature of the
23102 host is using @code{AC_CANONICAL_HOST} (@pxref{Canonicalizing}).
23103 @end defmac
23105 @defmac AC_YYTEXT_POINTER
23106 @acindex{YYTEXT_POINTER}
23107 This macro was renamed @code{AC_DECL_YYTEXT}, which in turn was
23108 integrated into @code{AC_PROG_LEX} (@pxref{AC_PROG_LEX}).
23109 @end defmac
23111 @node Autoconf 1
23112 @section Upgrading From Version 1
23113 @cindex Upgrading autoconf
23114 @cindex Autoconf upgrading
23116 Autoconf version 2 is mostly backward compatible with version 1.
23117 However, it introduces better ways to do some things, and doesn't
23118 support some of the ugly things in version 1.  So, depending on how
23119 sophisticated your @file{configure.ac} files are, you might have to do
23120 some manual work in order to upgrade to version 2.  This chapter points
23121 out some problems to watch for when upgrading.  Also, perhaps your
23122 @command{configure} scripts could benefit from some of the new features in
23123 version 2; the changes are summarized in the file @file{NEWS} in the
23124 Autoconf distribution.
23126 @menu
23127 * Changed File Names::          Files you might rename
23128 * Changed Makefiles::           New things to put in @file{Makefile.in}
23129 * Changed Macros::              Macro calls you might replace
23130 * Changed Results::             Changes in how to check test results
23131 * Changed Macro Writing::       Better ways to write your own macros
23132 @end menu
23134 @node Changed File Names
23135 @subsection Changed File Names
23137 If you have an @file{aclocal.m4} installed with Autoconf (as opposed to
23138 in a particular package's source directory), you must rename it to
23139 @file{acsite.m4}.  @xref{autoconf Invocation}.
23141 If you distribute @file{install.sh} with your package, rename it to
23142 @file{install-sh} so @command{make} builtin rules don't inadvertently
23143 create a file called @file{install} from it.  @code{AC_PROG_INSTALL}
23144 looks for the script under both names, but it is best to use the new name.
23146 If you were using @file{config.h.top}, @file{config.h.bot}, or
23147 @file{acconfig.h}, you still can, but you have less clutter if you
23148 use the @code{AH_} macros.  @xref{Autoheader Macros}.
23150 @node Changed Makefiles
23151 @subsection Changed Makefiles
23153 Add @samp{@@CFLAGS@@}, @samp{@@CPPFLAGS@@}, and @samp{@@LDFLAGS@@} in
23154 your @file{Makefile.in} files, so they can take advantage of the values
23155 of those variables in the environment when @command{configure} is run.
23156 Doing this isn't necessary, but it's a convenience for users.
23158 Also add @samp{@@configure_input@@} in a comment to each input file for
23159 @code{AC_OUTPUT}, so that the output files contain a comment saying
23160 they were produced by @command{configure}.  Automatically selecting the
23161 right comment syntax for all the kinds of files that people call
23162 @code{AC_OUTPUT} on became too much work.
23164 Add @file{config.log} and @file{config.cache} to the list of files you
23165 remove in @code{distclean} targets.
23167 If you have the following in @file{Makefile.in}:
23169 @example
23170 prefix = /usr/local
23171 exec_prefix = $(prefix)
23172 @end example
23174 @noindent
23175 you must change it to:
23177 @example
23178 prefix = @@prefix@@
23179 exec_prefix = @@exec_prefix@@
23180 @end example
23182 @noindent
23183 The old behavior of replacing those variables without @samp{@@}
23184 characters around them has been removed.
23186 @node Changed Macros
23187 @subsection Changed Macros
23189 Many of the macros were renamed in Autoconf version 2.  You can still
23190 use the old names, but the new ones are clearer, and it's easier to find
23191 the documentation for them.  @xref{Obsolete Macros}, for a table showing the
23192 new names for the old macros.  Use the @command{autoupdate} program to
23193 convert your @file{configure.ac} to using the new macro names.
23194 @xref{autoupdate Invocation}.
23196 Some macros have been superseded by similar ones that do the job better,
23197 but are not call-compatible.  If you get warnings about calling obsolete
23198 macros while running @command{autoconf}, you may safely ignore them, but
23199 your @command{configure} script generally works better if you follow
23200 the advice that is printed about what to replace the obsolete macros with.  In
23201 particular, the mechanism for reporting the results of tests has
23202 changed.  If you were using @command{echo} or @code{AC_VERBOSE} (perhaps
23203 via @code{AC_COMPILE_CHECK}), your @command{configure} script's output
23204 looks better if you switch to @code{AC_MSG_CHECKING} and
23205 @code{AC_MSG_RESULT}.  @xref{Printing Messages}.  Those macros work best
23206 in conjunction with cache variables.  @xref{Caching Results}.
23210 @node Changed Results
23211 @subsection Changed Results
23213 If you were checking the results of previous tests by examining the
23214 shell variable @code{DEFS}, you need to switch to checking the values of
23215 the cache variables for those tests.  @code{DEFS} no longer exists while
23216 @command{configure} is running; it is only created when generating output
23217 files.  This difference from version 1 is because properly quoting the
23218 contents of that variable turned out to be too cumbersome and
23219 inefficient to do every time @code{AC_DEFINE} is called.  @xref{Cache
23220 Variable Names}.
23222 For example, here is a @file{configure.ac} fragment written for Autoconf
23223 version 1:
23225 @example
23226 AC_HAVE_FUNCS(syslog)
23227 case "$DEFS" in
23228 *-DHAVE_SYSLOG*) ;;
23229 *) # syslog is not in the default libraries.  See if it's in some other.
23230   saved_LIBS="$LIBS"
23231   for lib in bsd socket inet; do
23232     AC_CHECKING(for syslog in -l$lib)
23233     LIBS="-l$lib $saved_LIBS"
23234     AC_HAVE_FUNCS(syslog)
23235     case "$DEFS" in
23236     *-DHAVE_SYSLOG*) break ;;
23237     *) ;;
23238     esac
23239     LIBS="$saved_LIBS"
23240   done ;;
23241 esac
23242 @end example
23244 Here is a way to write it for version 2:
23246 @example
23247 AC_CHECK_FUNCS([syslog])
23248 if test "x$ac_cv_func_syslog" = xno; then
23249   # syslog is not in the default libraries.  See if it's in some other.
23250   for lib in bsd socket inet; do
23251     AC_CHECK_LIB([$lib], [syslog], [AC_DEFINE([HAVE_SYSLOG])
23252       LIBS="-l$lib $LIBS"; break])
23253   done
23255 @end example
23257 If you were working around bugs in @code{AC_DEFINE_UNQUOTED} by adding
23258 backslashes before quotes, you need to remove them.  It now works
23259 predictably, and does not treat quotes (except back quotes) specially.
23260 @xref{Setting Output Variables}.
23262 All of the Boolean shell variables set by Autoconf macros now use
23263 @samp{yes} for the true value.  Most of them use @samp{no} for false,
23264 though for backward compatibility some use the empty string instead.  If
23265 you were relying on a shell variable being set to something like 1 or
23266 @samp{t} for true, you need to change your tests.
23268 @node Changed Macro Writing
23269 @subsection Changed Macro Writing
23271 When defining your own macros, you should now use @code{AC_DEFUN}
23272 instead of @code{define}.  @code{AC_DEFUN} automatically calls
23273 @code{AC_PROVIDE} and ensures that macros called via @code{AC_REQUIRE}
23274 do not interrupt other macros, to prevent nested @samp{checking@dots{}}
23275 messages on the screen.  There's no actual harm in continuing to use the
23276 older way, but it's less convenient and attractive.  @xref{Macro
23277 Definitions}.
23279 You probably looked at the macros that came with Autoconf as a guide for
23280 how to do things.  It would be a good idea to take a look at the new
23281 versions of them, as the style is somewhat improved and they take
23282 advantage of some new features.
23284 If you were doing tricky things with undocumented Autoconf internals
23285 (macros, variables, diversions), check whether you need to change
23286 anything to account for changes that have been made.  Perhaps you can
23287 even use an officially supported technique in version 2 instead of
23288 kludging.  Or perhaps not.
23290 To speed up your locally written feature tests, add caching to them.
23291 See whether any of your tests are of general enough usefulness to
23292 encapsulate them into macros that you can share.
23295 @node Autoconf 2.13
23296 @section Upgrading From Version 2.13
23297 @cindex Upgrading autoconf
23298 @cindex Autoconf upgrading
23300 The introduction of the previous section (@pxref{Autoconf 1}) perfectly
23301 suits this section@enddots{}
23303 @quotation
23304 Autoconf version 2.50 is mostly backward compatible with version 2.13.
23305 However, it introduces better ways to do some things, and doesn't
23306 support some of the ugly things in version 2.13.  So, depending on how
23307 sophisticated your @file{configure.ac} files are, you might have to do
23308 some manual work in order to upgrade to version 2.50.  This chapter
23309 points out some problems to watch for when upgrading.  Also, perhaps
23310 your @command{configure} scripts could benefit from some of the new
23311 features in version 2.50; the changes are summarized in the file
23312 @file{NEWS} in the Autoconf distribution.
23313 @end quotation
23315 @menu
23316 * Changed Quotation::           Broken code which used to work
23317 * New Macros::                  Interaction with foreign macros
23318 * Hosts and Cross-Compilation::  Bugward compatibility kludges
23319 * AC_LIBOBJ vs LIBOBJS::        LIBOBJS is a forbidden token
23320 * AC_ACT_IFELSE vs AC_TRY_ACT::  A more generic scheme for testing sources
23321 @end menu
23323 @node Changed Quotation
23324 @subsection Changed Quotation
23326 The most important changes are invisible to you: the implementation of
23327 most macros have completely changed.  This allowed more factorization of
23328 the code, better error messages, a higher uniformity of the user's
23329 interface etc.  Unfortunately, as a side effect, some construct which
23330 used to (miraculously) work might break starting with Autoconf 2.50.
23331 The most common culprit is bad quotation.
23333 For instance, in the following example, the message is not properly
23334 quoted:
23336 @example
23337 AC_INIT
23338 AC_CHECK_HEADERS(foo.h, ,
23339   AC_MSG_ERROR(cannot find foo.h, bailing out))
23340 AC_OUTPUT
23341 @end example
23343 @noindent
23344 Autoconf 2.13 simply ignores it:
23346 @example
23347 $ @kbd{autoconf-2.13; ./configure --silent}
23348 creating cache ./config.cache
23349 configure: error: cannot find foo.h
23351 @end example
23353 @noindent
23354 while Autoconf 2.50 produces a broken @file{configure}:
23356 @example
23357 $ @kbd{autoconf-2.50; ./configure --silent}
23358 configure: error: cannot find foo.h
23359 ./configure: exit: bad non-numeric arg `bailing'
23360 ./configure: exit: bad non-numeric arg `bailing'
23362 @end example
23364 The message needs to be quoted, and the @code{AC_MSG_ERROR} invocation
23365 too!
23367 @example
23368 AC_INIT([Example], [1.0], [bug-example@@example.org])
23369 AC_CHECK_HEADERS([foo.h], [],
23370   [AC_MSG_ERROR([cannot find foo.h, bailing out])])
23371 AC_OUTPUT
23372 @end example
23374 Many many (and many more) Autoconf macros were lacking proper quotation,
23375 including no less than@dots{} @code{AC_DEFUN} itself!
23377 @example
23378 $ @kbd{cat configure.in}
23379 AC_DEFUN([AC_PROG_INSTALL],
23380 [# My own much better version
23382 AC_INIT
23383 AC_PROG_INSTALL
23384 AC_OUTPUT
23385 $ @kbd{autoconf-2.13}
23386 autoconf: Undefined macros:
23387 ***BUG in Autoconf--please report*** AC_FD_MSG
23388 ***BUG in Autoconf--please report*** AC_EPI
23389 configure.in:1:AC_DEFUN([AC_PROG_INSTALL],
23390 configure.in:5:AC_PROG_INSTALL
23391 $ @kbd{autoconf-2.50}
23393 @end example
23396 @node New Macros
23397 @subsection New Macros
23399 @cindex undefined macro
23400 @cindex @code{_m4_divert_diversion}
23402 While Autoconf was relatively dormant in the late 1990s, Automake
23403 provided Autoconf-like macros for a while.  Starting with Autoconf 2.50
23404 in 2001, Autoconf provided
23405 versions of these macros, integrated in the @code{AC_} namespace,
23406 instead of @code{AM_}.  But in order to ease the upgrading via
23407 @command{autoupdate}, bindings to such @code{AM_} macros are provided.
23409 Unfortunately older versions of Automake (e.g., Automake 1.4)
23410 did not quote the names of these macros.
23411 Therefore, when @command{m4} finds something like
23412 @samp{AC_DEFUN(AM_TYPE_PTRDIFF_T, @dots{})} in @file{aclocal.m4},
23413 @code{AM_TYPE_PTRDIFF_T} is
23414 expanded, replaced with its Autoconf definition.
23416 Fortunately Autoconf catches pre-@code{AC_INIT} expansions, and
23417 complains, in its own words:
23419 @example
23420 $ @kbd{cat configure.ac}
23421 AC_INIT([Example], [1.0], [bug-example@@example.org])
23422 AM_TYPE_PTRDIFF_T
23423 $ @kbd{aclocal-1.4}
23424 $ @kbd{autoconf}
23425 aclocal.m4:17: error: m4_defn: undefined macro: _m4_divert_diversion
23426 aclocal.m4:17: the top level
23427 autom4te: m4 failed with exit status: 1
23429 @end example
23431 Modern versions of Automake no longer define most of these
23432 macros, and properly quote the names of the remaining macros.
23433 If you must use an old Automake, do not depend upon macros from Automake
23434 as it is simply not its job
23435 to provide macros (but the one it requires itself):
23437 @example
23438 $ @kbd{cat configure.ac}
23439 AC_INIT([Example], [1.0], [bug-example@@example.org])
23440 AM_TYPE_PTRDIFF_T
23441 $ @kbd{rm aclocal.m4}
23442 $ @kbd{autoupdate}
23443 autoupdate: `configure.ac' is updated
23444 $ @kbd{cat configure.ac}
23445 AC_INIT([Example], [1.0], [bug-example@@example.org])
23446 AC_CHECK_TYPES([ptrdiff_t])
23447 $ @kbd{aclocal-1.4}
23448 $ @kbd{autoconf}
23450 @end example
23453 @node Hosts and Cross-Compilation
23454 @subsection Hosts and Cross-Compilation
23455 @cindex Cross compilation
23457 Based on the experience of compiler writers, and after long public
23458 debates, many aspects of the cross-compilation chain have changed:
23460 @itemize @minus
23461 @item
23462 the relationship between the build, host, and target architecture types,
23464 @item
23465 the command line interface for specifying them to @command{configure},
23467 @item
23468 the variables defined in @command{configure},
23470 @item
23471 the enabling of cross-compilation mode.
23472 @end itemize
23474 @sp 1
23476 The relationship between build, host, and target have been cleaned up:
23477 the chain of default is now simply: target defaults to host, host to
23478 build, and build to the result of @command{config.guess}.  Nevertheless,
23479 in order to ease the transition from 2.13 to 2.50, the following
23480 transition scheme is implemented.  @emph{Do not rely on it}, as it will
23481 be completely disabled in a couple of releases (we cannot keep it, as it
23482 proves to cause more problems than it cures).
23484 They all default to the result of running @command{config.guess}, unless
23485 you specify either @option{--build} or @option{--host}.  In this case,
23486 the default becomes the system type you specified.  If you specify both,
23487 and they're different, @command{configure} enters cross compilation
23488 mode, so it doesn't run any tests that require execution.
23490 Hint: if you mean to override the result of @command{config.guess},
23491 prefer @option{--build} over @option{--host}.  In the future,
23492 @option{--host} will not override the name of the build system type.
23493 Whenever you specify @option{--host}, be sure to specify @option{--build}
23494 too.
23496 @sp 1
23498 For backward compatibility, @command{configure} accepts a system
23499 type as an option by itself.  Such an option overrides the
23500 defaults for build, host, and target system types.  The following
23501 configure statement configures a cross toolchain that runs on
23502 NetBSD/alpha but generates code for GNU Hurd/sparc,
23503 which is also the build platform.
23505 @example
23506 ./configure --host=alpha-netbsd sparc-gnu
23507 @end example
23509 @sp 1
23511 In Autoconf 2.13 and before, the variables @code{build}, @code{host},
23512 and @code{target} had a different semantics before and after the
23513 invocation of @code{AC_CANONICAL_BUILD} etc.  Now, the argument of
23514 @option{--build} is strictly copied into @code{build_alias}, and is left
23515 empty otherwise.  After the @code{AC_CANONICAL_BUILD}, @code{build} is
23516 set to the canonicalized build type.  To ease the transition, before,
23517 its contents is the same as that of @code{build_alias}.  Do @emph{not}
23518 rely on this broken feature.
23520 For consistency with the backward compatibility scheme exposed above,
23521 when @option{--host} is specified but @option{--build} isn't, the build
23522 system is assumed to be the same as @option{--host}, and
23523 @samp{build_alias} is set to that value.  Eventually, this
23524 historically incorrect behavior will go away.
23526 @sp 1
23528 The former scheme to enable cross-compilation proved to cause more harm
23529 than good, in particular, it used to be triggered too easily, leaving
23530 regular end users puzzled in front of cryptic error messages.
23531 @command{configure} could even enter cross-compilation mode only
23532 because the compiler was not functional.  This is mainly because
23533 @command{configure} used to try to detect cross-compilation, instead of
23534 waiting for an explicit flag from the user.
23536 Now, @command{configure} enters cross-compilation mode if and only if
23537 @option{--host} is passed.
23539 That's the short documentation.  To ease the transition between 2.13 and
23540 its successors, a more complicated scheme is implemented.  @emph{Do not
23541 rely on the following}, as it will be removed in the near future.
23543 If you specify @option{--host}, but not @option{--build}, when
23544 @command{configure} performs the first compiler test it tries to run
23545 an executable produced by the compiler.  If the execution fails, it
23546 enters cross-compilation mode.  This is fragile.  Moreover, by the time
23547 the compiler test is performed, it may be too late to modify the
23548 build-system type: other tests may have already been performed.
23549 Therefore, whenever you specify @option{--host}, be sure to specify
23550 @option{--build} too.
23552 @example
23553 ./configure --build=i686-pc-linux-gnu --host=m68k-coff
23554 @end example
23556 @noindent
23557 enters cross-compilation mode.  The former interface, which
23558 consisted in setting the compiler to a cross-compiler without informing
23559 @command{configure} is obsolete.  For instance, @command{configure}
23560 fails if it can't run the code generated by the specified compiler if you
23561 configure as follows:
23563 @example
23564 ./configure CC=m68k-coff-gcc
23565 @end example
23568 @node AC_LIBOBJ vs LIBOBJS
23569 @subsection @code{AC_LIBOBJ} vs.@: @code{LIBOBJS}
23571 Up to Autoconf 2.13, the replacement of functions was triggered via the
23572 variable @code{LIBOBJS}.  Since Autoconf 2.50, the macro
23573 @code{AC_LIBOBJ} should be used instead (@pxref{Generic Functions}).
23574 Starting at Autoconf 2.53, the use of @code{LIBOBJS} is an error.
23576 This change is mandated by the unification of the GNU Build System
23577 components.  In particular, the various fragile techniques used to parse
23578 a @file{configure.ac} are all replaced with the use of traces.  As a
23579 consequence, any action must be traceable, which obsoletes critical
23580 variable assignments.  Fortunately, @code{LIBOBJS} was the only problem,
23581 and it can even be handled gracefully (read, ``without your having to
23582 change something'').
23584 There were two typical uses of @code{LIBOBJS}: asking for a replacement
23585 function, and adjusting @code{LIBOBJS} for Automake and/or Libtool.
23587 @sp 1
23589 As for function replacement, the fix is immediate: use
23590 @code{AC_LIBOBJ}.  For instance:
23592 @example
23593 LIBOBJS="$LIBOBJS fnmatch.o"
23594 LIBOBJS="$LIBOBJS malloc.$ac_objext"
23595 @end example
23597 @noindent
23598 should be replaced with:
23600 @example
23601 AC_LIBOBJ([fnmatch])
23602 AC_LIBOBJ([malloc])
23603 @end example
23605 @sp 1
23607 @ovindex LIBOBJDIR
23608 When used with Automake 1.10 or newer, a suitable value for
23609 @code{LIBOBJDIR} is set so that the @code{LIBOBJS} and @code{LTLIBOBJS}
23610 can be referenced from any @file{Makefile.am}.  Even without Automake,
23611 arranging for @code{LIBOBJDIR} to be set correctly enables
23612 referencing @code{LIBOBJS} and @code{LTLIBOBJS} in another directory.
23613 The @code{LIBOBJDIR} feature is experimental.
23616 @node AC_ACT_IFELSE vs AC_TRY_ACT
23617 @subsection @code{AC_@var{ACT}_IFELSE} vs.@: @code{AC_TRY_@var{ACT}}
23618 @c the anchor keeps the old node name, to try to avoid breaking links
23619 @anchor{AC_FOO_IFELSE vs AC_TRY_FOO}
23621 @acindex{@var{ACT}_IFELSE}
23622 @acindex{TRY_@var{ACT}}
23623 Since Autoconf 2.50, internal codes uses @code{AC_PREPROC_IFELSE},
23624 @code{AC_COMPILE_IFELSE}, @code{AC_LINK_IFELSE}, and
23625 @code{AC_RUN_IFELSE} on one hand and @code{AC_LANG_SOURCE},
23626 and @code{AC_LANG_PROGRAM} on the other hand instead of the deprecated
23627 @code{AC_TRY_CPP}, @code{AC_TRY_COMPILE}, @code{AC_TRY_LINK}, and
23628 @code{AC_TRY_RUN}.  The motivations where:
23629 @itemize @minus
23630 @item
23631 a more consistent interface: @code{AC_TRY_COMPILE} etc.@: were double
23632 quoting their arguments;
23634 @item
23635 the combinatoric explosion is solved by decomposing on the one hand the
23636 generation of sources, and on the other hand executing the program;
23638 @item
23639 this scheme helps supporting more languages than plain C and C++.
23640 @end itemize
23642 In addition to the change of syntax, the philosophy has changed too:
23643 while emphasis was put on speed at the expense of accuracy, today's
23644 Autoconf promotes accuracy of the testing framework at, ahem@dots{}, the
23645 expense of speed.
23648 As a perfect example of what is @emph{not} to be done, here is how to
23649 find out whether a header file contains a particular declaration, such
23650 as a typedef, a structure, a structure member, or a function.  Use
23651 @code{AC_EGREP_HEADER} instead of running @code{grep} directly on the
23652 header file; on some systems the symbol might be defined in another
23653 header file that the file you are checking includes.
23655 As a (bad) example, here is how you should not check for C preprocessor
23656 symbols, either defined by header files or predefined by the C
23657 preprocessor: using @code{AC_EGREP_CPP}:
23659 @example
23660 @group
23661 AC_EGREP_CPP(yes,
23662 [#ifdef _AIX
23663   yes
23664 #endif
23665 ], is_aix=yes, is_aix=no)
23666 @end group
23667 @end example
23669 The above example, properly written would (i) use
23670 @code{AC_LANG_PROGRAM}, and (ii) run the compiler:
23672 @example
23673 @group
23674 AC_COMPILE_IFELSE([AC_LANG_PROGRAM(
23675 [[#ifndef _AIX
23676  error: This isn't AIX!
23677 #endif
23678 ]])],
23679                    [is_aix=yes],
23680                    [is_aix=no])
23681 @end group
23682 @end example
23685 @c ============================= Generating Test Suites with Autotest
23687 @node Using Autotest
23688 @chapter Generating Test Suites with Autotest
23690 @cindex Autotest
23692 @display
23693 @strong{N.B.: This section describes a feature which is still
23694 stabilizing.  Although we believe that Autotest is useful as-is, this
23695 documentation describes an interface which might change in the future:
23696 do not depend upon Autotest without subscribing to the Autoconf mailing
23697 lists.}
23698 @end display
23700 It is paradoxical that portable projects depend on nonportable tools
23701 to run their test suite.  Autoconf by itself is the paragon of this
23702 problem: although it aims at perfectly portability, up to 2.13 its
23703 test suite was using DejaGNU, a rich and complex testing
23704 framework, but which is far from being standard on Posix systems.
23705 Worse yet, it was likely to be missing on the most fragile platforms,
23706 the very platforms that are most likely to torture Autoconf and
23707 exhibit deficiencies.
23709 To circumvent this problem, many package maintainers have developed their
23710 own testing framework, based on simple shell scripts whose sole outputs
23711 are exit status values describing whether the test succeeded.  Most of
23712 these tests share common patterns, and this can result in lots of
23713 duplicated code and tedious maintenance.
23715 Following exactly the same reasoning that yielded to the inception of
23716 Autoconf, Autotest provides a test suite generation framework, based on
23717 M4 macros building a portable shell script.  The suite itself is
23718 equipped with automatic logging and tracing facilities which greatly
23719 diminish the interaction with bug reporters, and simple timing reports.
23721 Autoconf itself has been using Autotest for years, and we do attest that
23722 it has considerably improved the strength of the test suite and the
23723 quality of bug reports.  Other projects are known to use some generation
23724 of Autotest, such as Bison, Free Recode, Free Wdiff, GNU Tar, each of
23725 them with different needs, and this usage has validated Autotest as a general
23726 testing framework.
23728 Nonetheless, compared to DejaGNU, Autotest is inadequate for
23729 interactive tool testing, which is probably its main limitation.
23731 @menu
23732 * Using an Autotest Test Suite::  Autotest and the user
23733 * Writing Testsuites::          Autotest macros
23734 * testsuite Invocation::        Running @command{testsuite} scripts
23735 * Making testsuite Scripts::    Using autom4te to create @command{testsuite}
23736 @end menu
23738 @node Using an Autotest Test Suite
23739 @section Using an Autotest Test Suite
23741 @menu
23742 * testsuite Scripts::           The concepts of Autotest
23743 * Autotest Logs::               Their contents
23744 @end menu
23746 @node testsuite Scripts
23747 @subsection @command{testsuite} Scripts
23749 @cindex @command{testsuite}
23751 Generating testing or validation suites using Autotest is rather easy.
23752 The whole validation suite is held in a file to be processed through
23753 @command{autom4te}, itself using GNU M4 under the hood, to
23754 produce a stand-alone Bourne shell script which then gets distributed.
23755 Neither @command{autom4te} nor GNU M4 are needed at
23756 the installer's end.
23758 @cindex test group
23759 Each test of the validation suite should be part of some test group.  A
23760 @dfn{test group} is a sequence of interwoven tests that ought to be
23761 executed together, usually because one test in the group creates data
23762 files than a later test in the same group needs to read.  Complex test
23763 groups make later debugging more tedious.  It is much better to
23764 keep only a few tests per test group.  Ideally there is only one test
23765 per test group.
23767 For all but the simplest packages, some file such as @file{testsuite.at}
23768 does not fully hold all test sources, as these are often easier to
23769 maintain in separate files.  Each of these separate files holds a single
23770 test group, or a sequence of test groups all addressing some common
23771 functionality in the package.  In such cases, @file{testsuite.at}
23772 merely initializes the validation suite, and sometimes does elementary
23773 health checking, before listing include statements for all other test
23774 files.  The special file @file{package.m4}, containing the
23775 identification of the package, is automatically included if found.
23777 A convenient alternative consists in moving all the global issues
23778 (local Autotest macros, elementary health checking, and @code{AT_INIT}
23779 invocation) into the file @code{local.at}, and making
23780 @file{testsuite.at} be a simple list of @code{m4_include} of sub test
23781 suites.  In such case, generating the whole test suite or pieces of it
23782 is only a matter of choosing the @command{autom4te} command line
23783 arguments.
23785 The validation scripts that Autotest produces are by convention called
23786 @command{testsuite}.  When run, @command{testsuite} executes each test
23787 group in turn, producing only one summary line per test to say if that
23788 particular test succeeded or failed.  At end of all tests, summarizing
23789 counters get printed.  One debugging directory is left for each test
23790 group which failed, if any: such directories are named
23791 @file{testsuite.dir/@var{nn}}, where @var{nn} is the sequence number of
23792 the test group, and they include:
23794 @itemize @bullet
23795 @item a debugging script named @file{run} which reruns the test in
23796 @dfn{debug mode} (@pxref{testsuite Invocation}).  The automatic generation
23797 of debugging scripts has the purpose of easing the chase for bugs.
23799 @item all the files created with @code{AT_DATA}
23801 @item all the Erlang source code files created with @code{AT_CHECK_EUNIT}
23803 @item a log of the run, named @file{testsuite.log}
23804 @end itemize
23806 In the ideal situation, none of the tests fail, and consequently no
23807 debugging directory is left behind for validation.
23809 It often happens in practice that individual tests in the validation
23810 suite need to get information coming out of the configuration process.
23811 Some of this information, common for all validation suites, is provided
23812 through the file @file{atconfig}, automatically created by
23813 @code{AC_CONFIG_TESTDIR}.  For configuration informations which your
23814 testing environment specifically needs, you might prepare an optional
23815 file named @file{atlocal.in}, instantiated by @code{AC_CONFIG_FILES}.
23816 The configuration process produces @file{atconfig} and @file{atlocal}
23817 out of these two input files, and these two produced files are
23818 automatically read by the @file{testsuite} script.
23820 Here is a diagram showing the relationship between files.
23822 @noindent
23823 Files used in preparing a software package for distribution:
23825 @example
23826                 [package.m4] -->.
23827                                  \
23828 subfile-1.at ->.  [local.at] ---->+
23829     ...         \                  \
23830 subfile-i.at ---->-- testsuite.at -->-- autom4te* -->testsuite
23831     ...         /
23832 subfile-n.at ->'
23833 @end example
23835 @noindent
23836 Files used in configuring a software package:
23838 @example
23839                                      .--> atconfig
23840                                     /
23841 [atlocal.in] -->  config.status* --<
23842                                     \
23843                                      `--> [atlocal]
23844 @end example
23846 @noindent
23847 Files created during test suite execution:
23849 @example
23850 atconfig -->.                    .--> testsuite.log
23851              \                  /
23852               >-- testsuite* --<
23853              /                  \
23854 [atlocal] ->'                    `--> [testsuite.dir]
23855 @end example
23858 @node Autotest Logs
23859 @subsection Autotest Logs
23861 When run, the test suite creates a log file named after itself, e.g., a
23862 test suite named @command{testsuite} creates @file{testsuite.log}.  It
23863 contains a lot of information, usually more than maintainers actually
23864 need, but therefore most of the time it contains all that is needed:
23866 @table @asis
23867 @item command line arguments
23868 A bad but unfortunately widespread habit consists of
23869 setting environment variables before the command, such as in
23870 @samp{CC=my-home-grown-cc ./testsuite}.  The test suite does not
23871 know this change, hence (i) it cannot report it to you, and (ii)
23872 it cannot preserve the value of @code{CC} for subsequent runs.
23873 Autoconf faced exactly the same problem, and solved it by asking
23874 users to pass the variable definitions as command line arguments.
23875 Autotest requires this rule, too, but has no means to enforce it; the log
23876 then contains a trace of the variables that were changed by the user.
23878 @item @file{ChangeLog} excerpts
23879 The topmost lines of all the @file{ChangeLog} files found in the source
23880 hierarchy.  This is especially useful when bugs are reported against
23881 development versions of the package, since the version string does not
23882 provide sufficient information to know the exact state of the sources
23883 the user compiled.  Of course, this relies on the use of a
23884 @file{ChangeLog}.
23886 @item build machine
23887 Running a test suite in a cross-compile environment is not an easy task,
23888 since it would mean having the test suite run on a machine @var{build},
23889 while running programs on a machine @var{host}.  It is much simpler to
23890 run both the test suite and the programs on @var{host}, but then, from
23891 the point of view of the test suite, there remains a single environment,
23892 @var{host} = @var{build}.  The log contains relevant information on the
23893 state of the @var{build} machine, including some important environment
23894 variables.
23895 @c FIXME: How about having an M4sh macro to say `hey, log the value
23896 @c of `@dots{}'?  This would help both Autoconf and Autotest.
23898 @item tested programs
23899 The absolute file name and answers to @option{--version} of the tested
23900 programs (see @ref{Writing Testsuites}, @code{AT_TESTED}).
23902 @item configuration log
23903 The contents of @file{config.log}, as created by @command{configure},
23904 are appended.  It contains the configuration flags and a detailed report
23905 on the configuration itself.
23906 @end table
23909 @node Writing Testsuites
23910 @section Writing @file{testsuite.at}
23912 The @file{testsuite.at} is a Bourne shell script making use of special
23913 Autotest M4 macros.  It often contains a call to @code{AT_INIT} near
23914 its beginning followed by one call to @code{m4_include} per source file
23915 for tests.  Each such included file, or the remainder of
23916 @file{testsuite.at} if include files are not used, contain a sequence of
23917 test groups.  Each test group begins with a call to @code{AT_SETUP},
23918 then an arbitrary number of shell commands or calls to @code{AT_CHECK},
23919 and then completes with a call to @code{AT_CLEANUP}.  Multiple test
23920 groups can be categorized by a call to @code{AT_BANNER}.
23922 All of the public Autotest macros have all-uppercase names in the
23923 namespace @samp{^AT_} to prevent them from accidentally conflicting with
23924 other text; Autoconf also reserves the namespace @samp{^_AT_} for
23925 internal macros.  All shell variables used in the testsuite for internal
23926 purposes have mostly-lowercase names starting with @samp{at_}.  Autotest
23927 also uses here-document delimiters in the namespace @samp{^_AT[A-Z]}, and
23928 makes use of the file system namespace @samp{^at-}.
23930 Since Autoconf is built on top of M4sugar (@pxref{Programming in
23931 M4sugar}) and M4sh (@pxref{Programming in M4sh}), you must also be aware
23932 of those namespaces (@samp{^_?\(m4\|AS\)_}).  In general, you
23933 @emph{should not use} the namespace of a package that does not own the
23934 macro or shell code you are writing.
23936 @defmac AT_INIT (@ovar{name})
23937 @atindex{INIT}
23938 @c FIXME: Not clear, plus duplication of the information.
23939 Initialize Autotest.  Giving a @var{name} to the test suite is
23940 encouraged if your package includes several test suites.  Before this
23941 macro is called, @code{AT_PACKAGE_STRING} and
23942 @code{AT_PACKAGE_BUGREPORT} must be defined, which are used to display
23943 information about the testsuite to the user.  Typically, these macros
23944 are provided by a file @file{package.m4} built by @command{make}
23945 (@pxref{Making testsuite Scripts}), in order to inherit the package
23946 name, version, and bug reporting address from @file{configure.ac}.
23947 @end defmac
23949 @defmac AT_COPYRIGHT (@var{copyright-notice})
23950 @atindex{COPYRIGHT}
23951 @cindex Copyright Notice
23952 State that, in addition to the Free Software Foundation's copyright on
23953 the Autotest macros, parts of your test suite are covered by
23954 @var{copyright-notice}.
23956 The @var{copyright-notice} shows up in both the head of
23957 @command{testsuite} and in @samp{testsuite --version}.
23958 @end defmac
23960 @defmac AT_ARG_OPTION (@var{options}, @var{help-text}, @
23961   @ovar{action-if-given}, @ovar{action-if-not-given})
23962 @atindex{ARG_OPTION}
23963 Accept options from the space-separated list @var{options}, a list that
23964 has leading dashes removed from the options.  Long options will be
23965 prefixed with @samp{--}, single-character options with @samp{-}.  The
23966 first word in this list is the primary @var{option}, any others are
23967 assumed to be short-hand aliases.  The variable associated with it
23968 is @code{at_arg_@var{option}}, with any dashes in @var{option} replaced
23969 with underscores.
23971 If the user passes @option{--@var{option}} to the @command{testsuite},
23972 the variable will be set to @samp{:}.  If the user does not pass the
23973 option, or passes @option{--no-@var{option}}, then the variable will be
23974 set to @samp{false}.
23976 @var{action-if-given} is run each time the option is encountered; here,
23977 the variable @code{at_optarg} will be set to @samp{:} or @samp{false} as
23978 appropriate.  @code{at_optarg} is actually just a copy of
23979 @code{at_arg_@var{option}}.
23981 @var{action-if-not-given} will be run once after option parsing is
23982 complete and if no option from @var{options} was used.
23984 @var{help-text} is added to the end of the list of options shown in
23985 @command{testsuite --help} (@pxref{AS_HELP_STRING}).
23987 It it recommended that you use a package-specific prefix to @var{options}
23988 names in order to avoid clashes with future Autotest built-in options.
23989 @end defmac
23991 @defmac AT_ARG_OPTION_ARG (@var{options}, @var{help-text}, @
23992   @ovar{action-if-given}, @ovar{action-if-not-given})
23993 @atindex{ARG_OPTION_ARG}
23994 Accept options with arguments from the space-separated list
23995 @var{options}, a list that has leading dashes removed from the options.
23996 Long options will be prefixed with @samp{--}, single-character options
23997 with @samp{-}.  The first word in this list is the primary @var{option},
23998 any others are assumed to be short-hand aliases.  The variable associated
23999 with it is @code{at_arg_@var{option}}, with any dashes in @var{option}
24000 replaced with underscores.
24002 If the user passes @option{--@var{option}=@var{arg}} or
24003 @option{--@var{option} @var{arg}} to the @command{testsuite}, the
24004 variable will be set to @samp{@var{arg}}.
24006 @var{action-if-given} is run each time the option is encountered; here,
24007 the variable @code{at_optarg} will be set to @samp{@var{arg}}.
24008 @code{at_optarg} is actually just a copy of @code{at_arg_@var{option}}.
24010 @var{action-if-not-given} will be run once after option parsing is
24011 complete and if no option from @var{options} was used.
24013 @var{help-text} is added to the end of the list of options shown in
24014 @command{testsuite --help} (@pxref{AS_HELP_STRING}).
24016 It it recommended that you use a package-specific prefix to @var{options}
24017 names in order to avoid clashes with future Autotest built-in options.
24018 @end defmac
24020 @defmac AT_COLOR_TESTS
24021 @atindex{COLOR_TESTS}
24022 Enable colored test results by default when the output is connected to
24023 a terminal.
24024 @end defmac
24026 @defmac AT_TESTED (@var{executables})
24027 @atindex{TESTED}
24028 Log the file name and answer to @option{--version} of each program in
24029 space-separated list @var{executables}.  Several invocations register
24030 new executables, in other words, don't fear registering one program
24031 several times.
24033 Autotest test suites rely on @env{PATH} to find the tested program.
24034 This avoids the need to generate absolute names of the various tools, and
24035 makes it possible to test installed programs.  Therefore, knowing which
24036 programs are being exercised is crucial to understanding problems in
24037 the test suite itself, or its occasional misuses.  It is a good idea to
24038 also subscribe foreign programs you depend upon, to avoid incompatible
24039 diagnostics.
24040 @end defmac
24042 @sp 1
24044 @defmac AT_BANNER (@var{test-category-name})
24045 @atindex{BANNER}
24046 This macro identifies the start of a category of related test groups.
24047 When the resulting @file{testsuite} is invoked with more than one test
24048 group to run, its output will include a banner containing
24049 @var{test-category-name} prior to any tests run from that category.  The
24050 banner should be no more than about 40 or 50 characters.  A blank banner
24051 indicates uncategorized tests; an empty line will be inserted after
24052 tests from an earlier category, effectively ending that category.
24053 @end defmac
24055 @defmac AT_SETUP (@var{test-group-name})
24056 @atindex{SETUP}
24057 This macro starts a group of related tests, all to be executed in the
24058 same subshell.  It accepts a single argument, which holds a few words
24059 (no more than about 30 or 40 characters) quickly describing the purpose
24060 of the test group being started.  @var{test-group-name} must not expand
24061 to unbalanced quotes, although quadrigraphs can be used.
24062 @end defmac
24064 @defmac AT_KEYWORDS (@var{keywords})
24065 @atindex{KEYWORDS}
24066 Associate the space-separated list of @var{keywords} to the enclosing
24067 test group.  This makes it possible to run ``slices'' of the test suite.
24068 For instance, if some of your test groups exercise some @samp{foo}
24069 feature, then using @samp{AT_KEYWORDS(foo)} lets you run
24070 @samp{./testsuite -k foo} to run exclusively these test groups.  The
24071 @var{test-group-name} of the test group is automatically recorded to
24072 @code{AT_KEYWORDS}.
24074 Several invocations within a test group accumulate new keywords.  In
24075 other words, don't fear registering the same keyword several times in a
24076 test group.
24077 @end defmac
24079 @defmac AT_CAPTURE_FILE (@var{file})
24080 @atindex{CAPTURE_FILE}
24081 If the current test group fails, log the contents of @var{file}.
24082 Several identical calls within one test group have no additional effect.
24083 @end defmac
24085 @defmac AT_FAIL_IF (@var{shell-condition})
24086 @atindex{FAIL_IF}
24087 Make the test group fail and skip the rest of its execution, if
24088 @var{shell-condition} is true.  @var{shell-condition} is a shell expression
24089 such as a @code{test} command.  Tests before @command{AT_FAIL_IF}
24090 will be executed and may still cause the test group to be skipped.
24091 You can instantiate this macro many times from within the same test group.
24093 You should use this macro only for very simple failure conditions.  If the
24094 @var{shell-condition} could emit any kind of output you should instead
24095 use @command{AT_CHECK} like
24096 @example
24097 AT_CHECK([if @var{shell-condition}; then exit 99; fi])
24098 @end example
24099 @noindent
24100 so that such output is properly recorded in the @file{testsuite.log}
24101 file.
24102 @end defmac
24104 @defmac AT_SKIP_IF (@var{shell-condition})
24105 @atindex{SKIP_IF}
24106 Determine whether the test should be skipped because it requires
24107 features that are unsupported on the machine under test.
24108 @var{shell-condition} is a shell expression such as a @code{test}
24109 command.  Tests before @command{AT_SKIP_IF} will be executed
24110 and may still cause the test group to fail.  You can instantiate this
24111 macro many times from within the same test group.
24113 You should use this macro only for very simple skip conditions.  If the
24114 @var{shell-condition} could emit any kind of output you should instead
24115 use @command{AT_CHECK} like
24116 @example
24117 AT_CHECK([if @var{shell-condition}; then exit 77; fi])
24118 @end example
24119 @noindent
24120 so that such output is properly recorded in the @file{testsuite.log}
24121 file.
24122 @end defmac
24124 @defmac AT_XFAIL_IF (@var{shell-condition})
24125 @atindex{XFAIL_IF}
24126 Determine whether the test is expected to fail because it is a known
24127 bug (for unsupported features, you should skip the test).
24128 @var{shell-condition} is a shell expression such as a @code{test}
24129 command; you can instantiate this macro many times from within the
24130 same test group, and one of the conditions is enough to turn
24131 the test into an expected failure.
24132 @end defmac
24134 @defmac AT_CLEANUP
24135 @atindex{CLEANUP}
24136 End the current test group.
24137 @end defmac
24139 @sp 1
24141 @defmac AT_DATA (@var{file}, @var{contents})
24142 @atindex{DATA}
24143 Initialize an input data @var{file} with given @var{contents}.  Of
24144 course, the @var{contents} have to be properly quoted between square
24145 brackets to protect against included commas or spurious M4
24146 expansion.  The contents must end with an end of line.  @var{file} must
24147 be a single shell word that expands into a single file name.
24148 @end defmac
24150 @defmac AT_CHECK (@var{commands}, @dvar{status, 0}, @ovar{stdout}, @
24151   @ovar{stderr}, @ovar{run-if-fail}, @ovar{run-if-pass})
24152 @defmacx AT_CHECK_UNQUOTED (@var{commands}, @dvar{status, 0}, @ovar{stdout}, @
24153   @ovar{stderr}, @ovar{run-if-fail}, @ovar{run-if-pass})
24154 @atindex{CHECK}
24155 @atindex{CHECK_UNQUOTED}
24156 Execute a test by performing given shell @var{commands}.  @var{commands}
24157 is output as-is, so shell expansions are honored.  These commands
24158 should normally exit with @var{status}, while producing expected
24159 @var{stdout} and @var{stderr} contents.  If @var{commands} exit with
24160 unexpected status 77, then the rest of the test group is skipped.  If
24161 @var{commands} exit with unexpected status 99, then the test group is
24162 immediately failed.  Otherwise, if this test
24163 fails, run shell commands @var{run-if-fail} or, if this test passes, run shell
24164 commands @var{run-if-pass}.
24166 This macro must be invoked in between @code{AT_SETUP} and @code{AT_CLEANUP}.
24168 If @var{status} is the literal @samp{ignore}, then the corresponding
24169 exit status is not checked, except for the special cases of 77 (skip)
24170 and 99 (hard failure).  The existence of hard failures allows one to
24171 mark a test as an expected failure with @code{AT_XFAIL_IF} because a
24172 feature has not yet been implemented, but to still distinguish between
24173 gracefully handling the missing feature and dumping core.  A hard
24174 failure also inhibits post-test actions in @var{run-if-fail}.
24176 If the value of the @var{stdout} or @var{stderr} parameter is one of the
24177 literals in the following table, then the test treats the output
24178 according to the rules of that literal.  Otherwise, the value of the
24179 parameter is treated as text that must exactly match the output given by
24180 @var{commands} on standard output and standard error (including an empty
24181 parameter for no output); any differences are captured in the testsuite
24182 log and the test is failed (unless an unexpected exit status of 77
24183 skipped the test instead).  The difference between @code{AT_CHECK} and
24184 @code{AT_CHECK_UNQUOTED} is that only the latter performs shell variable
24185 expansion (@samp{$}), command substitution (@samp{`}), and backslash
24186 escaping (@samp{\}) on comparison text given in the @var{stdout} and
24187 @var{stderr} arguments; if the text includes a trailing newline, this
24188 would be the same as if it were specified via an unquoted
24189 here-document.  (However, there is no difference in the interpretation
24190 of @var{commands}).
24192 @table @samp
24193 @item ignore
24194 The content of the output is ignored, but still captured in the test
24195 group log (if the testsuite is run with option @option{-v}, the test
24196 group log is displayed as the test is run; if the test group later
24197 fails, the test group log is also copied into the overall testsuite
24198 log).  This action is valid for both @var{stdout} and @var{stderr}.
24200 @item ignore-nolog
24201 The content of the output is ignored, and nothing is captured in the log
24202 files.  If @var{commands} are likely to produce binary output (including
24203 long lines) or large amounts of output, then logging the output can make
24204 it harder to locate details related to subsequent tests within the
24205 group, and could potentially corrupt terminal display of a user running
24206 @command{testsuite -v}.
24208 @item stdout
24209 For the @var{stdout} parameter, capture the content of standard output
24210 to both the file @file{stdout} and the test group log.  Subsequent
24211 commands in the test group can then post-process the file.  This action
24212 is often used when it is desired to use @command{grep} to look for a
24213 substring in the output, or when the output must be post-processed to
24214 normalize error messages into a common form.
24216 @item stderr
24217 Like @samp{stdout}, except that it only works for the @var{stderr}
24218 parameter, and the standard error capture file will be named
24219 @file{stderr}.
24221 @item stdout-nolog
24222 @itemx stderr-nolog
24223 Like @samp{stdout} or @samp{stderr}, except that the captured output is
24224 not duplicated into the test group log.  This action is particularly
24225 useful for an intermediate check that produces large amounts of data,
24226 which will be followed by another check that filters down to the
24227 relevant data, as it makes it easier to locate details in the log.
24229 @item expout
24230 For the @var{stdout} parameter, compare standard output contents with
24231 the previously created file @file{expout}, and list any differences in
24232 the testsuite log.
24234 @item experr
24235 Like @samp{expout}, except that it only works for the @var{stderr}
24236 parameter, and the standard error contents are compared with
24237 @file{experr}.
24238 @end table
24239 @end defmac
24241 @defmac AT_CHECK_EUNIT (@var{module}, @var{test-spec}, @ovar{erlflags}, @
24242   @ovar{run-if-fail}, @ovar{run-if-pass})
24243 @atindex{CHECK_EUNIT}
24244 Initialize and execute an Erlang module named @var{module} that performs
24245 tests following the @var{test-spec} EUnit test specification.
24246 @var{test-spec} must be a valid EUnit test specification, as defined in
24247 the @uref{http://@/erlang.org/@/doc/@/apps/@/eunit/@/index.html, EUnit
24248 Reference Manual}.  @var{erlflags} are optional command-line options
24249 passed to the Erlang interpreter to execute the test Erlang module.
24250 Typically, @var{erlflags} defines at least the paths to directories
24251 containing the compiled Erlang modules under test, as @samp{-pa path1
24252 path2 ...}.
24254 For example, the unit tests associated with Erlang module @samp{testme},
24255 which compiled code is in subdirectory @file{src}, can be performed
24256 with:
24258 @example
24259 AT_CHECK_EUNIT([testme_testsuite], [@{module, testme@}],
24260                [-pa "$@{abs_top_builddir@}/src"])
24261 @end example
24263 This macro must be invoked in between @code{AT_SETUP} and @code{AT_CLEANUP}.
24265 Variables @code{ERL}, @code{ERLC}, and (optionally) @code{ERLCFLAGS}
24266 must be defined as the path of the Erlang interpreter, the path of the
24267 Erlang compiler, and the command-line flags to pass to the compiler,
24268 respectively.  Those variables should be configured in
24269 @file{configure.ac} using the @command{AC_ERLANG_PATH_ERL} and
24270 @command{AC_ERLANG_PATH_ERLC} macros, and the configured values of those
24271 variables are automatically defined in the testsuite.  If @code{ERL} or
24272 @code{ERLC} is not defined, the test group is skipped.
24274 If the EUnit library cannot be found, i.e. if module @code{eunit} cannot
24275 be loaded, the test group is skipped.  Otherwise, if @var{test-spec} is
24276 an invalid EUnit test specification, the test group fails.  Otherwise,
24277 if the EUnit test passes, shell commands @var{run-if-pass} are executed
24278 or, if the EUnit test fails, shell commands @var{run-if-fail} are
24279 executed and the test group fails.
24281 Only the generated test Erlang module is automatically compiled and
24282 executed.  If @var{test-spec} involves testing other Erlang modules,
24283 e.g. module @samp{testme} in the example above, those modules must be
24284 already compiled.
24286 If the testsuite is run in verbose mode, with option @option{--verbose},
24287 EUnit is also run in verbose mode to output more details about
24288 individual unit tests.
24289 @end defmac
24292 @node testsuite Invocation
24293 @section Running @command{testsuite} Scripts
24294 @cindex @command{testsuite}
24296 Autotest test suites support the following options:
24298 @table @option
24299 @item --help
24300 @itemx -h
24301 Display the list of options and exit successfully.
24303 @item --version
24304 @itemx -V
24305 Display the version of the test suite and exit successfully.
24307 @item --directory=@var{dir}
24308 @itemx -C @var{dir}
24309 Change the current directory to @var{dir} before creating any files.
24310 Useful for running the testsuite in a subdirectory from a top-level
24311 Makefile.
24313 @item --jobs@r{[}=@var{n}@r{]}
24314 @itemx -j@ovar{n}
24315 Run @var{n} tests in parallel, if possible.  If @var{n} is not given,
24316 run all given tests in parallel.  Note that there should be no space
24317 before the argument to @option{-j}, as @option{-j @var{number}} denotes
24318 the separate arguments @option{-j} and @option{@var{number}}, see below.
24320 In parallel mode, the standard input device of the testsuite script is
24321 not available to commands inside a test group.  Furthermore, banner
24322 lines are not printed, and the summary line for each test group is
24323 output after the test group completes.  Summary lines may appear
24324 unordered.  If verbose and trace output are enabled (see below), they
24325 may appear intermixed from concurrently running tests.
24327 Parallel mode requires the @command{mkfifo} command to work, and will be
24328 silently disabled otherwise.
24330 @item --clean
24331 @itemx -c
24332 Remove all the files the test suite might have created and exit.  Meant
24333 for @code{clean} Make targets.
24335 @item --list
24336 @itemx -l
24337 List all the tests (or only the selection), including their possible
24338 keywords.
24339 @end table
24341 @sp 1
24343 By default all tests are performed (or described with @option{--list})
24344 silently in the default environment, but the environment, set of tests,
24345 and verbosity level can be tuned:
24347 @table @samp
24348 @item @var{variable}=@var{value}
24349 Set the environment @var{variable} to @var{value}.  Use this rather
24350 than @samp{FOO=foo ./testsuite} as debugging scripts would then run in a
24351 different environment.
24353 @cindex @code{AUTOTEST_PATH}
24354 The variable @code{AUTOTEST_PATH} specifies the testing path to prepend
24355 to @env{PATH}.  Relative directory names (not starting with
24356 @samp{/}) are considered to be relative to the top level of the
24357 package being built.  All directories are made absolute, first
24358 starting from the top level @emph{build} tree, then from the
24359 @emph{source} tree.  For instance @samp{./testsuite
24360 AUTOTEST_PATH=tests:bin} for a @file{/src/foo-1.0} source package built
24361 in @file{/tmp/foo} results in @samp{/tmp/foo/tests:/tmp/foo/bin} and
24362 then @samp{/src/foo-1.0/tests:/src/foo-1.0/bin} being prepended to
24363 @env{PATH}.
24365 @item @var{number}
24366 @itemx @var{number}-@var{number}
24367 @itemx @var{number}-
24368 @itemx -@var{number}
24369 Add the corresponding test groups, with obvious semantics, to the
24370 selection.
24372 @item --keywords=@var{keywords}
24373 @itemx -k @var{keywords}
24374 Add to the selection the test groups with title or keywords (arguments
24375 to @code{AT_SETUP} or @code{AT_KEYWORDS}) that match @emph{all} keywords
24376 of the comma separated list @var{keywords}, case-insensitively.  Use
24377 @samp{!} immediately before the keyword to invert the selection for this
24378 keyword.  By default, the keywords match whole words; enclose them in
24379 @samp{.*} to also match parts of words.
24381 For example, running
24383 @example
24384 @kbd{./testsuite -k 'autoupdate,.*FUNC.*'}
24385 @end example
24387 @noindent
24388 selects all tests tagged @samp{autoupdate} @emph{and} with tags
24389 containing @samp{FUNC} (as in @samp{AC_CHECK_FUNC}, @samp{AC_FUNC_ALLOCA},
24390 etc.), while
24392 @example
24393 @kbd{./testsuite -k '!autoupdate' -k '.*FUNC.*'}
24394 @end example
24396 @noindent
24397 selects all tests not tagged @samp{autoupdate} @emph{or} with tags
24398 containing @samp{FUNC}.
24400 @item --errexit
24401 @itemx -e
24402 If any test fails, immediately abort testing.  This implies
24403 @option{--debug}: post test group clean up, and top-level logging
24404 are inhibited.  This option is meant for the full test
24405 suite, it is not really useful for generated debugging scripts.
24406 If the testsuite is run in parallel mode using @option{--jobs},
24407 then concurrently running tests will finish before exiting.
24409 @item --verbose
24410 @itemx -v
24411 Force more verbosity in the detailed output of what is being done.  This
24412 is the default for debugging scripts.
24414 @item --color
24415 @itemx --color@r{[}=never@r{|}auto@r{|}always@r{]}
24416 Enable colored test results.  Without an argument, or with @samp{always},
24417 test results will be colored.  With @samp{never}, color mode is turned
24418 off.  Otherwise, if either the macro @code{AT_COLOR_TESTS} is used by
24419 the testsuite author, or the argument @samp{auto} is given, then test
24420 results are colored if standard output is connected to a terminal.
24422 @item --debug
24423 @itemx -d
24424 Do not remove the files after a test group was performed---but they are
24425 still removed @emph{before}, therefore using this option is sane when
24426 running several test groups.  Create debugging scripts.  Do not
24427 overwrite the top-level
24428 log (in order to preserve a supposedly existing full log file).  This is
24429 the default for debugging scripts, but it can also be useful to debug
24430 the testsuite itself.
24432 @item --recheck
24433 Add to the selection all test groups that failed or passed unexpectedly
24434 during the last non-debugging test run.
24436 @item --trace
24437 @itemx -x
24438 Trigger shell tracing of the test groups.
24439 @end table
24441 Besides these options accepted by every Autotest testsuite, the
24442 testsuite author might have added package-specific options
24443 via the @code{AT_ARG_OPTION} and @code{AT_ARG_OPTION_ARG} macros
24444 (@pxref{Writing Testsuites}); refer to @command{testsuite --help} and
24445 the package documentation for details.
24448 @node Making testsuite Scripts
24449 @section Making @command{testsuite} Scripts
24451 For putting Autotest into movement, you need some configuration and
24452 makefile machinery.  We recommend, at least if your package uses deep or
24453 shallow hierarchies, that you use @file{tests/} as the name of the
24454 directory holding all your tests and their makefile.  Here is a
24455 check list of things to do.
24457 @itemize @minus
24459 @item
24460 @cindex @file{package.m4}
24461 @atindex{PACKAGE_STRING}
24462 @atindex{PACKAGE_BUGREPORT}
24463 @atindex{PACKAGE_NAME}
24464 @atindex{PACKAGE_TARNAME}
24465 @atindex{PACKAGE_VERSION}
24466 @atindex{PACKAGE_URL}
24467 Make sure to create the file @file{package.m4}, which defines the
24468 identity of the package.  It must define @code{AT_PACKAGE_STRING}, the
24469 full signature of the package, and @code{AT_PACKAGE_BUGREPORT}, the
24470 address to which bug reports should be sent.  For sake of completeness,
24471 we suggest that you also define @code{AT_PACKAGE_NAME},
24472 @code{AT_PACKAGE_TARNAME}, @code{AT_PACKAGE_VERSION}, and
24473 @code{AT_PACKAGE_URL}.
24474 @xref{Initializing configure}, for a description of these variables.
24475 Be sure to distribute @file{package.m4} and to put it into the source
24476 hierarchy: the test suite ought to be shipped!  See below for an example
24477 @file{Makefile} excerpt.
24479 @item
24480 Invoke @code{AC_CONFIG_TESTDIR}.
24482 @defmac AC_CONFIG_TESTDIR (@var{directory}, @dvar{test-path, directory})
24483 @acindex{CONFIG_TESTDIR}
24484 An Autotest test suite is to be configured in @var{directory}.  This
24485 macro causes @file{@var{directory}/atconfig} to be created by
24486 @command{config.status} and sets the default @code{AUTOTEST_PATH} to
24487 @var{test-path} (@pxref{testsuite Invocation}).
24488 @end defmac
24490 @item
24491 Still within @file{configure.ac}, as appropriate, ensure that some
24492 @code{AC_CONFIG_FILES} command includes substitution for
24493 @file{tests/atlocal}.
24495 @item
24496 The appropriate @file{Makefile} should be modified so the validation in
24497 your package is triggered by @samp{make check}.  An example is provided
24498 below.
24499 @end itemize
24501 With Automake, here is a minimal example for inclusion in
24502 @file{tests/Makefile.am}, in order to link @samp{make check} with a
24503 validation suite.
24505 @example
24506 # The `:;' works around a Bash 3.2 bug when the output is not writeable.
24507 $(srcdir)/package.m4: $(top_srcdir)/configure.ac
24508         :;@{ \
24509           echo '# Signature of the current package.' && \
24510           echo 'm4_define([AT_PACKAGE_NAME],' && \
24511           echo '  [$(PACKAGE_NAME)])' && \
24512           echo 'm4_define([AT_PACKAGE_TARNAME],' && \
24513           echo '  [$(PACKAGE_TARNAME)])' && \
24514           echo 'm4_define([AT_PACKAGE_VERSION],' && \
24515           echo '  [$(PACKAGE_VERSION)])' && \
24516           echo 'm4_define([AT_PACKAGE_STRING],' && \
24517           echo '  [$(PACKAGE_STRING)])' && \
24518           echo 'm4_define([AT_PACKAGE_BUGREPORT],' && \
24519           echo '  [$(PACKAGE_BUGREPORT)])'; \
24520           echo 'm4_define([AT_PACKAGE_URL],' && \
24521           echo '  [$(PACKAGE_URL)])'; \
24522         @} >'$(srcdir)/package.m4'
24524 EXTRA_DIST = testsuite.at $(srcdir)/package.m4 $(TESTSUITE) atlocal.in
24525 TESTSUITE = $(srcdir)/testsuite
24527 check-local: atconfig atlocal $(TESTSUITE)
24528         $(SHELL) '$(TESTSUITE)' $(TESTSUITEFLAGS)
24530 installcheck-local: atconfig atlocal $(TESTSUITE)
24531         $(SHELL) '$(TESTSUITE)' AUTOTEST_PATH='$(bindir)' \
24532           $(TESTSUITEFLAGS)
24534 clean-local:
24535         test ! -f '$(TESTSUITE)' || \
24536          $(SHELL) '$(TESTSUITE)' --clean
24538 AUTOM4TE = $(SHELL) $(srcdir)/build-aux/missing --run autom4te
24539 AUTOTEST = $(AUTOM4TE) --language=autotest
24540 $(TESTSUITE): $(srcdir)/testsuite.at $(srcdir)/package.m4
24541         $(AUTOTEST) -I '$(srcdir)' -o $@@.tmp $@@.at
24542         mv $@@.tmp $@@
24543 @end example
24545 Note that the built testsuite is distributed; this is necessary because
24546 users might not have Autoconf installed, and thus would not be able to
24547 rebuild it.  Likewise, the use of @file{missing} provides the user with
24548 a nicer error message if they modify a source file to the testsuite, and
24549 accidentally trigger the rebuild rules.
24551 You might want to list explicitly the dependencies, i.e., the list of
24552 the files @file{testsuite.at} includes.
24554 If you don't use Automake, you should include the above example in
24555 @file{tests/@/Makefile.in}, along with additional lines inspired from
24556 the following:
24558 @example
24559 subdir = tests
24560 PACKAGE_NAME = @@PACKAGE_NAME@@
24561 PACKAGE_TARNAME = @@PACKAGE_TARNAME@@
24562 PACKAGE_VERSION = @@PACKAGE_VERSION@@
24563 PACKAGE_STRING = @@PACKAGE_STRING@@
24564 PACKAGE_BUGREPORT = @@PACKAGE_BUGREPORT@@
24565 PACKAGE_URL = @@PACKAGE_URL@@
24567 atconfig: $(top_builddir)/config.status
24568         cd $(top_builddir) && \
24569            $(SHELL) ./config.status $(subdir)/$@@
24571 atlocal: $(srcdir)/atlocal.in $(top_builddir)/config.status
24572         cd $(top_builddir) && \
24573            $(SHELL) ./config.status $(subdir)/$@@
24574 @end example
24576 @noindent
24577 and manage to have @code{$(EXTRA_DIST)} distributed.  You will also want
24578 to distribute the file @file{build-aux/@/missing} from the Automake
24579 project; a copy of this file resides in the Autoconf source tree.
24581 With all this in place, and if you have not initialized @samp{TESTSUITEFLAGS}
24582 within your makefile, you can fine-tune test suite execution with this
24583 variable, for example:
24585 @example
24586 make check TESTSUITEFLAGS='-v -d -x 75 -k AC_PROG_CC CFLAGS=-g'
24587 @end example
24591 @c =============================== Frequent Autoconf Questions, with answers
24593 @node FAQ
24594 @chapter Frequent Autoconf Questions, with answers
24596 Several questions about Autoconf come up occasionally.  Here some of them
24597 are addressed.
24599 @menu
24600 * Distributing::                Distributing @command{configure} scripts
24601 * Why GNU M4::                  Why not use the standard M4?
24602 * Bootstrapping::               Autoconf and GNU M4 require each other?
24603 * Why Not Imake::               Why GNU uses @command{configure} instead of Imake
24604 * Defining Directories::        Passing @code{datadir} to program
24605 * Autom4te Cache::              What is it?  Can I remove it?
24606 * Present But Cannot Be Compiled::  Compiler and Preprocessor Disagree
24607 * Expanded Before Required::    Expanded Before Required
24608 * Debugging::                   Debugging @command{configure} scripts
24609 @end menu
24611 @node Distributing
24612 @section Distributing @command{configure} Scripts
24613 @cindex License
24615 @display
24616 What are the restrictions on distributing @command{configure}
24617 scripts that Autoconf generates?  How does that affect my
24618 programs that use them?
24619 @end display
24621 There are no restrictions on how the configuration scripts that Autoconf
24622 produces may be distributed or used.  In Autoconf version 1, they were
24623 covered by the GNU General Public License.  We still encourage
24624 software authors to distribute their work under terms like those of the
24625 GPL, but doing so is not required to use Autoconf.
24627 Of the other files that might be used with @command{configure},
24628 @file{config.h.in} is under whatever copyright you use for your
24629 @file{configure.ac}.  @file{config.sub} and @file{config.guess} have an
24630 exception to the GPL when they are used with an Autoconf-generated
24631 @command{configure} script, which permits you to distribute them under the
24632 same terms as the rest of your package.  @file{install-sh} is from the X
24633 Consortium and is not copyrighted.
24635 @node Why GNU M4
24636 @section Why Require GNU M4?
24638 @display
24639 Why does Autoconf require GNU M4?
24640 @end display
24642 Many M4 implementations have hard-coded limitations on the size and
24643 number of macros that Autoconf exceeds.  They also lack several
24644 builtin macros that it would be difficult to get along without in a
24645 sophisticated application like Autoconf, including:
24647 @example
24648 m4_builtin
24649 m4_indir
24650 m4_bpatsubst
24651 __file__
24652 __line__
24653 @end example
24655 Autoconf requires version 1.4.6 or later of GNU M4.
24657 Since only software maintainers need to use Autoconf, and since GNU
24658 M4 is simple to configure and install, it seems reasonable to require
24659 GNU M4 to be installed also.  Many maintainers of GNU and
24660 other free software already have most of the GNU utilities
24661 installed, since they prefer them.
24663 @node Bootstrapping
24664 @section How Can I Bootstrap?
24665 @cindex Bootstrap
24667 @display
24668 If Autoconf requires GNU M4 and GNU M4 has an Autoconf
24669 @command{configure} script, how do I bootstrap?  It seems like a chicken
24670 and egg problem!
24671 @end display
24673 This is a misunderstanding.  Although GNU M4 does come with a
24674 @command{configure} script produced by Autoconf, Autoconf is not required
24675 in order to run the script and install GNU M4.  Autoconf is only
24676 required if you want to change the M4 @command{configure} script, which few
24677 people have to do (mainly its maintainer).
24679 @node Why Not Imake
24680 @section Why Not Imake?
24681 @cindex Imake
24683 @display
24684 Why not use Imake instead of @command{configure} scripts?
24685 @end display
24687 Several people have written addressing this question, so I include
24688 adaptations of their explanations here.
24690 The following answer is based on one written by Richard Pixley:
24692 @quotation
24693 Autoconf generated scripts frequently work on machines that it has
24694 never been set up to handle before.  That is, it does a good job of
24695 inferring a configuration for a new system.  Imake cannot do this.
24697 Imake uses a common database of host specific data.  For X11, this makes
24698 sense because the distribution is made as a collection of tools, by one
24699 central authority who has control over the database.
24701 GNU tools are not released this way.  Each GNU tool has a
24702 maintainer; these maintainers are scattered across the world.  Using a
24703 common database would be a maintenance nightmare.  Autoconf may appear
24704 to be this kind of database, but in fact it is not.  Instead of listing
24705 host dependencies, it lists program requirements.
24707 If you view the GNU suite as a collection of native tools, then the
24708 problems are similar.  But the GNU development tools can be
24709 configured as cross tools in almost any host+target permutation.  All of
24710 these configurations can be installed concurrently.  They can even be
24711 configured to share host independent files across hosts.  Imake doesn't
24712 address these issues.
24714 Imake templates are a form of standardization.  The GNU coding
24715 standards address the same issues without necessarily imposing the same
24716 restrictions.
24717 @end quotation
24720 Here is some further explanation, written by Per Bothner:
24722 @quotation
24723 One of the advantages of Imake is that it easy to generate large
24724 makefiles using the @samp{#include} and macro mechanisms of @command{cpp}.
24725 However, @code{cpp} is not programmable: it has limited conditional
24726 facilities, and no looping.  And @code{cpp} cannot inspect its
24727 environment.
24729 All of these problems are solved by using @code{sh} instead of
24730 @code{cpp}.  The shell is fully programmable, has macro substitution,
24731 can execute (or source) other shell scripts, and can inspect its
24732 environment.
24733 @end quotation
24736 Paul Eggert elaborates more:
24738 @quotation
24739 With Autoconf, installers need not assume that Imake itself is already
24740 installed and working well.  This may not seem like much of an advantage
24741 to people who are accustomed to Imake.  But on many hosts Imake is not
24742 installed or the default installation is not working well, and requiring
24743 Imake to install a package hinders the acceptance of that package on
24744 those hosts.  For example, the Imake template and configuration files
24745 might not be installed properly on a host, or the Imake build procedure
24746 might wrongly assume that all source files are in one big directory
24747 tree, or the Imake configuration might assume one compiler whereas the
24748 package or the installer needs to use another, or there might be a
24749 version mismatch between the Imake expected by the package and the Imake
24750 supported by the host.  These problems are much rarer with Autoconf,
24751 where each package comes with its own independent configuration
24752 processor.
24754 Also, Imake often suffers from unexpected interactions between
24755 @command{make} and the installer's C preprocessor.  The fundamental problem
24756 here is that the C preprocessor was designed to preprocess C programs,
24757 not makefiles.  This is much less of a problem with Autoconf,
24758 which uses the general-purpose preprocessor M4, and where the
24759 package's author (rather than the installer) does the preprocessing in a
24760 standard way.
24761 @end quotation
24764 Finally, Mark Eichin notes:
24766 @quotation
24767 Imake isn't all that extensible, either.  In order to add new features to
24768 Imake, you need to provide your own project template, and duplicate most
24769 of the features of the existing one.  This means that for a sophisticated
24770 project, using the vendor-provided Imake templates fails to provide any
24771 leverage---since they don't cover anything that your own project needs
24772 (unless it is an X11 program).
24774 On the other side, though:
24776 The one advantage that Imake has over @command{configure}:
24777 @file{Imakefile} files tend to be much shorter (likewise, less redundant)
24778 than @file{Makefile.in} files.  There is a fix to this, however---at least
24779 for the Kerberos V5 tree, we've modified things to call in common
24780 @file{post.in} and @file{pre.in} makefile fragments for the
24781 entire tree.  This means that a lot of common things don't have to be
24782 duplicated, even though they normally are in @command{configure} setups.
24783 @end quotation
24786 @node Defining Directories
24787 @section How Do I @code{#define} Installation Directories?
24789 @display
24790 My program needs library files, installed in @code{datadir} and
24791 similar.  If I use
24793 @example
24794 AC_DEFINE_UNQUOTED([DATADIR], [$datadir],
24795   [Define to the read-only architecture-independent
24796    data directory.])
24797 @end example
24799 @noindent
24800 I get
24802 @example
24803 #define DATADIR "$@{prefix@}/share"
24804 @end example
24805 @end display
24807 As already explained, this behavior is on purpose, mandated by the
24808 GNU Coding Standards, see @ref{Installation Directory
24809 Variables}.  There are several means to achieve a similar goal:
24811 @itemize @minus
24812 @item
24813 Do not use @code{AC_DEFINE} but use your makefile to pass the
24814 actual value of @code{datadir} via compilation flags.
24815 @xref{Installation Directory Variables}, for the details.
24817 @item
24818 This solution can be simplified when compiling a program: you may either
24819 extend the @code{CPPFLAGS}:
24821 @example
24822 CPPFLAGS = -DDATADIR='"$(datadir)"' @@CPPFLAGS@@
24823 @end example
24825 @noindent
24826 If you are using Automake, you should use @code{AM_CPPFLAGS} instead:
24828 @example
24829 AM_CPPFLAGS = -DDATADIR='"$(datadir)"'
24830 @end example
24832 @noindent
24833 Alternatively, create a dedicated header file:
24835 @example
24836 DISTCLEANFILES = myprog-paths.h
24837 myprog-paths.h: Makefile
24838         echo '#define DATADIR "$(datadir)"' >$@@
24839 @end example
24841 @item
24842 Use @code{AC_DEFINE} but have @command{configure} compute the literal
24843 value of @code{datadir} and others.  Many people have wrapped macros to
24844 automate this task; for an example, see the macro @code{AC_DEFINE_DIR} from
24845 the @uref{http://@/www.gnu.org/@/software/@/autoconf-archive/, Autoconf Macro
24846 Archive}.
24848 This solution does not conform to the GNU Coding Standards.
24850 @item
24851 Note that all the previous solutions hard wire the absolute name of
24852 these directories in the executables, which is not a good property.  You
24853 may try to compute the names relative to @code{prefix}, and try to
24854 find @code{prefix} at runtime, this way your package is relocatable.
24855 @end itemize
24858 @node Autom4te Cache
24859 @section What is @file{autom4te.cache}?
24861 @display
24862 What is this directory @file{autom4te.cache}?  Can I safely remove it?
24863 @end display
24865 In the GNU Build System, @file{configure.ac} plays a central
24866 role and is read by many tools: @command{autoconf} to create
24867 @file{configure}, @command{autoheader} to create @file{config.h.in},
24868 @command{automake} to create @file{Makefile.in}, @command{autoscan} to
24869 check the completeness of @file{configure.ac}, @command{autoreconf} to
24870 check the GNU Build System components that are used.  To
24871 ``read @file{configure.ac}'' actually means to compile it with M4,
24872 which can be a long process for complex @file{configure.ac}.
24874 This is why all these tools, instead of running directly M4, invoke
24875 @command{autom4te} (@pxref{autom4te Invocation}) which, while answering to
24876 a specific demand, stores additional information in
24877 @file{autom4te.cache} for future runs.  For instance, if you run
24878 @command{autoconf}, behind the scenes, @command{autom4te} also
24879 stores information for the other tools, so that when you invoke
24880 @command{autoheader} or @command{automake} etc., reprocessing
24881 @file{configure.ac} is not needed.  The speed up is frequently 30%,
24882 and is increasing with the size of @file{configure.ac}.
24884 But it is and remains being simply a cache: you can safely remove it.
24886 @sp 1
24888 @display
24889 Can I permanently get rid of it?
24890 @end display
24892 The creation of this cache can be disabled from
24893 @file{~/.autom4te.cfg}, see @ref{Customizing autom4te}, for more
24894 details.  You should be aware that disabling the cache slows down the
24895 Autoconf test suite by 40%.  The more GNU Build System
24896 components are used, the more the cache is useful; for instance
24897 running @samp{autoreconf -f} on the Core Utilities is twice slower without
24898 the cache @emph{although @option{--force} implies that the cache is
24899 not fully exploited}, and eight times slower than without
24900 @option{--force}.
24903 @node Present But Cannot Be Compiled
24904 @section Header Present But Cannot Be Compiled
24906 The most important guideline to bear in mind when checking for
24907 features is to mimic as much as possible the intended use.
24908 Unfortunately, old versions of @code{AC_CHECK_HEADER} and
24909 @code{AC_CHECK_HEADERS} failed to follow this idea, and called
24910 the preprocessor, instead of the compiler, to check for headers.  As a
24911 result, incompatibilities between headers went unnoticed during
24912 configuration, and maintainers finally had to deal with this issue
24913 elsewhere.
24915 The transition began with Autoconf 2.56.  As of Autoconf 2.64 both
24916 checks are performed, and @command{configure} complains loudly if the
24917 compiler and the preprocessor do not agree.  However, only the compiler
24918 result is considered.
24920 Consider the following example:
24922 @smallexample
24923 $ @kbd{cat number.h}
24924 typedef int number;
24925 $ @kbd{cat pi.h}
24926 const number pi = 3;
24927 $ @kbd{cat configure.ac}
24928 AC_INIT([Example], [1.0], [bug-example@@example.org])
24929 AC_CHECK_HEADERS([pi.h])
24930 $ @kbd{autoconf -Wall}
24931 $ @kbd{./configure}
24932 checking for gcc... gcc
24933 checking for C compiler default output file name... a.out
24934 checking whether the C compiler works... yes
24935 checking whether we are cross compiling... no
24936 checking for suffix of executables...
24937 checking for suffix of object files... o
24938 checking whether we are using the GNU C compiler... yes
24939 checking whether gcc accepts -g... yes
24940 checking for gcc option to accept ISO C89... none needed
24941 checking how to run the C preprocessor... gcc -E
24942 checking for grep that handles long lines and -e... grep
24943 checking for egrep... grep -E
24944 checking for ANSI C header files... yes
24945 checking for sys/types.h... yes
24946 checking for sys/stat.h... yes
24947 checking for stdlib.h... yes
24948 checking for string.h... yes
24949 checking for memory.h... yes
24950 checking for strings.h... yes
24951 checking for inttypes.h... yes
24952 checking for stdint.h... yes
24953 checking for unistd.h... yes
24954 checking pi.h usability... no
24955 checking pi.h presence... yes
24956 configure: WARNING: pi.h: present but cannot be compiled
24957 configure: WARNING: pi.h:     check for missing prerequisite headers?
24958 configure: WARNING: pi.h: see the Autoconf documentation
24959 configure: WARNING: pi.h:     section "Present But Cannot Be Compiled"
24960 configure: WARNING: pi.h: proceeding with the compiler's result
24961 configure: WARNING:     ## -------------------------------------- ##
24962 configure: WARNING:     ## Report this to bug-example@@example.org ##
24963 configure: WARNING:     ## -------------------------------------- ##
24964 checking for pi.h... yes
24965 @end smallexample
24967 @noindent
24968 The proper way the handle this case is using the fourth argument
24969 (@pxref{Generic Headers}):
24971 @example
24972 $ @kbd{cat configure.ac}
24973 AC_INIT([Example], [1.0], [bug-example@@example.org])
24974 AC_CHECK_HEADERS([number.h pi.h], [], [],
24975 [[#ifdef HAVE_NUMBER_H
24976 # include <number.h>
24977 #endif
24979 $ @kbd{autoconf -Wall}
24980 $ @kbd{./configure}
24981 checking for gcc... gcc
24982 checking for C compiler default output... a.out
24983 checking whether the C compiler works... yes
24984 checking whether we are cross compiling... no
24985 checking for suffix of executables...
24986 checking for suffix of object files... o
24987 checking whether we are using the GNU C compiler... yes
24988 checking whether gcc accepts -g... yes
24989 checking for gcc option to accept ANSI C... none needed
24990 checking for number.h... yes
24991 checking for pi.h... yes
24992 @end example
24994 See @ref{Particular Headers}, for a list of headers with their
24995 prerequisites.
24997 @node Expanded Before Required
24998 @section Expanded Before Required
25000 @cindex expanded before required
25001 Older versions of Autoconf silently built files with incorrect ordering
25002 between dependent macros if an outer macro first expanded, then later
25003 indirectly required, an inner macro.  Starting with Autoconf 2.64, this
25004 situation no longer generates out-of-order code, but results in
25005 duplicate output and a syntax warning:
25007 @example
25008 $ @kbd{cat configure.ac}
25009 @result{}AC_DEFUN([TESTA], [[echo in A
25010 @result{}if test -n "$SEEN_A" ; then echo duplicate ; fi
25011 @result{}SEEN_A=:]])
25012 @result{}AC_DEFUN([TESTB], [AC_REQUIRE([TESTA])[echo in B
25013 @result{}if test -z "$SEEN_A" ; then echo bug ; fi]])
25014 @result{}AC_DEFUN([TESTC], [AC_REQUIRE([TESTB])[echo in C]])
25015 @result{}AC_DEFUN([OUTER], [[echo in OUTER]
25016 @result{}TESTA
25017 @result{}TESTC])
25018 @result{}AC_INIT
25019 @result{}OUTER
25020 @result{}AC_OUTPUT
25021 $ @kbd{autoconf}
25022 @result{}configure.ac:11: warning: AC_REQUIRE:
25023 @result{} `TESTA' was expanded before it was required
25024 @result{}configure.ac:4: TESTB is expanded from...
25025 @result{}configure.ac:6: TESTC is expanded from...
25026 @result{}configure.ac:7: OUTER is expanded from...
25027 @result{}configure.ac:11: the top level
25028 @end example
25030 @noindent
25031 To avoid this warning, decide what purpose the macro in question serves.
25032 If it only needs to be expanded once (for example, if it provides
25033 initialization text used by later macros), then the simplest fix is to
25034 change the macro to be declared with @code{AC_DEFUN_ONCE}
25035 (@pxref{One-Shot Macros}), although this only works in Autoconf 2.64 and
25036 newer.  A more portable fix is to change all
25037 instances of direct calls to instead go through @code{AC_REQUIRE}
25038 (@pxref{Prerequisite Macros}).  If, instead, the macro is parameterized
25039 by arguments or by the current definition of other macros in the m4
25040 environment, then the macro should always be directly expanded instead
25041 of required.
25043 For another case study, consider this example trimmed down from an
25044 actual package.  Originally, the package contained shell code and
25045 multiple macro invocations at the top level of @file{configure.ac}:
25047 @example
25048 AC_DEFUN([FOO], [AC_COMPILE_IFELSE([@dots{}])])
25049 foobar=
25050 AC_PROG_CC
25052 @end example
25054 @noindent
25055 but that was getting complex, so the author wanted to offload some of
25056 the text into a new macro in another file included via
25057 @file{aclocal.m4}.  The na@"ive approach merely wraps the text in a new
25058 macro:
25060 @example
25061 AC_DEFUN([FOO], [AC_COMPILE_IFELSE([@dots{}])])
25062 AC_DEFUN([BAR], [
25063 foobar=
25064 AC_PROG_CC
25068 @end example
25070 @noindent
25071 With older versions of Autoconf, the setting of @samp{foobar=} occurs
25072 before the single compiler check, as the author intended.  But with
25073 Autoconf 2.64, this issues the ``expanded before it was required''
25074 warning for @code{AC_PROG_CC}, and outputs two copies of the compiler
25075 check, one before @samp{foobar=}, and one after.  To understand why this
25076 is happening, remember that the use of @code{AC_COMPILE_IFELSE} includes
25077 a call to @code{AC_REQUIRE([AC_PROG_CC])} under the hood.  According to
25078 the documented semantics of @code{AC_REQUIRE}, this means that
25079 @code{AC_PROG_CC} @emph{must} occur before the body of the outermost
25080 @code{AC_DEFUN}, which in this case is @code{BAR}, thus preceeding the
25081 use of @samp{foobar=}.  The older versions of Autoconf were broken with
25082 regards to the rules of @code{AC_REQUIRE}, which explains why the code
25083 changed from one over to two copies of @code{AC_PROG_CC} when upgrading
25084 autoconf.  In other words, the author was unknowingly relying on a bug
25085 exploit to get the desired results, and that exploit broke once the bug
25086 was fixed.
25088 So, what recourse does the author have, to restore their intended
25089 semantics of setting @samp{foobar=} prior to a single compiler check,
25090 regardless of whether Autoconf 2.63 or 2.64 is used?  One idea is to
25091 remember that only @code{AC_DEFUN} is impacted by @code{AC_REQUIRE};
25092 there is always the possibility of using the lower-level
25093 @code{m4_define}:
25095 @example
25096 AC_DEFUN([FOO], [AC_COMPILE_IFELSE([@dots{}])])
25097 m4_define([BAR], [
25098 foobar=
25099 AC_PROG_CC
25103 @end example
25105 @noindent
25106 This works great if everything is in the same file.  However, it does
25107 not help in the case where the author wants to have @command{aclocal}
25108 find the definition of @code{BAR} from its own file, since
25109 @command{aclocal} requires the use of @code{AC_DEFUN}.  In this case, a
25110 better fix is to recognize that if @code{BAR} also uses
25111 @code{AC_REQUIRE}, then there will no longer be direct expansion prior
25112 to a subsequent require.  Then, by creating yet another helper macro,
25113 the author can once again guarantee a single invocation of
25114 @code{AC_PROG_CC}, which will still occur after @code{foobar=}.  The
25115 author can also use @code{AC_BEFORE} to make sure no other macro
25116 appearing before @code{BAR} has triggered an unwanted expansion of
25117 @code{AC_PROG_CC}.
25119 @example
25120 AC_DEFUN([FOO], [AC_COMPILE_IFELSE([@dots{}])])
25121 AC_DEFUN([BEFORE_CC], [
25122 foobar=
25124 AC_DEFUN([BAR], [
25125 AC_BEFORE([$0], [AC_PROG_CC])dnl
25126 AC_REQUIRE([BEFORE_CC])dnl
25127 AC_REQUIRE([AC_PROG_CC])dnl
25131 @end example
25134 @node Debugging
25135 @section Debugging @command{configure} scripts
25137 While in general, @command{configure} scripts generated by Autoconf
25138 strive to be fairly portable to various systems, compilers, shells, and
25139 other tools, it may still be necessary to debug a failing test, broken
25140 script or makefile, or fix or override an incomplete, faulty, or erroneous
25141 test, especially during macro development.  Failures can occur at all levels,
25142 in M4 syntax or semantics, shell script issues, or due to bugs in the
25143 test or the tools invoked by @command{configure}.  Together with the
25144 rather arcane error message that @command{m4} and @command{make} may
25145 produce when their input contains syntax errors, this can make debugging
25146 rather painful.
25148 Nevertheless, here is a list of hints and strategies that may help:
25150 @itemize
25151 @item
25152 When @command{autoconf} fails, common causes for error include:
25154 @itemize
25155 @item
25156 mismatched or unbalanced parentheses or braces (@pxref{Balancing
25157 Parentheses}),
25159 @item under- or overquoted macro arguments (@pxref{Autoconf
25160 Language}, @pxref{Quoting and Parameters}, @pxref{Quotation and Nested
25161 Macros}),
25163 @item spaces between macro name and opening parenthesis (@pxref{Autoconf
25164 Language}).
25165 @end itemize
25167 Typically, it helps to go back to the last working version of the input
25168 and compare the differences for each of these errors.  Another
25169 possibility is to sprinkle pairs of @code{m4_traceon} and
25170 @code{m4_traceoff} judiciously in the code, either without a parameter
25171 or listing some macro names and watch @command{m4} expand its input
25172 verbosely (@pxref{Debugging via autom4te}).
25174 @item
25175 Sometimes @command{autoconf} succeeds but the generated
25176 @command{configure} script has invalid shell syntax.  You can detect this
25177 case by running @samp{bash -n configure} or @samp{sh -n configure}.
25178 If this command fails, the same tips apply, as if @command{autoconf} had
25179 failed.
25181 @item
25182 Debugging @command{configure} script execution may be done by sprinkling
25183 pairs of @code{set -x} and @code{set +x} into the shell script before
25184 and after the region that contains a bug.  Running the whole script with
25185 @samp{@var{shell} ./configure -vx 2>&1 | tee @var{log-file}} with a decent
25186 @var{shell} may work, but produces lots of output.  Here, it can help to
25187 search for markers like @samp{checking for} a particular test in the
25188 @var{log-file}.
25190 @item
25191 When @command{configure} tests produce invalid results for your system,
25192 it may be necessary to override them:
25194 @itemize
25195 @item
25196 For programs, tools or libraries variables, preprocessor, compiler, or
25197 linker flags, it is often sufficient to override them at @command{make}
25198 run time with some care (@pxref{Macros and Submakes}).  Since this
25199 normally won't cause @command{configure} to be run again with these
25200 changed settings, it may fail if the changed variable would have caused
25201 different test results from @command{configure}, so this may work only
25202 for simple differences.
25204 @item
25205 Most tests which produce their result in a substituted variable allow to
25206 override the test by setting the variable on the @command{configure}
25207 command line (@pxref{Compilers and Options}, @pxref{Defining Variables},
25208 @pxref{Particular Systems}).
25210 @item
25211 Many tests store their result in a cache variable (@pxref{Caching
25212 Results}).  This lets you override them either on the
25213 @command{configure} command line as above, or through a primed cache or
25214 site file (@pxref{Cache Files}, @pxref{Site Defaults}).  The name of a
25215 cache variable is documented with a test macro or may be inferred from
25216 @ref{Cache Variable Names}; the precise semantics of undocumented
25217 variables are often internal details, subject to change.
25218 @end itemize
25220 @item
25221 Alternatively, @command{configure} may produce invalid results because
25222 of uncaught programming errors, in your package or in an upstream
25223 library package.  For example, when @code{AC_CHECK_LIB} fails to find a
25224 library with a specified function, always check @file{config.log}.  This
25225 will reveal the exact error that produced the failing result: the
25226 library linked by @code{AC_CHECK_LIB} probably has a fatal bug.
25227 @end itemize
25229 Conversely, as macro author, you can make it easier for users of your
25230 macro:
25232 @itemize
25233 @item
25234 by minimizing dependencies between tests and between test results as far
25235 as possible,
25237 @item
25238 by using @command{make} variables to factorize and allow
25239 override of settings at @command{make} run time,
25241 @item
25242 by honoring the GNU Coding Standards and not overriding flags
25243 reserved for the user except temporarily during @command{configure}
25244 tests,
25246 @item
25247 by not requiring users of your macro to use the cache variables.
25248 Instead, expose the result of the test via @var{run-if-true} and
25249 @var{run-if-false} parameters.  If the result is not a boolean,
25250 then provide it through documented shell variables.
25251 @end itemize
25254 @c ===================================================== History of Autoconf.
25256 @node History
25257 @chapter History of Autoconf
25258 @cindex History of autoconf
25260 You may be wondering, Why was Autoconf originally written?  How did it
25261 get into its present form?  (Why does it look like gorilla spit?)  If
25262 you're not wondering, then this chapter contains no information useful
25263 to you, and you might as well skip it.  If you @emph{are} wondering,
25264 then let there be light@enddots{}
25266 @menu
25267 * Genesis::                     Prehistory and naming of @command{configure}
25268 * Exodus::                      The plagues of M4 and Perl
25269 * Leviticus::                   The priestly code of portability arrives
25270 * Numbers::                     Growth and contributors
25271 * Deuteronomy::                 Approaching the promises of easy configuration
25272 @end menu
25274 @node Genesis
25275 @section Genesis
25277 In June 1991 I was maintaining many of the GNU utilities for the
25278 Free Software Foundation.  As they were ported to more platforms and
25279 more programs were added, the number of @option{-D} options that users
25280 had to select in the makefile (around 20) became burdensome.
25281 Especially for me---I had to test each new release on a bunch of
25282 different systems.  So I wrote a little shell script to guess some of
25283 the correct settings for the fileutils package, and released it as part
25284 of fileutils 2.0.  That @command{configure} script worked well enough that
25285 the next month I adapted it (by hand) to create similar @command{configure}
25286 scripts for several other GNU utilities packages.  Brian Berliner
25287 also adapted one of my scripts for his CVS revision control system.
25289 Later that summer, I learned that Richard Stallman and Richard Pixley
25290 were developing similar scripts to use in the GNU compiler tools;
25291 so I adapted my @command{configure} scripts to support their evolving
25292 interface: using the file name @file{Makefile.in} as the templates;
25293 adding @samp{+srcdir}, the first option (of many); and creating
25294 @file{config.status} files.
25296 @node Exodus
25297 @section Exodus
25299 As I got feedback from users, I incorporated many improvements, using
25300 Emacs to search and replace, cut and paste, similar changes in each of
25301 the scripts.  As I adapted more GNU utilities packages to use
25302 @command{configure} scripts, updating them all by hand became impractical.
25303 Rich Murphey, the maintainer of the GNU graphics utilities, sent me
25304 mail saying that the @command{configure} scripts were great, and asking if
25305 I had a tool for generating them that I could send him.  No, I thought,
25306 but I should!  So I started to work out how to generate them.  And the
25307 journey from the slavery of hand-written @command{configure} scripts to the
25308 abundance and ease of Autoconf began.
25310 Cygnus @command{configure}, which was being developed at around that time,
25311 is table driven; it is meant to deal mainly with a discrete number of
25312 system types with a small number of mainly unguessable features (such as
25313 details of the object file format).  The automatic configuration system
25314 that Brian Fox had developed for Bash takes a similar approach.  For
25315 general use, it seems to me a hopeless cause to try to maintain an
25316 up-to-date database of which features each variant of each operating
25317 system has.  It's easier and more reliable to check for most features on
25318 the fly---especially on hybrid systems that people have hacked on
25319 locally or that have patches from vendors installed.
25321 I considered using an architecture similar to that of Cygnus
25322 @command{configure}, where there is a single @command{configure} script that
25323 reads pieces of @file{configure.in} when run.  But I didn't want to have
25324 to distribute all of the feature tests with every package, so I settled
25325 on having a different @command{configure} made from each
25326 @file{configure.in} by a preprocessor.  That approach also offered more
25327 control and flexibility.
25329 I looked briefly into using the Metaconfig package, by Larry Wall,
25330 Harlan Stenn, and Raphael Manfredi, but I decided not to for several
25331 reasons.  The @command{Configure} scripts it produces are interactive,
25332 which I find quite inconvenient; I didn't like the ways it checked for
25333 some features (such as library functions); I didn't know that it was
25334 still being maintained, and the @command{Configure} scripts I had
25335 seen didn't work on many modern systems (such as System V R4 and NeXT);
25336 it wasn't flexible in what it could do in response to a feature's
25337 presence or absence; I found it confusing to learn; and it was too big
25338 and complex for my needs (I didn't realize then how much Autoconf would
25339 eventually have to grow).
25341 I considered using Perl to generate my style of @command{configure}
25342 scripts, but decided that M4 was better suited to the job of simple
25343 textual substitutions: it gets in the way less, because output is
25344 implicit.  Plus, everyone already has it.  (Initially I didn't rely on
25345 the GNU extensions to M4.)  Also, some of my friends at the
25346 University of Maryland had recently been putting M4 front ends on
25347 several programs, including @code{tvtwm}, and I was interested in trying
25348 out a new language.
25350 @node Leviticus
25351 @section Leviticus
25353 Since my @command{configure} scripts determine the system's capabilities
25354 automatically, with no interactive user intervention, I decided to call
25355 the program that generates them Autoconfig.  But with a version number
25356 tacked on, that name would be too long for old Unix file systems,
25357 so I shortened it to Autoconf.
25359 In the fall of 1991 I called together a group of fellow questers after
25360 the Holy Grail of portability (er, that is, alpha testers) to give me
25361 feedback as I encapsulated pieces of my handwritten scripts in M4 macros
25362 and continued to add features and improve the techniques used in the
25363 checks.  Prominent among the testers were Fran@,{c}ois Pinard, who came up
25364 with the idea of making an Autoconf shell script to run M4
25365 and check for unresolved macro calls; Richard Pixley, who suggested
25366 running the compiler instead of searching the file system to find
25367 include files and symbols, for more accurate results; Karl Berry, who
25368 got Autoconf to configure @TeX{} and added the macro index to the
25369 documentation; and Ian Lance Taylor, who added support for creating a C
25370 header file as an alternative to putting @option{-D} options in a
25371 makefile, so he could use Autoconf for his UUCP package.
25372 The alpha testers cheerfully adjusted their files again and again as the
25373 names and calling conventions of the Autoconf macros changed from
25374 release to release.  They all contributed many specific checks, great
25375 ideas, and bug fixes.
25377 @node Numbers
25378 @section Numbers
25380 In July 1992, after months of alpha testing, I released Autoconf 1.0,
25381 and converted many GNU packages to use it.  I was surprised by how
25382 positive the reaction to it was.  More people started using it than I
25383 could keep track of, including people working on software that wasn't
25384 part of the GNU Project (such as TCL, FSP, and Kerberos V5).
25385 Autoconf continued to improve rapidly, as many people using the
25386 @command{configure} scripts reported problems they encountered.
25388 Autoconf turned out to be a good torture test for M4 implementations.
25389 Unix M4 started to dump core because of the length of the
25390 macros that Autoconf defined, and several bugs showed up in GNU
25391 M4 as well.  Eventually, we realized that we needed to use some
25392 features that only GNU M4 has.  4.3BSD M4, in
25393 particular, has an impoverished set of builtin macros; the System V
25394 version is better, but still doesn't provide everything we need.
25396 More development occurred as people put Autoconf under more stresses
25397 (and to uses I hadn't anticipated).  Karl Berry added checks for X11.
25398 david zuhn contributed C++ support.  Fran@,{c}ois Pinard made it diagnose
25399 invalid arguments.  Jim Blandy bravely coerced it into configuring
25400 GNU Emacs, laying the groundwork for several later improvements.
25401 Roland McGrath got it to configure the GNU C Library, wrote the
25402 @command{autoheader} script to automate the creation of C header file
25403 templates, and added a @option{--verbose} option to @command{configure}.
25404 Noah Friedman added the @option{--autoconf-dir} option and
25405 @code{AC_MACRODIR} environment variable.  (He also coined the term
25406 @dfn{autoconfiscate} to mean ``adapt a software package to use
25407 Autoconf''.)  Roland and Noah improved the quoting protection in
25408 @code{AC_DEFINE} and fixed many bugs, especially when I got sick of
25409 dealing with portability problems from February through June, 1993.
25411 @node Deuteronomy
25412 @section Deuteronomy
25414 A long wish list for major features had accumulated, and the effect of
25415 several years of patching by various people had left some residual
25416 cruft.  In April 1994, while working for Cygnus Support, I began a major
25417 revision of Autoconf.  I added most of the features of the Cygnus
25418 @command{configure} that Autoconf had lacked, largely by adapting the
25419 relevant parts of Cygnus @command{configure} with the help of david zuhn
25420 and Ken Raeburn.  These features include support for using
25421 @file{config.sub}, @file{config.guess}, @option{--host}, and
25422 @option{--target}; making links to files; and running @command{configure}
25423 scripts in subdirectories.  Adding these features enabled Ken to convert
25424 GNU @code{as}, and Rob Savoye to convert DejaGNU, to using
25425 Autoconf.
25427 I added more features in response to other peoples' requests.  Many
25428 people had asked for @command{configure} scripts to share the results of
25429 the checks between runs, because (particularly when configuring a large
25430 source tree, like Cygnus does) they were frustratingly slow.  Mike
25431 Haertel suggested adding site-specific initialization scripts.  People
25432 distributing software that had to unpack on MS-DOS asked for a way to
25433 override the @file{.in} extension on the file names, which produced file
25434 names like @file{config.h.in} containing two dots.  Jim Avera did an
25435 extensive examination of the problems with quoting in @code{AC_DEFINE}
25436 and @code{AC_SUBST}; his insights led to significant improvements.
25437 Richard Stallman asked that compiler output be sent to @file{config.log}
25438 instead of @file{/dev/null}, to help people debug the Emacs
25439 @command{configure} script.
25441 I made some other changes because of my dissatisfaction with the quality
25442 of the program.  I made the messages showing results of the checks less
25443 ambiguous, always printing a result.  I regularized the names of the
25444 macros and cleaned up coding style inconsistencies.  I added some
25445 auxiliary utilities that I had developed to help convert source code
25446 packages to use Autoconf.  With the help of Fran@,{c}ois Pinard, I made
25447 the macros not interrupt each others' messages.  (That feature revealed
25448 some performance bottlenecks in GNU M4, which he hastily
25449 corrected!)  I reorganized the documentation around problems people want
25450 to solve.  And I began a test suite, because experience had shown that
25451 Autoconf has a pronounced tendency to regress when we change it.
25453 Again, several alpha testers gave invaluable feedback, especially
25454 Fran@,{c}ois Pinard, Jim Meyering, Karl Berry, Rob Savoye, Ken Raeburn,
25455 and Mark Eichin.
25457 Finally, version 2.0 was ready.  And there was much rejoicing.  (And I
25458 have free time again.  I think.  Yeah, right.)
25461 @c ========================================================== Appendices
25464 @node GNU Free Documentation License
25465 @appendix GNU Free Documentation License
25467 @include fdl.texi
25469 @node Indices
25470 @appendix Indices
25472 @menu
25473 * Environment Variable Index::  Index of environment variables used
25474 * Output Variable Index::       Index of variables set in output files
25475 * Preprocessor Symbol Index::   Index of C preprocessor symbols defined
25476 * Cache Variable Index::        Index of documented cache variables
25477 * Autoconf Macro Index::        Index of Autoconf macros
25478 * M4 Macro Index::              Index of M4, M4sugar, and M4sh macros
25479 * Autotest Macro Index::        Index of Autotest macros
25480 * Program & Function Index::    Index of those with portability problems
25481 * Concept Index::               General index
25482 @end menu
25484 @node Environment Variable Index
25485 @appendixsec Environment Variable Index
25487 This is an alphabetical list of the environment variables that might
25488 influence Autoconf checks.
25490 @printindex ev
25492 @node Output Variable Index
25493 @appendixsec Output Variable Index
25495 This is an alphabetical list of the variables that Autoconf can
25496 substitute into files that it creates, typically one or more
25497 makefiles.  @xref{Setting Output Variables}, for more information
25498 on how this is done.
25500 @printindex ov
25502 @node Preprocessor Symbol Index
25503 @appendixsec Preprocessor Symbol Index
25505 This is an alphabetical list of the C preprocessor symbols that the
25506 Autoconf macros define.  To work with Autoconf, C source code needs to
25507 use these names in @code{#if} or @code{#ifdef} directives.
25509 @printindex cv
25511 @node Cache Variable Index
25512 @appendixsec Cache Variable Index
25514 This is an alphabetical list of documented cache variables used
25515 by macros defined in Autoconf.  Autoconf macros may use additional cache
25516 variables internally.
25517 @ifset shortindexflag
25518 To make the list easier to use, the variables are listed without their
25519 preceding @samp{ac_cv_}.
25520 @end ifset
25522 @printindex CA
25524 @node Autoconf Macro Index
25525 @appendixsec Autoconf Macro Index
25527 This is an alphabetical list of the Autoconf macros.
25528 @ifset shortindexflag
25529 To make the list easier to use, the macros are listed without their
25530 preceding @samp{AC_}.
25531 @end ifset
25533 @printindex AC
25535 @node M4 Macro Index
25536 @appendixsec M4 Macro Index
25538 This is an alphabetical list of the M4, M4sugar, and M4sh macros.
25539 @ifset shortindexflag
25540 To make the list easier to use, the macros are listed without their
25541 preceding @samp{m4_} or @samp{AS_}.
25542 @end ifset
25544 @printindex MS
25546 @node Autotest Macro Index
25547 @appendixsec Autotest Macro Index
25549 This is an alphabetical list of the Autotest macros.
25550 @ifset shortindexflag
25551 To make the list easier to use, the macros are listed without their
25552 preceding @samp{AT_}.
25553 @end ifset
25555 @printindex AT
25557 @node Program & Function Index
25558 @appendixsec Program and Function Index
25560 This is an alphabetical list of the programs and functions whose
25561 portability is discussed in this document.
25563 @printindex pr
25565 @node Concept Index
25566 @appendixsec Concept Index
25568 This is an alphabetical list of the files, tools, and concepts
25569 introduced in this document.
25571 @printindex cp
25573 @bye
25575 @c  LocalWords:  texinfo setfilename autoconf texi settitle setchapternewpage
25576 @c  LocalWords:  setcontentsaftertitlepage finalout ARG ovar varname dvar acx
25577 @c  LocalWords:  makeinfo dvi defcodeindex ev ov CPP cv Autotest mv defindex fn
25578 @c  LocalWords:  shortindexflag iftex ifset acindex ACindex ifclear ahindex fu
25579 @c  LocalWords:  asindex MSindex atindex ATindex auindex hdrindex prindex FIXME
25580 @c  LocalWords:  msindex alloca fnindex Aaarg indices FSF's dircategory ifnames
25581 @c  LocalWords:  direntry autoscan autoreconf autoheader autoupdate config FDs
25582 @c  LocalWords:  testsuite titlepage Elliston Demaille vskip filll ifnottex hmm
25583 @c  LocalWords:  insertcopying Autoconf's detailmenu Automake Libtool Posix ois
25584 @c  LocalWords:  Systemology Checkpointing Changequote INTERCAL changequote dfn
25585 @c  LocalWords:  Quadrigraphs builtins Shellology acconfig Bugward LIBOBJ Imake
25586 @c  LocalWords:  LIBOBJS IFELSE cindex flushright Pinard Metaconfig uref Simons
25587 @c  LocalWords:  distclean uninstall noindent versioning Tromey dir
25588 @c  LocalWords:  SAMS samp aclocal acsite underquoted emph itemx prepend SUBST
25589 @c  LocalWords:  evindex automake Gettext autopoint gettext symlink libtoolize
25590 @c  LocalWords:  defmac INIT tarname ovindex cvindex BUGREPORT PREREQ asis PROG
25591 @c  LocalWords:  SRCDIR srcdir globbing afterwards cmds foos fooo foooo init cd
25592 @c  LocalWords:  builddir timestamp src Imakefile chmod defvar CFLAGS CPPFLAGS
25593 @c  LocalWords:  CXXFLAGS DEFS DHAVE defvarx FCFLAGS FFLAGS LDFLAGS bindir GCC
25594 @c  LocalWords:  datadir datarootdir docdir dvidir htmldir libdir ifnothtml kbd
25595 @c  LocalWords:  includedir infodir libexecdir localedir localstatedir mandir
25596 @c  LocalWords:  oldincludedir pdfdir PDF psdir PostScript sbindir sysconfdir
25597 @c  LocalWords:  sharedstatedir DDATADIR sed tmp pkgdatadir VPATH conf unistd
25598 @c  LocalWords:  undef endif builtin FUNCS ifndef STACKSEG getb GETB YMP fubar
25599 @c  LocalWords:  PRE dest SUBDIRS subdirs fi struct STDC stdlib stddef INTTYPES
25600 @c  LocalWords:  inttypes STDINT stdint AWK AIX Solaris NeXT env EGREP FGREP yy
25601 @c  LocalWords:  LEXLIB YYTEXT lfl nonportable Automake's LN RANLIB byacc INETD
25602 @c  LocalWords:  inetd prog PROGS progs ranlib lmp lXt lX nsl gethostbyname UX
25603 @c  LocalWords:  NextStep isinf isnan glibc IRIX sunmath lm lsunmath pre sizeof
25604 @c  LocalWords:  ld inline malloc putenv setenv FreeBSD realloc SunOS MinGW
25605 @c  LocalWords:  snprintf vsnprintf sprintf vsprintf sscanf gcc strerror ifdef
25606 @c  LocalWords:  strnlen sysconf PAGESIZE unsetenv va fallback memcpy dst FUNC
25607 @c  LocalWords:  PowerPC GNUC libPW pragma Olibcalls CHOWN chown CLOSEDIR VFORK
25608 @c  LocalWords:  closedir FNMATCH fnmatch vfork FSEEKO LARGEFILE fseeko SVR sc
25609 @c  LocalWords:  largefile GETGROUPS getgroups GETLOADAVG DGUX UMAX NLIST KMEM
25610 @c  LocalWords:  SETGID getloadavg nlist GETMNTENT irix
25611 @c  LocalWords:  getmntent UnixWare GETPGRP getpgid getpgrp Posix's pid LSTAT
25612 @c  LocalWords:  lstat rpl MEMCMP memcmp OpenStep MBRTOWC mbrtowc MKTIME mktime
25613 @c  LocalWords:  localtime MMAP mmap OBSTACK obstack obstacks ARGTYPES timeval
25614 @c  LocalWords:  SETPGRP setpgrp defmacx Hurd SETVBUF setvbuf STRCOLL strcoll
25615 @c  LocalWords:  STRTOD strtod DECL STRFTIME strftime SCO UTIME utime VPRINTF
25616 @c  LocalWords:  DOPRNT vprintf doprnt sp unfixable LIBSOURCE LIBSOURCES Eggert
25617 @c  LocalWords:  linux netinet ia Tru XFree DIRENT NDIR dirent ndir multitable
25618 @c  LocalWords:  NAMLEN strlen namlen MKDEV SYSMACROS makedev RESOLV resolv DNS
25619 @c  LocalWords:  inet structs NAMESER arpa NETDB netdb UTekV UTS GCC's kB
25620 @c  LocalWords:  STDBOOL BOOL stdbool conformant cplusplus bool Bool stdarg tm
25621 @c  LocalWords:  ctype strchr strrchr rindex bcopy memmove memchr WEXITSTATUS
25622 @c  LocalWords:  WIFEXITED TIOCGWINSZ GWINSZ termios preprocess preprocessable
25623 @c  LocalWords:  DECLS strdup calloc BLKSIZE blksize RDEV rdev TZNAME tzname pw
25624 @c  LocalWords:  passwd gecos pwd MBSTATE mbstate wchar RETSIGTYPE hup UID uid
25625 @c  LocalWords:  gid ptrdiff uintmax EXEEXT OBJEXT Ae conftest AXP str
25626 @c  LocalWords:  ALIGNOF WERROR Werror cpp HP's WorkShop egcs un fied stdc CXX
25627 @c  LocalWords:  varargs BIGENDIAN Endianness SPARC endianness grep'ed CONST FC
25628 @c  LocalWords:  const STRINGIZE stringizing PARAMS unprotoize protos KCC cxx
25629 @c  LocalWords:  xlC aCC CXXCPP FREEFORM xlf FLIBS FCLIBS ish SRCEXT XTRA LFS
25630 @c  LocalWords:  ISC lcposix MINIX Minix conditionalized inlines hw dD confdefs
25631 @c  LocalWords:  fputs stdout PREPROC ar UFS HFS QNX realtime fstype STATVFS se
25632 @c  LocalWords:  statvfs STATFS statfs func machfile hdr lelf raboof DEFUN GTK
25633 @c  LocalWords:  GTKMM Grmph ified ine defn baz EOF qar Ahhh changecom algol io
25634 @c  LocalWords:  changeword quadrigraphs quadrigraph dnl SGI atoi overquoting
25635 @c  LocalWords:  Aas Wcross sep args namespace undefine bpatsubst popdef dquote
25636 @c  LocalWords:  bregexp Overquote overquotation meisch maisch meische maische
25637 @c  LocalWords:  miscian DIRNAME dirname MKDIR CATFILE XMKMF TRAVOLTA celsius
25638 @c  LocalWords:  EMX emxos Emacsen Korn DYNIX subshell posix Ksh ksh Pdksh Zsh
25639 @c  LocalWords:  pdksh zsh Allbery Lipe Kubota UWS zorglub stderr eval esac lfn
25640 @c  LocalWords:  drivespec Posixy DJGPP doschk prettybird LPT pfew Zsh's yu yaa
25641 @c  LocalWords:  yM uM aM firebird IP subdir misparses ok Unpatched abc bc zA
25642 @c  LocalWords:  CDPATH DUALCASE LINENO prepass Subshells lineno NULLCMD cmp wc
25643 @c  LocalWords:  MAILPATH scanset arg NetBSD Almquist printf expr cp
25644 @c  LocalWords:  Oliva awk Aaaaarg cmd regex xfoo GNV OpenVMS VM
25645 @c  LocalWords:  sparc Proulx nbar nfoo maxdepth acdilrtu TWG mc
25646 @c  LocalWords:  mkdir exe uname OpenBSD Fileutils mktemp umask TMPDIR guid os
25647 @c  LocalWords:  fooXXXXXX Unicos utimes hpux hppa unescaped
25648 @c  LocalWords:  pmake DOS's gmake ifoo DESTDIR autoconfiscated pc coff mips gg
25649 @c  LocalWords:  dec ultrix cpu wildcards rpcc rdtsc powerpc readline
25650 @c  LocalWords:  withval vxworks gless localcache usr LOFF loff CYGWIN Cygwin
25651 @c  LocalWords:  cygwin SIGLIST siglist SYSNDIR SYSDIR ptx lseq rusage elif MSC
25652 @c  LocalWords:  lfoo POUNDBANG lsun NIS getpwnam SYSCALLS RSH INTL lintl aix
25653 @c  LocalWords:  intl lx ldir syslog bsd EPI toolchain netbsd objext de KNR nn
25654 @c  LocalWords:  fication LTLIBOBJS Wdiff TESTDIR atconfig atlocal akim XFAIL
25655 @c  LocalWords:  ChangeLog prepended errexit smallexample TESTSUITEFLAGS GPL er
25656 @c  LocalWords:  installcheck autotest indir Pixley Bothner Eichin Kerberos adl
25657 @c  LocalWords:  DISTCLEANFILES preprocessor's fileutils Stallman Murphey Stenn
25658 @c  LocalWords:  Manfredi Autoconfig TCL FSP david zuhn Blandy MACRODIR Raeburn
25659 @c  LocalWords:  autoconfiscate Savoye Haertel Avera Meyering fdl appendixsec
25660 @c  LocalWords:  printindex american LIBOBJDIR LibdirTest ERLCFLAGS OBJCFLAGS
25661 @c  LocalWords:  VER Gnulib online xyes strcpy TYPEOF typeof OBJC objcc objc ln
25662 @c  LocalWords:  GOBJC OTP ERLC erl valloc decr dumpdef errprint incr
25663 @c  LocalWords:  esyscmd len maketemp pushdef substr syscmd sysval translit txt
25664 @c  LocalWords:  sinclude foreach myvar tolower toupper uniq BASENAME STDIN
25665 @c  LocalWords:  Dynix descrips basename aname cname macroexpands xno xcheck
25666 @c  LocalWords:  LIBREADLINE lreadline lncurses libreadline
25668 @c Local Variables:
25669 @c fill-column: 72
25670 @c ispell-local-dictionary: "american"
25671 @c indent-tabs-mode: nil
25672 @c whitespace-check-buffer-indent: nil
25673 @c End: