extract "Programming in M4sh" into its own chapter
[autoconf.git] / doc / autoconf.texi
blob96fdc5b938286104bbd18ae4bac85d6acf8cdeab
1 \input texinfo @c -*-texinfo-*-
2 @comment ========================================================
3 @comment %**start of header
4 @setfilename autoconf.info
5 @include version.texi
6 @settitle Autoconf
7 @setchapternewpage odd
8 @ifnothtml
9 @setcontentsaftertitlepage
10 @end ifnothtml
11 @finalout
13 @c @ovar(ARG)
14 @c ----------
15 @c The ARG is an optional argument.  To be used for macro arguments in
16 @c their documentation (@defmac).
17 @macro ovar{varname}
18 @r{[}@var{\varname\}@r{]}@c
19 @end macro
21 @c @dvar(ARG, DEFAULT)
22 @c -------------------
23 @c The ARG is an optional argument, defaulting to DEFAULT.  To be used
24 @c for macro arguments in their documentation (@defmac).
25 @macro dvar{varname, default}
26 @r{[}@var{\varname\} = @samp{\default\}@r{]}@c
27 @end macro
29 @c Handling the indexes with Texinfo yields several different problems.
31 @c Because we want to drop out the AC_ part of the macro names in the
32 @c printed manual, but not in the other outputs, we need a layer above
33 @c the usual @acindex{} etc.  That's why we first define indexes such as
34 @c acx meant to become the macro @acindex.  First of all, using ``ac_''
35 @c does not work with makeinfo, and using ``ac1'' doesn't work with TeX.
36 @c So use something more regular ``acx''.  Then you finish with a printed
37 @c index saying ``index is not existent''.  Of course: you ought to use
38 @c two letters :(  So you use capitals.
40 @c Second, when defining a macro in the TeX world, following spaces are
41 @c eaten.  But then, since we embed @acxindex commands that use the end
42 @c of line as an end marker, the whole things wrecks itself.  So make
43 @c sure you do *force* an additional end of line, add a ``@c''.
45 @c Finally, you might want to get rid of TeX expansion, using --expand
46 @c with texi2dvi.  But then you wake up an old problem: we use macros
47 @c in @defmac etc. where TeX does perform the expansion, but not makeinfo.
49 @c Define an environment variable index.
50 @defcodeindex ev
51 @c Define an output variable index.
52 @defcodeindex ov
53 @c Define a CPP variable index.
54 @defcodeindex cv
55 @c Define an Autoconf macro index that @defmac doesn't write to.
56 @defcodeindex AC
57 @c Define an Autotest macro index that @defmac doesn't write to.
58 @defcodeindex AT
59 @c Define an M4sugar macro index that @defmac doesn't write to.
60 @defcodeindex MS
61 @c Define an index for *foreign* programs: `mv' etc.  Used for the
62 @c portability sections and so on.
63 @defindex pr
65 @c shortindexflag
66 @c --------------
67 @c Shall we factor AC_ out of the Autoconf macro index etc.?
68 @iftex
69 @set shortindexflag
70 @end iftex
72 @c @acindex{MACRO}
73 @c ---------------
74 @c Registering an AC_\MACRO\.
75 @ifset shortindexflag
76 @macro acindex{macro}
77 @ACindex \macro\
79 @end macro
80 @end ifset
81 @ifclear shortindexflag
82 @macro acindex{macro}
83 @ACindex AC_\macro\
84 @end macro
85 @end ifclear
87 @c @ahindex{MACRO}
88 @c ---------------
89 @c Registering an AH_\MACRO\.
90 @macro ahindex{macro}
91 @ACindex AH_\macro\
93 @end macro
95 @c @asindex{MACRO}
96 @c ---------------
97 @c Registering an AS_\MACRO\.
98 @ifset shortindexflag
99 @macro asindex{macro}
100 @MSindex \macro\
102 @end macro
103 @end ifset
104 @ifclear shortindexflag
105 @macro asindex{macro}
106 @MSindex AS_\macro\
107 @end macro
108 @end ifclear
110 @c @atindex{MACRO}
111 @c ---------------
112 @c Registering an AT_\MACRO\.
113 @ifset shortindexflag
114 @macro atindex{macro}
115 @ATindex \macro\
117 @end macro
118 @end ifset
119 @ifclear shortindexflag
120 @macro atindex{macro}
121 @ATindex AT_\macro\
122 @end macro
123 @end ifclear
125 @c @auindex{MACRO}
126 @c ---------------
127 @c Registering an AU_\MACRO\.
128 @macro auindex{macro}
129 @ACindex AU_\macro\
131 @end macro
133 @c @hdrindex{MACRO}
134 @c ----------------
135 @c Indexing a header.
136 @macro hdrindex{macro}
137 @prindex @file{\macro\}
139 @end macro
141 @c @msindex{MACRO}
142 @c ---------------
143 @c Registering an m4_\MACRO\.
144 @ifset shortindexflag
145 @macro msindex{macro}
146 @MSindex \macro\
148 @end macro
149 @end ifset
150 @ifclear shortindexflag
151 @macro msindex{macro}
152 @MSindex m4_\macro\
153 @end macro
154 @end ifclear
157 @c Define an index for functions: `alloca' etc.  Used for the
158 @c portability sections and so on.  We can't use `fn' (aka `fnindex),
159 @c since `@defmac' goes into it => we'd get all the macros too.
161 @c   FIXME: Aaarg!  It seems there are too many indices for TeX :(
163 @c   ! No room for a new @write .
164 @c   l.112 @defcodeindex fu
166 @c   so don't define yet another one :(  Just put some tags before each
167 @c   @prindex which is actually a @funindex.
169 @c   @defcodeindex fu
172 @c   @c Put the programs and functions into their own index.
173 @c   @syncodeindex fu pr
175 @comment %**end of header
176 @comment ========================================================
178 @copying
180 This manual (@value{UPDATED}) is for @acronym{GNU} Autoconf
181 (version @value{VERSION}),
182 a package for creating scripts to configure source code packages using
183 templates and an M4 macro package.
185 Copyright @copyright{} 1992, 1993, 1994, 1995, 1996, 1998, 1999, 2000,
186 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008 Free Software Foundation, Inc.
188 @quotation
189 Permission is granted to copy, distribute and/or modify this document
190 under the terms of the @acronym{GNU} Free Documentation License,
191 Version 1.2 or any later version published by the Free Software
192 Foundation; with no Invariant Sections, with the Front-Cover texts
193 being ``A @acronym{GNU} Manual,'' and with the Back-Cover Texts as in
194 (a) below.  A copy of the license is included in the section entitled
195 ``@acronym{GNU} Free Documentation License.''
197 (a) The FSF's Back-Cover Text is: ``You have the freedom to copy and
198 modify this @acronym{GNU} manual.  Buying copies from the @acronym{FSF}
199 supports it in developing @acronym{GNU} and promoting software
200 freedom.''
201 @end quotation
202 @end copying
206 @dircategory Software development
207 @direntry
208 * Autoconf: (autoconf).         Create source code configuration scripts.
209 @end direntry
211 @dircategory Individual utilities
212 @direntry
213 * autoscan: (autoconf)autoscan Invocation.
214                                 Semi-automatic @file{configure.ac} writing
215 * ifnames: (autoconf)ifnames Invocation.        Listing conditionals in source.
216 * autoconf-invocation: (autoconf)autoconf Invocation.
217                                 How to create configuration scripts
218 * autoreconf: (autoconf)autoreconf Invocation.
219                                 Remaking multiple @command{configure} scripts
220 * autoheader: (autoconf)autoheader Invocation.
221                                 How to create configuration templates
222 * autom4te: (autoconf)autom4te Invocation.
223                                 The Autoconf executables backbone
224 * configure: (autoconf)configure Invocation.    Configuring a package.
225 * autoupdate: (autoconf)autoupdate Invocation.
226                                 Automatic update of @file{configure.ac}
227 * config.status: (autoconf)config.status Invocation. Recreating configurations.
228 * testsuite: (autoconf)testsuite Invocation.    Running an Autotest test suite.
229 @end direntry
231 @titlepage
232 @title Autoconf
233 @subtitle Creating Automatic Configuration Scripts
234 @subtitle for version @value{VERSION}, @value{UPDATED}
235 @author David MacKenzie
236 @author Ben Elliston
237 @author Akim Demaille
238 @page
239 @vskip 0pt plus 1filll
240 @insertcopying
241 @end titlepage
243 @contents
246 @ifnottex
247 @node Top
248 @top Autoconf
249 @insertcopying
250 @end ifnottex
252 @c The master menu, created with texinfo-master-menu, goes here.
254 @menu
255 * Introduction::                Autoconf's purpose, strengths, and weaknesses
256 * The GNU Build System::        A set of tools for portable software packages
257 * Making configure Scripts::    How to organize and produce Autoconf scripts
258 * Setup::                       Initialization and output
259 * Existing Tests::              Macros that check for particular features
260 * Writing Tests::               How to write new feature checks
261 * Results::                     What to do with results from feature checks
262 * Programming in M4::           Layers on top of which Autoconf is written
263 * Programming in M4sh::         Shell portability layer
264 * Writing Autoconf Macros::     Adding new macros to Autoconf
265 * Portable Shell::              Shell script portability pitfalls
266 * Portable Make::               Makefile portability pitfalls
267 * Portable C and C++::          C and C++ portability pitfalls
268 * Manual Configuration::        Selecting features that can't be guessed
269 * Site Configuration::          Local defaults for @command{configure}
270 * Running configure Scripts::   How to use the Autoconf output
271 * config.status Invocation::    Recreating a configuration
272 * Obsolete Constructs::         Kept for backward compatibility
273 * Using Autotest::              Creating portable test suites
274 * FAQ::                         Frequent Autoconf Questions, with answers
275 * History::                     History of Autoconf
276 * GNU Free Documentation License::  License for copying this manual
277 * Indices::                     Indices of symbols, concepts, etc.
279 @detailmenu
280  --- The Detailed Node Listing ---
282 The @acronym{GNU} Build System
284 * Automake::                    Escaping makefile hell
285 * Gnulib::                      The @acronym{GNU} portability library
286 * Libtool::                     Building libraries portably
287 * Pointers::                    More info on the @acronym{GNU} build system
289 Making @command{configure} Scripts
291 * Writing Autoconf Input::      What to put in an Autoconf input file
292 * autoscan Invocation::         Semi-automatic @file{configure.ac} writing
293 * ifnames Invocation::          Listing the conditionals in source code
294 * autoconf Invocation::         How to create configuration scripts
295 * autoreconf Invocation::       Remaking multiple @command{configure} scripts
297 Writing @file{configure.ac}
299 * Shell Script Compiler::       Autoconf as solution of a problem
300 * Autoconf Language::           Programming in Autoconf
301 * Autoconf Input Layout::       Standard organization of @file{configure.ac}
303 Initialization and Output Files
305 * Initializing configure::      Option processing etc.
306 * Versioning::                  Dealing with Autoconf versions
307 * Notices::                     Copyright, version numbers in @command{configure}
308 * Input::                       Where Autoconf should find files
309 * Output::                      Outputting results from the configuration
310 * Configuration Actions::       Preparing the output based on results
311 * Configuration Files::         Creating output files
312 * Makefile Substitutions::      Using output variables in makefiles
313 * Configuration Headers::       Creating a configuration header file
314 * Configuration Commands::      Running arbitrary instantiation commands
315 * Configuration Links::         Links depending on the configuration
316 * Subdirectories::              Configuring independent packages together
317 * Default Prefix::              Changing the default installation prefix
319 Substitutions in Makefiles
321 * Preset Output Variables::     Output variables that are always set
322 * Installation Directory Variables::  Other preset output variables
323 * Changed Directory Variables:: Warnings about @file{datarootdir}
324 * Build Directories::           Supporting multiple concurrent compiles
325 * Automatic Remaking::          Makefile rules for configuring
327 Configuration Header Files
329 * Header Templates::            Input for the configuration headers
330 * autoheader Invocation::       How to create configuration templates
331 * Autoheader Macros::           How to specify CPP templates
333 Existing Tests
335 * Common Behavior::             Macros' standard schemes
336 * Alternative Programs::        Selecting between alternative programs
337 * Files::                       Checking for the existence of files
338 * Libraries::                   Library archives that might be missing
339 * Library Functions::           C library functions that might be missing
340 * Header Files::                Header files that might be missing
341 * Declarations::                Declarations that may be missing
342 * Structures::                  Structures or members that might be missing
343 * Types::                       Types that might be missing
344 * Compilers and Preprocessors::  Checking for compiling programs
345 * System Services::             Operating system services
346 * Posix Variants::              Special kludges for specific Posix variants
347 * Erlang Libraries::            Checking for the existence of Erlang libraries
349 Common Behavior
351 * Standard Symbols::            Symbols defined by the macros
352 * Default Includes::            Includes used by the generic macros
354 Alternative Programs
356 * Particular Programs::         Special handling to find certain programs
357 * Generic Programs::            How to find other programs
359 Library Functions
361 * Function Portability::        Pitfalls with usual functions
362 * Particular Functions::        Special handling to find certain functions
363 * Generic Functions::           How to find other functions
365 Header Files
367 * Header Portability::          Collected knowledge on common headers
368 * Particular Headers::          Special handling to find certain headers
369 * Generic Headers::             How to find other headers
371 Declarations
373 * Particular Declarations::     Macros to check for certain declarations
374 * Generic Declarations::        How to find other declarations
376 Structures
378 * Particular Structures::       Macros to check for certain structure members
379 * Generic Structures::          How to find other structure members
381 Types
383 * Particular Types::            Special handling to find certain types
384 * Generic Types::               How to find other types
386 Compilers and Preprocessors
388 * Specific Compiler Characteristics::  Some portability issues
389 * Generic Compiler Characteristics::  Language independent tests and features
390 * C Compiler::                  Checking its characteristics
391 * C++ Compiler::                Likewise
392 * Objective C Compiler::        Likewise
393 * Erlang Compiler and Interpreter::  Likewise
394 * Fortran Compiler::            Likewise
396 Writing Tests
398 * Language Choice::             Selecting which language to use for testing
399 * Writing Test Programs::       Forging source files for compilers
400 * Running the Preprocessor::    Detecting preprocessor symbols
401 * Running the Compiler::        Detecting language or header features
402 * Running the Linker::          Detecting library features
403 * Runtime::                     Testing for runtime features
404 * Systemology::                 A zoology of operating systems
405 * Multiple Cases::              Tests for several possible values
407 Writing Test Programs
409 * Guidelines::                  General rules for writing test programs
410 * Test Functions::              Avoiding pitfalls in test programs
411 * Generating Sources::          Source program boilerplate
413 Results of Tests
415 * Defining Symbols::            Defining C preprocessor symbols
416 * Setting Output Variables::    Replacing variables in output files
417 * Special Chars in Variables::  Characters to beware of in variables
418 * Caching Results::             Speeding up subsequent @command{configure} runs
419 * Printing Messages::           Notifying @command{configure} users
421 Caching Results
423 * Cache Variable Names::        Shell variables used in caches
424 * Cache Files::                 Files @command{configure} uses for caching
425 * Cache Checkpointing::         Loading and saving the cache file
427 Programming in M4
429 * M4 Quotation::                Protecting macros from unwanted expansion
430 * Using autom4te::              The Autoconf executables backbone
431 * Programming in M4sugar::      Convenient pure M4 macros
433 Programming in M4sh
435 * Common Shell Constructs::     Portability layer for common shell constructs
436 * Initialization Macros::       Macros to establish a sane shell environment
437 * File Descriptor Macros::      File descriptor macros for input and output
439 M4 Quotation
441 * Active Characters::           Characters that change the behavior of M4
442 * One Macro Call::              Quotation and one macro call
443 * Quoting and Parameters::      M4 vs. shell parameters
444 * Quotation and Nested Macros::  Macros calling macros
445 * Changequote is Evil::         Worse than INTERCAL: M4 + changequote
446 * Quadrigraphs::                Another way to escape special characters
447 * Quotation Rule Of Thumb::     One parenthesis, one quote
449 Using @command{autom4te}
451 * autom4te Invocation::         A @acronym{GNU} M4 wrapper
452 * Customizing autom4te::        Customizing the Autoconf package
454 Programming in M4sugar
456 * Redefined M4 Macros::         M4 builtins changed in M4sugar
457 * Diagnostic Macros::           Diagnostic messages from M4sugar
458 * Diversion support::           Diversions in M4sugar
459 * Conditional constructs::      Conditions in M4
460 * Looping constructs::          Iteration in M4
461 * Evaluation Macros::           More quotation and evaluation control
462 * Text processing Macros::      String manipulation in M4
463 * Number processing Macros::    Arithmetic computation in M4
464 * Set manipulation Macros::     Set manipulation in M4
465 * Forbidden Patterns::          Catching unexpanded macros
467 Writing Autoconf Macros
469 * Macro Definitions::           Basic format of an Autoconf macro
470 * Macro Names::                 What to call your new macros
471 * Reporting Messages::          Notifying @command{autoconf} users
472 * Dependencies Between Macros::  What to do when macros depend on other macros
473 * Obsoleting Macros::           Warning about old ways of doing things
474 * Coding Style::                Writing Autoconf macros @`a la Autoconf
476 Dependencies Between Macros
478 * Prerequisite Macros::         Ensuring required information
479 * Suggested Ordering::          Warning about possible ordering problems
480 * One-Shot Macros::             Ensuring a macro is called only once
482 Portable Shell Programming
484 * Shellology::                  A zoology of shells
485 * Here-Documents::              Quirks and tricks
486 * File Descriptors::            FDs and redirections
487 * File System Conventions::     File names
488 * Shell Pattern Matching::      Pattern matching
489 * Shell Substitutions::         Variable and command expansions
490 * Assignments::                 Varying side effects of assignments
491 * Parentheses::                 Parentheses in shell scripts
492 * Slashes::                     Slashes in shell scripts
493 * Special Shell Variables::     Variables you should not change
494 * Shell Functions::             What to look out for if you use them
495 * Limitations of Builtins::     Portable use of not so portable /bin/sh
496 * Limitations of Usual Tools::  Portable use of portable tools
498 Portable Make Programming
500 * $< in Ordinary Make Rules::   $< in ordinary rules
501 * Failure in Make Rules::       Failing portably in rules
502 * Special Chars in Names::      Special Characters in Macro Names
503 * Backslash-Newline-Newline::   Empty last lines in macro definitions
504 * Backslash-Newline Comments::  Spanning comments across line boundaries
505 * Long Lines in Makefiles::     Line length limitations
506 * Macros and Submakes::         @code{make macro=value} and submakes
507 * The Make Macro MAKEFLAGS::    @code{$(MAKEFLAGS)} portability issues
508 * The Make Macro SHELL::        @code{$(SHELL)} portability issues
509 * Comments in Make Rules::      Other problems with Make comments
510 * obj/ and Make::               Don't name a subdirectory @file{obj}
511 * make -k Status::              Exit status of @samp{make -k}
512 * VPATH and Make::              @code{VPATH} woes
513 * Single Suffix Rules::         Single suffix rules and separated dependencies
514 * Timestamps and Make::         Subsecond timestamp resolution
516 @code{VPATH} and Make
518 * VPATH and Double-colon::      Problems with @samp{::} on ancient hosts
519 * $< in Explicit Rules::        @code{$<} does not work in ordinary rules
520 * Automatic Rule Rewriting::    @code{VPATH} goes wild on Solaris
521 * Tru64 Directory Magic::       @command{mkdir} goes wild on Tru64
522 * Make Target Lookup::          More details about @code{VPATH} lookup
524 Portable C and C++ Programming
526 * Varieties of Unportability::  How to make your programs unportable
527 * Integer Overflow::            When integers get too large
528 * Preprocessor Arithmetic::     @code{#if} expression problems
529 * Null Pointers::               Properties of null pointers
530 * Buffer Overruns::             Subscript errors and the like
531 * Volatile Objects::            @code{volatile} and signals
532 * Floating Point Portability::  Portable floating-point arithmetic
533 * Exiting Portably::            Exiting and the exit status
535 Manual Configuration
537 * Specifying Names::            Specifying the system type
538 * Canonicalizing::              Getting the canonical system type
539 * Using System Type::           What to do with the system type
541 Site Configuration
543 * Help Formatting::             Customizing @samp{configure --help}
544 * External Software::           Working with other optional software
545 * Package Options::             Selecting optional features
546 * Pretty Help Strings::         Formatting help string
547 * Option Checking::             Controlling checking of @command{configure} options
548 * Site Details::                Configuring site details
549 * Transforming Names::          Changing program names when installing
550 * Site Defaults::               Giving @command{configure} local defaults
552 Transforming Program Names When Installing
554 * Transformation Options::      @command{configure} options to transform names
555 * Transformation Examples::     Sample uses of transforming names
556 * Transformation Rules::        Makefile uses of transforming names
558 Running @command{configure} Scripts
560 * Basic Installation::          Instructions for typical cases
561 * Compilers and Options::       Selecting compilers and optimization
562 * Multiple Architectures::      Compiling for multiple architectures at once
563 * Installation Names::          Installing in different directories
564 * Optional Features::           Selecting optional features
565 * Particular Systems::          Particular systems
566 * System Type::                 Specifying the system type
567 * Sharing Defaults::            Setting site-wide defaults for @command{configure}
568 * Defining Variables::          Specifying the compiler etc.
569 * configure Invocation::        Changing how @command{configure} runs
571 Obsolete Constructs
573 * Obsolete config.status Use::  Obsolete convention for @command{config.status}
574 * acconfig Header::             Additional entries in @file{config.h.in}
575 * autoupdate Invocation::       Automatic update of @file{configure.ac}
576 * Obsolete Macros::             Backward compatibility macros
577 * Autoconf 1::                  Tips for upgrading your files
578 * Autoconf 2.13::               Some fresher tips
580 Upgrading From Version 1
582 * Changed File Names::          Files you might rename
583 * Changed Makefiles::           New things to put in @file{Makefile.in}
584 * Changed Macros::              Macro calls you might replace
585 * Changed Results::             Changes in how to check test results
586 * Changed Macro Writing::       Better ways to write your own macros
588 Upgrading From Version 2.13
590 * Changed Quotation::           Broken code which used to work
591 * New Macros::                  Interaction with foreign macros
592 * Hosts and Cross-Compilation::  Bugward compatibility kludges
593 * AC_LIBOBJ vs LIBOBJS::        LIBOBJS is a forbidden token
594 * AC_FOO_IFELSE vs AC_TRY_FOO::  A more generic scheme for testing sources
596 Generating Test Suites with Autotest
598 * Using an Autotest Test Suite::  Autotest and the user
599 * Writing Testsuites::          Autotest macros
600 * testsuite Invocation::        Running @command{testsuite} scripts
601 * Making testsuite Scripts::    Using autom4te to create @command{testsuite}
603 Using an Autotest Test Suite
605 * testsuite Scripts::           The concepts of Autotest
606 * Autotest Logs::               Their contents
608 Frequent Autoconf Questions, with answers
610 * Distributing::                Distributing @command{configure} scripts
611 * Why GNU M4::                  Why not use the standard M4?
612 * Bootstrapping::               Autoconf and @acronym{GNU} M4 require each other?
613 * Why Not Imake::               Why @acronym{GNU} uses @command{configure} instead of Imake
614 * Defining Directories::        Passing @code{datadir} to program
615 * Autom4te Cache::              What is it?  Can I remove it?
616 * Present But Cannot Be Compiled::  Compiler and Preprocessor Disagree
618 History of Autoconf
620 * Genesis::                     Prehistory and naming of @command{configure}
621 * Exodus::                      The plagues of M4 and Perl
622 * Leviticus::                   The priestly code of portability arrives
623 * Numbers::                     Growth and contributors
624 * Deuteronomy::                 Approaching the promises of easy configuration
626 Indices
628 * Environment Variable Index::  Index of environment variables used
629 * Output Variable Index::       Index of variables set in output files
630 * Preprocessor Symbol Index::   Index of C preprocessor symbols defined
631 * Autoconf Macro Index::        Index of Autoconf macros
632 * M4 Macro Index::              Index of M4, M4sugar, and M4sh macros
633 * Autotest Macro Index::        Index of Autotest macros
634 * Program & Function Index::    Index of those with portability problems
635 * Concept Index::               General index
637 @end detailmenu
638 @end menu
640 @c ============================================================= Introduction.
642 @node Introduction
643 @chapter Introduction
644 @cindex Introduction
646 @flushright
647 A physicist, an engineer, and a computer scientist were discussing the
648 nature of God.  ``Surely a Physicist,'' said the physicist, ``because
649 early in the Creation, God made Light; and you know, Maxwell's
650 equations, the dual nature of electromagnetic waves, the relativistic
651 consequences@enddots{}'' ``An Engineer!,'' said the engineer, ``because
652 before making Light, God split the Chaos into Land and Water; it takes a
653 hell of an engineer to handle that big amount of mud, and orderly
654 separation of solids from liquids@enddots{}'' The computer scientist
655 shouted: ``And the Chaos, where do you think it was coming from, hmm?''
657 ---Anonymous
658 @end flushright
659 @c (via Franc,ois Pinard)
661 Autoconf is a tool for producing shell scripts that automatically
662 configure software source code packages to adapt to many kinds of
663 Posix-like systems.  The configuration scripts produced by Autoconf
664 are independent of Autoconf when they are run, so their users do not
665 need to have Autoconf.
667 The configuration scripts produced by Autoconf require no manual user
668 intervention when run; they do not normally even need an argument
669 specifying the system type.  Instead, they individually test for the
670 presence of each feature that the software package they are for might need.
671 (Before each check, they print a one-line message stating what they are
672 checking for, so the user doesn't get too bored while waiting for the
673 script to finish.)  As a result, they deal well with systems that are
674 hybrids or customized from the more common Posix variants.  There is
675 no need to maintain files that list the features supported by each
676 release of each variant of Posix.
678 For each software package that Autoconf is used with, it creates a
679 configuration script from a template file that lists the system features
680 that the package needs or can use.  After the shell code to recognize
681 and respond to a system feature has been written, Autoconf allows it to
682 be shared by many software packages that can use (or need) that feature.
683 If it later turns out that the shell code needs adjustment for some
684 reason, it needs to be changed in only one place; all of the
685 configuration scripts can be regenerated automatically to take advantage
686 of the updated code.
688 @c "Those who do not understand Unix are condemned to reinvent it, poorly."
689 @c --Henry Spencer, 1987 (see http://en.wikipedia.org/wiki/Unix_philosophy)
690 Those who do not understand Autoconf are condemned to reinvent it, poorly.
691 The primary goal of Autoconf is making the @emph{user's} life easier;
692 making the @emph{maintainer's} life easier is only a secondary goal.
693 Put another way, the primary goal is not to make the generation of
694 @file{configure} automatic for package maintainers (although patches
695 along that front are welcome, since package maintainers form the user
696 base of Autoconf); rather, the goal is to make @file{configure}
697 painless, portable, and predictable for the end user of each
698 @dfn{autoconfiscated} package.  And to this degree, Autoconf is highly
699 successful at its goal --- most complaints to the Autoconf list are
700 about difficulties in writing Autoconf input, and not in the behavior of
701 the resulting @file{configure}.  Even packages that don't use Autoconf
702 will generally provide a @file{configure} script, and the most common
703 complaint about these alternative home-grown scripts is that they fail
704 to meet one or more of the @acronym{GNU} Coding Standards that users
705 have come to expect from Autoconf-generated @file{configure} scripts.
707 The Metaconfig package is similar in purpose to Autoconf, but the
708 scripts it produces require manual user intervention, which is quite
709 inconvenient when configuring large source trees.  Unlike Metaconfig
710 scripts, Autoconf scripts can support cross-compiling, if some care is
711 taken in writing them.
713 Autoconf does not solve all problems related to making portable
714 software packages---for a more complete solution, it should be used in
715 concert with other @acronym{GNU} build tools like Automake and
716 Libtool.  These other tools take on jobs like the creation of a
717 portable, recursive makefile with all of the standard targets,
718 linking of shared libraries, and so on.  @xref{The GNU Build System},
719 for more information.
721 Autoconf imposes some restrictions on the names of macros used with
722 @code{#if} in C programs (@pxref{Preprocessor Symbol Index}).
724 Autoconf requires @acronym{GNU} M4 version 1.4.5 or later in order to
725 generate the scripts.  It uses features that some versions of M4,
726 including @acronym{GNU} M4 1.3, do not have.  Autoconf works better
727 with @acronym{GNU} M4 version 1.4.11 or later, though this is not
728 required.
730 @xref{Autoconf 1}, for information about upgrading from version 1.
731 @xref{History}, for the story of Autoconf's development.  @xref{FAQ},
732 for answers to some common questions about Autoconf.
734 See the @uref{http://@/www.gnu.org/@/software/@/autoconf/,
735 Autoconf web page} for up-to-date information, details on the mailing
736 lists, pointers to a list of known bugs, etc.
738 Mail suggestions to @email{autoconf@@gnu.org, the Autoconf mailing
739 list}.  Past suggestions are
740 @uref{http://@/lists.gnu.org/@/archive/@/html/@/autoconf/, archived}.
742 Mail bug reports to @email{bug-autoconf@@gnu.org, the
743 Autoconf Bugs mailing list}.  Past bug reports are
744 @uref{http://@/lists.gnu.org/@/archive/@/html/@/bug-autoconf/, archived}.
746 If possible, first check that your bug is
747 not already solved in current development versions, and that it has not
748 been reported yet.  Be sure to include all the needed information and a
749 short @file{configure.ac} that demonstrates the problem.
751 Autoconf's development tree is accessible via @command{git}; see the
752 @uref{http://@/savannah.gnu.org/@/projects/@/autoconf/, Autoconf
753 Summary} for details, or view
754 @uref{http://@/git.sv.gnu.org/@/gitweb/@/?p=autoconf.git, the actual
755 repository}.  Anonymous @acronym{CVS} access is also available, see
756 @file{README} for more details.  Patches relative to the
757 current @command{git} version can be sent for review to the
758 @email{autoconf-patches@@gnu.org, Autoconf Patches mailing list}, with
759 discussion on prior patches
760 @uref{http://@/lists.gnu.org/@/archive/@/html/@/autoconf-@/patches/,
761 archived}; and all commits are posted in the read-only
762 @email{autoconf-commit@@gnu.org, Autoconf Commit mailing list}, which is
763 also @uref{http://@/lists.gnu.org/@/archive/@/html/@/autoconf-commit/,
764 archived}.
766 Because of its mission, the Autoconf package itself
767 includes only a set of often-used
768 macros that have already demonstrated their usefulness.  Nevertheless,
769 if you wish to share your macros, or find existing ones, see the
770 @uref{http://@/autoconf-archive.cryp.to/, Autoconf Macro
771 Archive}, which is kindly run by @email{simons@@cryp.to,
772 Peter Simons}.
775 @c ================================================= The GNU Build System
777 @node The GNU Build System
778 @chapter The @acronym{GNU} Build System
779 @cindex @acronym{GNU} build system
781 Autoconf solves an important problem---reliable discovery of
782 system-specific build and runtime information---but this is only one
783 piece of the puzzle for the development of portable software.  To this
784 end, the @acronym{GNU} project has developed a suite of integrated
785 utilities to finish the job Autoconf started: the @acronym{GNU} build
786 system, whose most important components are Autoconf, Automake, and
787 Libtool.  In this chapter, we introduce you to those tools, point you
788 to sources of more information, and try to convince you to use the
789 entire @acronym{GNU} build system for your software.
791 @menu
792 * Automake::                    Escaping makefile hell
793 * Gnulib::                      The @acronym{GNU} portability library
794 * Libtool::                     Building libraries portably
795 * Pointers::                    More info on the @acronym{GNU} build system
796 @end menu
798 @node Automake
799 @section Automake
801 The ubiquity of @command{make} means that a makefile is almost the
802 only viable way to distribute automatic build rules for software, but
803 one quickly runs into its numerous limitations.  Its lack of
804 support for automatic dependency tracking, recursive builds in
805 subdirectories, reliable timestamps (e.g., for network file systems), and
806 so on, mean that developers must painfully (and often incorrectly)
807 reinvent the wheel for each project.  Portability is non-trivial, thanks
808 to the quirks of @command{make} on many systems.  On top of all this is the
809 manual labor required to implement the many standard targets that users
810 have come to expect (@code{make install}, @code{make distclean},
811 @code{make uninstall}, etc.).  Since you are, of course, using Autoconf,
812 you also have to insert repetitive code in your @file{Makefile.in} to
813 recognize @code{@@CC@@}, @code{@@CFLAGS@@}, and other substitutions
814 provided by @command{configure}.  Into this mess steps @dfn{Automake}.
815 @cindex Automake
817 Automake allows you to specify your build needs in a @file{Makefile.am}
818 file with a vastly simpler and more powerful syntax than that of a plain
819 makefile, and then generates a portable @file{Makefile.in} for
820 use with Autoconf.  For example, the @file{Makefile.am} to build and
821 install a simple ``Hello world'' program might look like:
823 @example
824 bin_PROGRAMS = hello
825 hello_SOURCES = hello.c
826 @end example
828 @noindent
829 The resulting @file{Makefile.in} (~400 lines) automatically supports all
830 the standard targets, the substitutions provided by Autoconf, automatic
831 dependency tracking, @code{VPATH} building, and so on.  @command{make}
832 builds the @code{hello} program, and @code{make install} installs it
833 in @file{/usr/local/bin} (or whatever prefix was given to
834 @command{configure}, if not @file{/usr/local}).
836 The benefits of Automake increase for larger packages (especially ones
837 with subdirectories), but even for small programs the added convenience
838 and portability can be substantial.  And that's not all@enddots{}
840 @node Gnulib
841 @section Gnulib
843 @acronym{GNU} software has a well-deserved reputation for running on
844 many different types of systems.  While our primary goal is to write
845 software for the @acronym{GNU} system, many users and developers have
846 been introduced to us through the systems that they were already using.
848 @cindex Gnulib
849 Gnulib is a central location for common @acronym{GNU} code, intended to
850 be shared among free software packages.  Its components are typically
851 shared at the source level, rather than being a library that gets built,
852 installed, and linked against.  The idea is to copy files from Gnulib
853 into your own source tree.  There is no distribution tarball; developers
854 should just grab source modules from the repository.  The source files
855 are available online, under various licenses, mostly @acronym{GNU}
856 @acronym{GPL} or @acronym{GNU} @acronym{LGPL}.
858 Gnulib modules typically contain C source code along with Autoconf
859 macros used to configure the source code.  For example, the Gnulib
860 @code{stdbool} module implements a @file{stdbool.h} header that nearly
861 conforms to C99, even on old-fashioned hosts that lack @file{stdbool.h}.
862 This module contains a source file for the replacement header, along
863 with an Autoconf macro that arranges to use the replacement header on
864 old-fashioned systems.
866 @node Libtool
867 @section Libtool
869 Often, one wants to build not only programs, but libraries, so that
870 other programs can benefit from the fruits of your labor.  Ideally, one
871 would like to produce @emph{shared} (dynamically linked) libraries,
872 which can be used by multiple programs without duplication on disk or in
873 memory and can be updated independently of the linked programs.
874 Producing shared libraries portably, however, is the stuff of
875 nightmares---each system has its own incompatible tools, compiler flags,
876 and magic incantations.  Fortunately, @acronym{GNU} provides a solution:
877 @dfn{Libtool}.
878 @cindex Libtool
880 Libtool handles all the requirements of building shared libraries for
881 you, and at this time seems to be the @emph{only} way to do so with any
882 portability.  It also handles many other headaches, such as: the
883 interaction of Make rules with the variable suffixes of
884 shared libraries, linking reliably with shared libraries before they are
885 installed by the superuser, and supplying a consistent versioning system
886 (so that different versions of a library can be installed or upgraded
887 without breaking binary compatibility).  Although Libtool, like
888 Autoconf, can be used without Automake, it is most simply utilized in
889 conjunction with Automake---there, Libtool is used automatically
890 whenever shared libraries are needed, and you need not know its syntax.
892 @node Pointers
893 @section Pointers
895 Developers who are used to the simplicity of @command{make} for small
896 projects on a single system might be daunted at the prospect of
897 learning to use Automake and Autoconf.  As your software is
898 distributed to more and more users, however, you otherwise
899 quickly find yourself putting lots of effort into reinventing the
900 services that the @acronym{GNU} build tools provide, and making the
901 same mistakes that they once made and overcame.  (Besides, since
902 you're already learning Autoconf, Automake is a piece of cake.)
904 There are a number of places that you can go to for more information on
905 the @acronym{GNU} build tools.
907 @itemize @minus
909 @item Web
911 The project home pages for
912 @uref{http://@/www@/.gnu@/.org/@/software/@/autoconf/, Autoconf},
913 @uref{http://@/www@/.gnu@/.org/@/software/@/automake/, Automake},
914 @uref{http://@/www@/.gnu@/.org/@/software/@/gnulib/, Gnulib}, and
915 @uref{http://@/www@/.gnu@/.org/@/software/@/libtool/, Libtool}.
917 @item Automake Manual
919 @xref{Top, , Automake, automake, @acronym{GNU} Automake}, for more
920 information on Automake.
922 @item Books
924 The book @cite{@acronym{GNU} Autoconf, Automake and
925 Libtool}@footnote{@cite{@acronym{GNU} Autoconf, Automake and Libtool},
926 by G. V. Vaughan, B. Elliston, T. Tromey, and I. L. Taylor.  SAMS (originally
927 New Riders), 2000, ISBN 1578701902.} describes the complete @acronym{GNU}
928 build environment.  You can also find
929 @uref{http://@/sources.redhat.com/@/autobook/, the entire book on-line}.
931 @end itemize
933 @c ================================================= Making configure Scripts.
935 @node Making configure Scripts
936 @chapter Making @command{configure} Scripts
937 @cindex @file{aclocal.m4}
938 @cindex @command{configure}
940 The configuration scripts that Autoconf produces are by convention
941 called @command{configure}.  When run, @command{configure} creates several
942 files, replacing configuration parameters in them with appropriate
943 values.  The files that @command{configure} creates are:
945 @itemize @minus
946 @item
947 one or more @file{Makefile} files, usually one in each subdirectory of the
948 package (@pxref{Makefile Substitutions});
950 @item
951 optionally, a C header file, the name of which is configurable,
952 containing @code{#define} directives (@pxref{Configuration Headers});
954 @item
955 a shell script called @file{config.status} that, when run, recreates
956 the files listed above (@pxref{config.status Invocation});
958 @item
959 an optional shell script normally called @file{config.cache}
960 (created when using @samp{configure --config-cache}) that
961 saves the results of running many of the tests (@pxref{Cache Files});
963 @item
964 a file called @file{config.log} containing any messages produced by
965 compilers, to help debugging if @command{configure} makes a mistake.
966 @end itemize
968 @cindex @file{configure.in}
969 @cindex @file{configure.ac}
970 To create a @command{configure} script with Autoconf, you need to write an
971 Autoconf input file @file{configure.ac} (or @file{configure.in}) and run
972 @command{autoconf} on it.  If you write your own feature tests to
973 supplement those that come with Autoconf, you might also write files
974 called @file{aclocal.m4} and @file{acsite.m4}.  If you use a C header
975 file to contain @code{#define} directives, you might also run
976 @command{autoheader}, and you can distribute the generated file
977 @file{config.h.in} with the package.
979 Here is a diagram showing how the files that can be used in
980 configuration are produced.  Programs that are executed are suffixed by
981 @samp{*}.  Optional files are enclosed in square brackets (@samp{[]}).
982 @command{autoconf} and @command{autoheader} also read the installed Autoconf
983 macro files (by reading @file{autoconf.m4}).
985 @noindent
986 Files used in preparing a software package for distribution:
987 @example
988 your source files --> [autoscan*] --> [configure.scan] --> configure.ac
990 @group
991 configure.ac --.
992                |   .------> autoconf* -----> configure
993 [aclocal.m4] --+---+
994                |   `-----> [autoheader*] --> [config.h.in]
995 [acsite.m4] ---'
996 @end group
998 Makefile.in -------------------------------> Makefile.in
999 @end example
1001 @noindent
1002 Files used in configuring a software package:
1003 @example
1004 @group
1005                        .-------------> [config.cache]
1006 configure* ------------+-------------> config.log
1007                        |
1008 [config.h.in] -.       v            .-> [config.h] -.
1009                +--> config.status* -+               +--> make*
1010 Makefile.in ---'                    `-> Makefile ---'
1011 @end group
1012 @end example
1014 @menu
1015 * Writing Autoconf Input::      What to put in an Autoconf input file
1016 * autoscan Invocation::         Semi-automatic @file{configure.ac} writing
1017 * ifnames Invocation::          Listing the conditionals in source code
1018 * autoconf Invocation::         How to create configuration scripts
1019 * autoreconf Invocation::       Remaking multiple @command{configure} scripts
1020 @end menu
1022 @node Writing Autoconf Input
1023 @section Writing @file{configure.ac}
1025 To produce a @command{configure} script for a software package, create a
1026 file called @file{configure.ac} that contains invocations of the
1027 Autoconf macros that test the system features your package needs or can
1028 use.  Autoconf macros already exist to check for many features; see
1029 @ref{Existing Tests}, for their descriptions.  For most other features,
1030 you can use Autoconf template macros to produce custom checks; see
1031 @ref{Writing Tests}, for information about them.  For especially tricky
1032 or specialized features, @file{configure.ac} might need to contain some
1033 hand-crafted shell commands; see @ref{Portable Shell}.  The
1034 @command{autoscan} program can give you a good start in writing
1035 @file{configure.ac} (@pxref{autoscan Invocation}, for more information).
1037 Previous versions of Autoconf promoted the name @file{configure.in},
1038 which is somewhat ambiguous (the tool needed to process this file is not
1039 described by its extension), and introduces a slight confusion with
1040 @file{config.h.in} and so on (for which @samp{.in} means ``to be
1041 processed by @command{configure}'').  Using @file{configure.ac} is now
1042 preferred.
1044 @menu
1045 * Shell Script Compiler::       Autoconf as solution of a problem
1046 * Autoconf Language::           Programming in Autoconf
1047 * Autoconf Input Layout::       Standard organization of @file{configure.ac}
1048 @end menu
1050 @node Shell Script Compiler
1051 @subsection A Shell Script Compiler
1053 Just as for any other computer language, in order to properly program
1054 @file{configure.ac} in Autoconf you must understand @emph{what} problem
1055 the language tries to address and @emph{how} it does so.
1057 The problem Autoconf addresses is that the world is a mess.  After all,
1058 you are using Autoconf in order to have your package compile easily on
1059 all sorts of different systems, some of them being extremely hostile.
1060 Autoconf itself bears the price for these differences: @command{configure}
1061 must run on all those systems, and thus @command{configure} must limit itself
1062 to their lowest common denominator of features.
1064 Naturally, you might then think of shell scripts; who needs
1065 @command{autoconf}?  A set of properly written shell functions is enough to
1066 make it easy to write @command{configure} scripts by hand.  Sigh!
1067 Unfortunately, even in 2008, where shells without any function support are
1068 far and few between, there are pitfalls to avoid when making use of them.
1069 Also, finding a Bourne shell that accepts shell functions is not trivial,
1070 even though there is almost always one on interesting porting targets.
1072 So, what is really needed is some kind of compiler, @command{autoconf},
1073 that takes an Autoconf program, @file{configure.ac}, and transforms it
1074 into a portable shell script, @command{configure}.
1076 How does @command{autoconf} perform this task?
1078 There are two obvious possibilities: creating a brand new language or
1079 extending an existing one.  The former option is attractive: all
1080 sorts of optimizations could easily be implemented in the compiler and
1081 many rigorous checks could be performed on the Autoconf program
1082 (e.g., rejecting any non-portable construct).  Alternatively, you can
1083 extend an existing language, such as the @code{sh} (Bourne shell)
1084 language.
1086 Autoconf does the latter: it is a layer on top of @code{sh}.  It was
1087 therefore most convenient to implement @command{autoconf} as a macro
1088 expander: a program that repeatedly performs @dfn{macro expansions} on
1089 text input, replacing macro calls with macro bodies and producing a pure
1090 @code{sh} script in the end.  Instead of implementing a dedicated
1091 Autoconf macro expander, it is natural to use an existing
1092 general-purpose macro language, such as M4, and implement the extensions
1093 as a set of M4 macros.
1096 @node Autoconf Language
1097 @subsection The Autoconf Language
1098 @cindex quotation
1100 The Autoconf language differs from many other computer
1101 languages because it treats actual code the same as plain text.  Whereas
1102 in C, for instance, data and instructions have different syntactic
1103 status, in Autoconf their status is rigorously the same.  Therefore, we
1104 need a means to distinguish literal strings from text to be expanded:
1105 quotation.
1107 When calling macros that take arguments, there must not be any white
1108 space between the macro name and the open parenthesis.  Arguments should
1109 be enclosed within the M4 quote characters @samp{[} and @samp{]}, and be
1110 separated by commas.  Any leading blanks or newlines in arguments are ignored,
1111 unless they are quoted.  You should always quote an argument that
1112 might contain a macro name, comma, parenthesis, or a leading blank or
1113 newline.  This rule applies recursively for every macro
1114 call, including macros called from other macros.
1116 For instance:
1118 @example
1119 AC_CHECK_HEADER([stdio.h],
1120                 [AC_DEFINE([HAVE_STDIO_H], [1],
1121                    [Define to 1 if you have <stdio.h>.])],
1122                 [AC_MSG_ERROR([Sorry, can't do anything for you])])
1123 @end example
1125 @noindent
1126 is quoted properly.  You may safely simplify its quotation to:
1128 @example
1129 AC_CHECK_HEADER([stdio.h],
1130                 [AC_DEFINE([HAVE_STDIO_H], 1,
1131                    [Define to 1 if you have <stdio.h>.])],
1132                 [AC_MSG_ERROR([Sorry, can't do anything for you])])
1133 @end example
1135 @noindent
1136 because @samp{1} cannot contain a macro call.  Here, the argument of
1137 @code{AC_MSG_ERROR} must be quoted; otherwise, its comma would be
1138 interpreted as an argument separator.  Also, the second and third arguments
1139 of @samp{AC_CHECK_HEADER} must be quoted, since they contain
1140 macro calls.  The three arguments @samp{HAVE_STDIO_H}, @samp{stdio.h},
1141 and @samp{Define to 1 if you have <stdio.h>.} do not need quoting, but
1142 if you unwisely defined a macro with a name like @samp{Define} or
1143 @samp{stdio} then they would need quoting.  Cautious Autoconf users
1144 would keep the quotes, but many Autoconf users find such precautions
1145 annoying, and would rewrite the example as follows:
1147 @example
1148 AC_CHECK_HEADER(stdio.h,
1149                 [AC_DEFINE(HAVE_STDIO_H, 1,
1150                    [Define to 1 if you have <stdio.h>.])],
1151                 [AC_MSG_ERROR([Sorry, can't do anything for you])])
1152 @end example
1154 @noindent
1155 This is safe, so long as you adopt good naming conventions and do not
1156 define macros with names like @samp{HAVE_STDIO_H}, @samp{stdio}, or
1157 @samp{h}.  Though it is also safe here to omit the quotes around
1158 @samp{Define to 1 if you have <stdio.h>.} this is not recommended, as
1159 message strings are more likely to inadvertently contain commas.
1161 The following example is wrong and dangerous, as it is underquoted:
1163 @example
1164 AC_CHECK_HEADER(stdio.h,
1165                 AC_DEFINE(HAVE_STDIO_H, 1,
1166                    Define to 1 if you have <stdio.h>.),
1167                 AC_MSG_ERROR([Sorry, can't do anything for you]))
1168 @end example
1170 In other cases, you may have to use text that also resembles a macro
1171 call.  You must quote that text even when it is not passed as a macro
1172 argument:
1174 @example
1175 echo "Hard rock was here!  --[AC_DC]"
1176 @end example
1178 @noindent
1179 which results in:
1181 @example
1182 echo "Hard rock was here!  --AC_DC"
1183 @end example
1185 @noindent
1186 When you use the same text in a macro argument, you must therefore have
1187 an extra quotation level (since one is stripped away by the macro
1188 substitution).  In general, then, it is a good idea to @emph{use double
1189 quoting for all literal string arguments}:
1191 @example
1192 AC_MSG_WARN([[AC_DC stinks  --Iron Maiden]])
1193 @end example
1195 You are now able to understand one of the constructs of Autoconf that
1196 has been continually misunderstood@enddots{}  The rule of thumb is that
1197 @emph{whenever you expect macro expansion, expect quote expansion};
1198 i.e., expect one level of quotes to be lost.  For instance:
1200 @example
1201 AC_COMPILE_IFELSE([char b[10];], [], [AC_MSG_ERROR([you lose])])
1202 @end example
1204 @noindent
1205 is incorrect: here, the first argument of @code{AC_COMPILE_IFELSE} is
1206 @samp{char b[10];} and is expanded once, which results in
1207 @samp{char b10;}.  (There was an idiom common in Autoconf's past to
1208 address this issue via the M4 @code{changequote} primitive, but do not
1209 use it!)  Let's take a closer look: the author meant the first argument
1210 to be understood as a literal, and therefore it must be quoted twice:
1212 @example
1213 AC_COMPILE_IFELSE([[char b[10];]], [], [AC_MSG_ERROR([you lose])])
1214 @end example
1216 @noindent
1217 Voil@`a, you actually produce @samp{char b[10];} this time!
1219 On the other hand, descriptions (e.g., the last parameter of
1220 @code{AC_DEFINE} or @code{AS_HELP_STRING}) are not literals---they
1221 are subject to line breaking, for example---and should not be double quoted.
1222 Even if these descriptions are short and are not actually broken, double
1223 quoting them yields weird results.
1225 Some macros take optional arguments, which this documentation represents
1226 as @ovar{arg} (not to be confused with the quote characters).  You may
1227 just leave them empty, or use @samp{[]} to make the emptiness of the
1228 argument explicit, or you may simply omit the trailing commas.  The
1229 three lines below are equivalent:
1231 @example
1232 AC_CHECK_HEADERS([stdio.h], [], [], [])
1233 AC_CHECK_HEADERS([stdio.h],,,)
1234 AC_CHECK_HEADERS([stdio.h])
1235 @end example
1237 It is best to put each macro call on its own line in
1238 @file{configure.ac}.  Most of the macros don't add extra newlines; they
1239 rely on the newline after the macro call to terminate the commands.
1240 This approach makes the generated @command{configure} script a little
1241 easier to read by not inserting lots of blank lines.  It is generally
1242 safe to set shell variables on the same line as a macro call, because
1243 the shell allows assignments without intervening newlines.
1245 You can include comments in @file{configure.ac} files by starting them
1246 with the @samp{#}.  For example, it is helpful to begin
1247 @file{configure.ac} files with a line like this:
1249 @example
1250 # Process this file with autoconf to produce a configure script.
1251 @end example
1253 @node Autoconf Input Layout
1254 @subsection Standard @file{configure.ac} Layout
1256 The order in which @file{configure.ac} calls the Autoconf macros is not
1257 important, with a few exceptions.  Every @file{configure.ac} must
1258 contain a call to @code{AC_INIT} before the checks, and a call to
1259 @code{AC_OUTPUT} at the end (@pxref{Output}).  Additionally, some macros
1260 rely on other macros having been called first, because they check
1261 previously set values of some variables to decide what to do.  These
1262 macros are noted in the individual descriptions (@pxref{Existing
1263 Tests}), and they also warn you when @command{configure} is created if they
1264 are called out of order.
1266 To encourage consistency, here is a suggested order for calling the
1267 Autoconf macros.  Generally speaking, the things near the end of this
1268 list are those that could depend on things earlier in it.  For example,
1269 library functions could be affected by types and libraries.
1271 @display
1272 @group
1273 Autoconf requirements
1274 @code{AC_INIT(@var{package}, @var{version}, @var{bug-report-address})}
1275 information on the package
1276 checks for programs
1277 checks for libraries
1278 checks for header files
1279 checks for types
1280 checks for structures
1281 checks for compiler characteristics
1282 checks for library functions
1283 checks for system services
1284 @code{AC_CONFIG_FILES(@r{[}@var{file@dots{}}@r{]})}
1285 @code{AC_OUTPUT}
1286 @end group
1287 @end display
1290 @node autoscan Invocation
1291 @section Using @command{autoscan} to Create @file{configure.ac}
1292 @cindex @command{autoscan}
1294 The @command{autoscan} program can help you create and/or maintain a
1295 @file{configure.ac} file for a software package.  @command{autoscan}
1296 examines source files in the directory tree rooted at a directory given
1297 as a command line argument, or the current directory if none is given.
1298 It searches the source files for common portability problems and creates
1299 a file @file{configure.scan} which is a preliminary @file{configure.ac}
1300 for that package, and checks a possibly existing @file{configure.ac} for
1301 completeness.
1303 When using @command{autoscan} to create a @file{configure.ac}, you
1304 should manually examine @file{configure.scan} before renaming it to
1305 @file{configure.ac}; it probably needs some adjustments.
1306 Occasionally, @command{autoscan} outputs a macro in the wrong order
1307 relative to another macro, so that @command{autoconf} produces a warning;
1308 you need to move such macros manually.  Also, if you want the package to
1309 use a configuration header file, you must add a call to
1310 @code{AC_CONFIG_HEADERS} (@pxref{Configuration Headers}).  You might
1311 also have to change or add some @code{#if} directives to your program in
1312 order to make it work with Autoconf (@pxref{ifnames Invocation}, for
1313 information about a program that can help with that job).
1315 When using @command{autoscan} to maintain a @file{configure.ac}, simply
1316 consider adding its suggestions.  The file @file{autoscan.log}
1317 contains detailed information on why a macro is requested.
1319 @command{autoscan} uses several data files (installed along with Autoconf)
1320 to determine which macros to output when it finds particular symbols in
1321 a package's source files.  These data files all have the same format:
1322 each line consists of a symbol, one or more blanks, and the Autoconf macro to
1323 output if that symbol is encountered.  Lines starting with @samp{#} are
1324 comments.
1326 @command{autoscan} accepts the following options:
1328 @table @option
1329 @item --help
1330 @itemx -h
1331 Print a summary of the command line options and exit.
1333 @item --version
1334 @itemx -V
1335 Print the version number of Autoconf and exit.
1337 @item --verbose
1338 @itemx -v
1339 Print the names of the files it examines and the potentially interesting
1340 symbols it finds in them.  This output can be voluminous.
1342 @item --debug
1343 @itemx -d
1344 Don't remove temporary files.
1346 @item --include=@var{dir}
1347 @itemx -I @var{dir}
1348 Append @var{dir} to the include path.  Multiple invocations accumulate.
1350 @item --prepend-include=@var{dir}
1351 @itemx -B @var{dir}
1352 Prepend @var{dir} to the include path.  Multiple invocations accumulate.
1353 @end table
1355 @node ifnames Invocation
1356 @section Using @command{ifnames} to List Conditionals
1357 @cindex @command{ifnames}
1359 @command{ifnames} can help you write @file{configure.ac} for a software
1360 package.  It prints the identifiers that the package already uses in C
1361 preprocessor conditionals.  If a package has already been set up to have
1362 some portability, @command{ifnames} can thus help you figure out what its
1363 @command{configure} needs to check for.  It may help fill in some gaps in a
1364 @file{configure.ac} generated by @command{autoscan} (@pxref{autoscan
1365 Invocation}).
1367 @command{ifnames} scans all of the C source files named on the command line
1368 (or the standard input, if none are given) and writes to the standard
1369 output a sorted list of all the identifiers that appear in those files
1370 in @code{#if}, @code{#elif}, @code{#ifdef}, or @code{#ifndef}
1371 directives.  It prints each identifier on a line, followed by a
1372 space-separated list of the files in which that identifier occurs.
1374 @noindent
1375 @command{ifnames} accepts the following options:
1377 @table @option
1378 @item --help
1379 @itemx -h
1380 Print a summary of the command line options and exit.
1382 @item --version
1383 @itemx -V
1384 Print the version number of Autoconf and exit.
1385 @end table
1387 @node autoconf Invocation
1388 @section Using @command{autoconf} to Create @command{configure}
1389 @cindex @command{autoconf}
1391 To create @command{configure} from @file{configure.ac}, run the
1392 @command{autoconf} program with no arguments.  @command{autoconf} processes
1393 @file{configure.ac} with the M4 macro processor, using the
1394 Autoconf macros.  If you give @command{autoconf} an argument, it reads that
1395 file instead of @file{configure.ac} and writes the configuration script
1396 to the standard output instead of to @command{configure}.  If you give
1397 @command{autoconf} the argument @option{-}, it reads from the standard
1398 input instead of @file{configure.ac} and writes the configuration script
1399 to the standard output.
1401 The Autoconf macros are defined in several files.  Some of the files are
1402 distributed with Autoconf; @command{autoconf} reads them first.  Then it
1403 looks for the optional file @file{acsite.m4} in the directory that
1404 contains the distributed Autoconf macro files, and for the optional file
1405 @file{aclocal.m4} in the current directory.  Those files can contain
1406 your site's or the package's own Autoconf macro definitions
1407 (@pxref{Writing Autoconf Macros}, for more information).  If a macro is
1408 defined in more than one of the files that @command{autoconf} reads, the
1409 last definition it reads overrides the earlier ones.
1411 @command{autoconf} accepts the following options:
1413 @table @option
1414 @item --help
1415 @itemx -h
1416 Print a summary of the command line options and exit.
1418 @item --version
1419 @itemx -V
1420 Print the version number of Autoconf and exit.
1422 @item --verbose
1423 @itemx -v
1424 Report processing steps.
1426 @item --debug
1427 @itemx -d
1428 Don't remove the temporary files.
1430 @item --force
1431 @itemx -f
1432 Remake @file{configure} even if newer than its input files.
1434 @item --include=@var{dir}
1435 @itemx -I @var{dir}
1436 Append @var{dir} to the include path.  Multiple invocations accumulate.
1438 @item --prepend-include=@var{dir}
1439 @itemx -B @var{dir}
1440 Prepend @var{dir} to the include path.  Multiple invocations accumulate.
1442 @item --output=@var{file}
1443 @itemx -o @var{file}
1444 Save output (script or trace) to @var{file}.  The file @option{-} stands
1445 for the standard output.
1447 @item --warnings=@var{category}
1448 @itemx -W @var{category}
1449 @evindex WARNINGS
1450 Report the warnings related to @var{category} (which can actually be a
1451 comma separated list).  @xref{Reporting Messages}, macro
1452 @code{AC_DIAGNOSE}, for a comprehensive list of categories.  Special
1453 values include:
1455 @table @samp
1456 @item all
1457 report all the warnings
1459 @item none
1460 report none
1462 @item error
1463 treats warnings as errors
1465 @item no-@var{category}
1466 disable warnings falling into @var{category}
1467 @end table
1469 Warnings about @samp{syntax} are enabled by default, and the environment
1470 variable @env{WARNINGS}, a comma separated list of categories, is
1471 honored as well.  Passing @option{-W @var{category}} actually behaves as if
1472 you had passed @option{--warnings syntax,$WARNINGS,@var{category}}.  If
1473 you want to disable the defaults and @env{WARNINGS}, but (for example)
1474 enable the warnings about obsolete constructs, you would use @option{-W
1475 none,obsolete}.
1477 @cindex Back trace
1478 @cindex Macro invocation stack
1479 Because @command{autoconf} uses @command{autom4te} behind the scenes, it
1480 displays a back trace for errors, but not for warnings; if you want
1481 them, just pass @option{-W error}.  @xref{autom4te Invocation}, for some
1482 examples.
1484 @item --trace=@var{macro}[:@var{format}]
1485 @itemx -t @var{macro}[:@var{format}]
1486 Do not create the @command{configure} script, but list the calls to
1487 @var{macro} according to the @var{format}.  Multiple @option{--trace}
1488 arguments can be used to list several macros.  Multiple @option{--trace}
1489 arguments for a single macro are not cumulative; instead, you should
1490 just make @var{format} as long as needed.
1492 The @var{format} is a regular string, with newlines if desired, and
1493 several special escape codes.  It defaults to @samp{$f:$l:$n:$%}; see
1494 @ref{autom4te Invocation}, for details on the @var{format}.
1496 @item --initialization
1497 @itemx -i
1498 By default, @option{--trace} does not trace the initialization of the
1499 Autoconf macros (typically the @code{AC_DEFUN} definitions).  This
1500 results in a noticeable speedup, but can be disabled by this option.
1501 @end table
1504 It is often necessary to check the content of a @file{configure.ac}
1505 file, but parsing it yourself is extremely fragile and error-prone.  It
1506 is suggested that you rely upon @option{--trace} to scan
1507 @file{configure.ac}.  For instance, to find the list of variables that
1508 are substituted, use:
1510 @example
1511 @group
1512 $ @kbd{autoconf -t AC_SUBST}
1513 configure.ac:2:AC_SUBST:ECHO_C
1514 configure.ac:2:AC_SUBST:ECHO_N
1515 configure.ac:2:AC_SUBST:ECHO_T
1516 @i{More traces deleted}
1517 @end group
1518 @end example
1520 @noindent
1521 The example below highlights the difference between @samp{$@@},
1522 @samp{$*}, and @samp{$%}.
1524 @example
1525 @group
1526 $ @kbd{cat configure.ac}
1527 AC_DEFINE(This, is, [an
1528 [example]])
1529 $ @kbd{autoconf -t 'AC_DEFINE:@@: $@@}
1530 *: $*
1531 %: $%'
1532 @@: [This],[is],[an
1533 [example]]
1534 *: This,is,an
1535 [example]
1536 %: This:is:an [example]
1537 @end group
1538 @end example
1540 @noindent
1541 The @var{format} gives you a lot of freedom:
1543 @example
1544 @group
1545 $ @kbd{autoconf -t 'AC_SUBST:$$ac_subst@{"$1"@} = "$f:$l";'}
1546 $ac_subst@{"ECHO_C"@} = "configure.ac:2";
1547 $ac_subst@{"ECHO_N"@} = "configure.ac:2";
1548 $ac_subst@{"ECHO_T"@} = "configure.ac:2";
1549 @i{More traces deleted}
1550 @end group
1551 @end example
1553 @noindent
1554 A long @var{separator} can be used to improve the readability of complex
1555 structures, and to ease their parsing (for instance when no single
1556 character is suitable as a separator):
1558 @example
1559 @group
1560 $ @kbd{autoconf -t 'AM_MISSING_PROG:$@{|:::::|@}*'}
1561 ACLOCAL|:::::|aclocal|:::::|$missing_dir
1562 AUTOCONF|:::::|autoconf|:::::|$missing_dir
1563 AUTOMAKE|:::::|automake|:::::|$missing_dir
1564 @i{More traces deleted}
1565 @end group
1566 @end example
1568 @node autoreconf Invocation
1569 @section Using @command{autoreconf} to Update @command{configure} Scripts
1570 @cindex @command{autoreconf}
1572 Installing the various components of the @acronym{GNU} Build System can be
1573 tedious: running @command{autopoint} for Gettext, @command{automake} for
1574 @file{Makefile.in} etc.@: in each directory.  It may be needed either
1575 because some tools such as @command{automake} have been updated on your
1576 system, or because some of the sources such as @file{configure.ac} have
1577 been updated, or finally, simply in order to install the @acronym{GNU} Build
1578 System in a fresh tree.
1580 @command{autoreconf} runs @command{autoconf}, @command{autoheader},
1581 @command{aclocal}, @command{automake}, @command{libtoolize}, and
1582 @command{autopoint} (when appropriate) repeatedly to update the
1583 @acronym{GNU} Build System in the specified directories and their
1584 subdirectories (@pxref{Subdirectories}).  By default, it only remakes
1585 those files that are older than their sources.  The environment variables
1586 @env{AUTOCONF}, @env{AUTOHEADER}, @env{AUTOMAKE}, @env{ACLOCAL},
1587 @env{AUTOPOINT}, @env{LIBTOOLIZE}, @env{M4}, and @env{MAKE} may be used
1588 to override the invocation of the respective tools.
1590 If you install a new version of some tool, you can make
1591 @command{autoreconf} remake @emph{all} of the files by giving it the
1592 @option{--force} option.
1594 @xref{Automatic Remaking}, for Make rules to automatically
1595 rebuild @command{configure} scripts when their source files change.  That
1596 method handles the timestamps of configuration header templates
1597 properly, but does not pass @option{--autoconf-dir=@var{dir}} or
1598 @option{--localdir=@var{dir}}.
1600 @cindex Gettext
1601 @cindex @command{autopoint}
1602 Gettext supplies the @command{autopoint} command to add translation
1603 infrastructure to a source package.  If you use @command{autopoint},
1604 your @file{configure.ac} should invoke both @code{AM_GNU_GETTEXT} and
1605 @code{AM_GNU_GETTEXT_VERSION(@var{gettext-version})}.  @xref{autopoint
1606 Invocation, , Invoking the @code{autopoint} Program, gettext,
1607 @acronym{GNU} @code{gettext} utilities}, for further details.
1609 @noindent
1610 @command{autoreconf} accepts the following options:
1612 @table @option
1613 @item --help
1614 @itemx -h
1615 Print a summary of the command line options and exit.
1617 @item --version
1618 @itemx -V
1619 Print the version number of Autoconf and exit.
1621 @item --verbose
1622 @itemx -V
1623 Print the name of each directory @command{autoreconf} examines and the
1624 commands it runs.  If given two or more times, pass @option{--verbose}
1625 to subordinate tools that support it.
1627 @item --debug
1628 @itemx -d
1629 Don't remove the temporary files.
1631 @item --force
1632 @itemx -f
1633 Remake even @file{configure} scripts and configuration headers that are
1634 newer than their input files (@file{configure.ac} and, if present,
1635 @file{aclocal.m4}).
1637 @item --install
1638 @itemx -i
1639 Install the missing auxiliary files in the package.  By default, files
1640 are copied; this can be changed with @option{--symlink}.
1642 If deemed appropriate, this option triggers calls to
1643 @samp{automake --add-missing},
1644 @samp{libtoolize}, @samp{autopoint}, etc.
1646 @item --no-recursive
1647 Do not rebuild files in subdirectories to configure (see @ref{Subdirectories},
1648 macro @code{AC_CONFIG_SUBDIRS}).
1650 @item --symlink
1651 @itemx -s
1652 When used with @option{--install}, install symbolic links to the missing
1653 auxiliary files instead of copying them.
1655 @item --make
1656 @itemx -m
1657 When the directories were configured, update the configuration by
1658 running @samp{./config.status --recheck && ./config.status}, and then
1659 run @samp{make}.
1661 @item --include=@var{dir}
1662 @itemx -I @var{dir}
1663 Append @var{dir} to the include path.  Multiple invocations accumulate.
1664 Passed on to @command{autoconf} and @command{autoheader} internally.
1666 @item --prepend-include=@var{dir}
1667 @itemx -B @var{dir}
1668 Prepend @var{dir} to the include path.  Multiple invocations accumulate.
1669 Passed on to @command{autoconf} and @command{autoheader} internally.
1671 @item --warnings=@var{category}
1672 @itemx -W @var{category}
1673 @evindex WARNINGS
1674 Report the warnings related to @var{category} (which can actually be a
1675 comma separated list).
1677 @table @samp
1678 @item cross
1679 related to cross compilation issues.
1681 @item obsolete
1682 report the uses of obsolete constructs.
1684 @item portability
1685 portability issues
1687 @item syntax
1688 dubious syntactic constructs.
1690 @item all
1691 report all the warnings
1693 @item none
1694 report none
1696 @item error
1697 treats warnings as errors
1699 @item no-@var{category}
1700 disable warnings falling into @var{category}
1701 @end table
1703 Warnings about @samp{syntax} are enabled by default, and the environment
1704 variable @env{WARNINGS}, a comma separated list of categories, is
1705 honored as well.  Passing @option{-W @var{category}} actually behaves as if
1706 you had passed @option{--warnings syntax,$WARNINGS,@var{category}}.  If
1707 you want to disable the defaults and @env{WARNINGS}, but (for example)
1708 enable the warnings about obsolete constructs, you would use @option{-W
1709 none,obsolete}.
1710 @end table
1712 If you want @command{autoreconf} to pass flags that are not listed here
1713 on to @command{aclocal}, set @code{ACLOCAL_AMFLAGS} in your @file{Makefile.am}.
1714 Due to a limitation in the Autoconf implementation these flags currently
1715 must be set on a single line in @file{Makefile.am}, without any
1716 backslash-newlines.
1718 @c ========================================= Initialization and Output Files.
1720 @node Setup
1721 @chapter Initialization and Output Files
1723 Autoconf-generated @command{configure} scripts need some information about
1724 how to initialize, such as how to find the package's source files and
1725 about the output files to produce.  The following sections describe the
1726 initialization and the creation of output files.
1728 @menu
1729 * Initializing configure::      Option processing etc.
1730 * Versioning::                  Dealing with Autoconf versions
1731 * Notices::                     Copyright, version numbers in @command{configure}
1732 * Input::                       Where Autoconf should find files
1733 * Output::                      Outputting results from the configuration
1734 * Configuration Actions::       Preparing the output based on results
1735 * Configuration Files::         Creating output files
1736 * Makefile Substitutions::      Using output variables in makefiles
1737 * Configuration Headers::       Creating a configuration header file
1738 * Configuration Commands::      Running arbitrary instantiation commands
1739 * Configuration Links::         Links depending on the configuration
1740 * Subdirectories::              Configuring independent packages together
1741 * Default Prefix::              Changing the default installation prefix
1742 @end menu
1744 @node Initializing configure
1745 @section Initializing @command{configure}
1747 Every @command{configure} script must call @code{AC_INIT} before doing
1748 anything else.  The only other required macro is @code{AC_OUTPUT}
1749 (@pxref{Output}).
1751 @anchor{AC_INIT}
1752 @defmac AC_INIT (@var{package}, @var{version}, @ovar{bug-report}, @
1753   @ovar{tarname})
1754 @acindex{INIT}
1755 Process any command-line arguments and perform various initializations
1756 and verifications.
1758 Set the name of the @var{package} and its @var{version}.  These are
1759 typically used in @option{--version} support, including that of
1760 @command{configure}.  The optional argument @var{bug-report} should be
1761 the email to which users should send bug reports.  The package
1762 @var{tarname} differs from @var{package}: the latter designates the full
1763 package name (e.g., @samp{GNU Autoconf}), while the former is meant for
1764 distribution tar ball names (e.g., @samp{autoconf}).  It defaults to
1765 @var{package} with @samp{GNU } stripped, lower-cased, and all characters
1766 other than alphanumerics and underscores are changed to @samp{-}.
1768 It is preferable that the arguments of @code{AC_INIT} be static, i.e.,
1769 there should not be any shell computation, but they can be computed by
1772 The following M4 macros (e.g., @code{AC_PACKAGE_NAME}), output variables
1773 (e.g., @code{PACKAGE_NAME}), and preprocessor symbols (e.g.,
1774 @code{PACKAGE_NAME}), are defined by @code{AC_INIT}:
1776 @table @asis
1777 @item @code{AC_PACKAGE_NAME}, @code{PACKAGE_NAME}
1778 @acindex{PACKAGE_NAME}
1779 @ovindex PACKAGE_NAME
1780 @cvindex PACKAGE_NAME
1781 Exactly @var{package}.
1783 @item @code{AC_PACKAGE_TARNAME}, @code{PACKAGE_TARNAME}
1784 @acindex{PACKAGE_TARNAME}
1785 @ovindex PACKAGE_TARNAME
1786 @cvindex PACKAGE_TARNAME
1787 Exactly @var{tarname}.
1789 @item @code{AC_PACKAGE_VERSION}, @code{PACKAGE_VERSION}
1790 @acindex{PACKAGE_VERSION}
1791 @ovindex PACKAGE_VERSION
1792 @cvindex PACKAGE_VERSION
1793 Exactly @var{version}.
1795 @item @code{AC_PACKAGE_STRING}, @code{PACKAGE_STRING}
1796 @acindex{PACKAGE_STRING}
1797 @ovindex PACKAGE_STRING
1798 @cvindex PACKAGE_STRING
1799 Exactly @samp{@var{package} @var{version}}.
1801 @item @code{AC_PACKAGE_BUGREPORT}, @code{PACKAGE_BUGREPORT}
1802 @acindex{PACKAGE_BUGREPORT}
1803 @ovindex PACKAGE_BUGREPORT
1804 @cvindex PACKAGE_BUGREPORT
1805 Exactly @var{bug-report}.
1806 @end table
1807 @end defmac
1809 If your @command{configure} script does its own option processing, it
1810 should inspect @samp{$@@} or @samp{$*} immediately after calling
1811 @code{AC_INIT}, because other Autoconf macros liberally use the
1812 @command{set} command to process strings, and this has the side effect
1813 of updating @samp{$@@} and @samp{$*}.  However, we suggest that you use
1814 standard macros like @code{AC_ARG_ENABLE} instead of attempting to
1815 implement your own option processing.  @xref{Site Configuration}.
1817 @node Versioning
1818 @section Dealing with Autoconf versions
1819 @cindex Autoconf version
1820 @cindex version, Autoconf
1822 The following optional macros can be used to help choose the minimum
1823 version of Autoconf that can successfully compile a given
1824 @file{configure.ac}.
1826 @defmac AC_PREREQ (@var{version})
1827 @acindex{PREREQ}
1828 @cindex Version
1829 Ensure that a recent enough version of Autoconf is being used.  If the
1830 version of Autoconf being used to create @command{configure} is
1831 earlier than @var{version}, print an error message to the standard
1832 error output and exit with failure (exit status is 63).  For example:
1834 @example
1835 AC_PREREQ([@value{VERSION}])
1836 @end example
1838 This macro is the only macro that may be used before @code{AC_INIT}, but
1839 for consistency, you are invited not to do so.
1840 @end defmac
1842 @defmac AC_AUTOCONF_VERSION
1843 @acindex{AUTOCONF_VERSION}
1844 This macro was introduced in Autoconf 2.62.  It identifies the version
1845 of Autoconf that is currently parsing the input file, in a format
1846 suitable for @code{m4_version_compare} (@pxref{m4_version_compare}); in
1847 other words, for this release of Autoconf, its value is
1848 @samp{@value{VERSION}}.  One potential use of this macro is for writing
1849 conditional fallbacks based on when a feature was added to Autoconf,
1850 rather than using @code{AC_PREREQ} to require the newer version of
1851 Autoconf.  However, remember that the Autoconf philosophy favors feature
1852 checks over version checks.
1854 You should not expand this macro directly; use
1855 @samp{m4_defn([AC_AUTOCONF_VERSION])} instead.  This is because some
1856 users might
1857 have a beta version of Autoconf installed, with arbitrary letters
1858 included in its version string.  This means it is possible for the
1859 version string to contain the name of a defined macro, such that
1860 expanding @code{AC_AUTOCONF_VERSION} would trigger the expansion of that
1861 macro during rescanning, and change the version string to be different
1862 than what you intended to check.
1863 @end defmac
1865 @node Notices
1866 @section Notices in @command{configure}
1867 @cindex Notices in @command{configure}
1869 The following macros manage version numbers for @command{configure}
1870 scripts.  Using them is optional.
1872 @defmac AC_COPYRIGHT (@var{copyright-notice})
1873 @acindex{COPYRIGHT}
1874 @cindex Copyright Notice
1875 State that, in addition to the Free Software Foundation's copyright on
1876 the Autoconf macros, parts of your @command{configure} are covered by the
1877 @var{copyright-notice}.
1879 The @var{copyright-notice} shows up in both the head of
1880 @command{configure} and in @samp{configure --version}.
1881 @end defmac
1884 @defmac AC_REVISION (@var{revision-info})
1885 @acindex{REVISION}
1886 @cindex Revision
1887 Copy revision stamp @var{revision-info} into the @command{configure}
1888 script, with any dollar signs or double-quotes removed.  This macro lets
1889 you put a revision stamp from @file{configure.ac} into @command{configure}
1890 without @acronym{RCS} or @acronym{CVS} changing it when you check in
1891 @command{configure}.  That way, you can determine easily which revision of
1892 @file{configure.ac} a particular @command{configure} corresponds to.
1894 For example, this line in @file{configure.ac}:
1896 @c The @w prevents RCS from changing the example in the manual.
1897 @example
1898 AC_REVISION([@w{$}Revision: 1.30 $])
1899 @end example
1901 @noindent
1902 produces this in @command{configure}:
1904 @example
1905 #!/bin/sh
1906 # From configure.ac Revision: 1.30
1907 @end example
1908 @end defmac
1911 @node Input
1912 @section Finding @command{configure} Input
1914 @anchor{AC_CONFIG_SRCDIR}
1915 @defmac AC_CONFIG_SRCDIR (@var{unique-file-in-source-dir})
1916 @acindex{CONFIG_SRCDIR}
1917 @var{unique-file-in-source-dir} is some file that is in the package's
1918 source directory; @command{configure} checks for this file's existence to
1919 make sure that the directory that it is told contains the source code in
1920 fact does.  Occasionally people accidentally specify the wrong directory
1921 with @option{--srcdir}; this is a safety check.  @xref{configure
1922 Invocation}, for more information.
1923 @end defmac
1926 @c FIXME: Remove definitively once --install explained.
1928 @c Small packages may store all their macros in @code{aclocal.m4}.  As the
1929 @c set of macros grows, or for maintenance reasons, a maintainer may prefer
1930 @c to split the macros in several files.  In this case, Autoconf must be
1931 @c told which files to load, and in which order.
1933 @c @defmac AC_INCLUDE (@var{file}@dots{})
1934 @c @acindex{INCLUDE}
1935 @c @c FIXME: There is no longer shell globbing.
1936 @c Read the macro definitions that appear in the listed files.  A list of
1937 @c space-separated file names or shell globbing patterns is expected.  The
1938 @c files are read in the order they're listed.
1940 @c Because the order of definition of macros is important (only the last
1941 @c definition of a macro is used), beware that it is @code{AC_INIT} that
1942 @c loads @file{acsite.m4} and @file{aclocal.m4}.  Note that
1943 @c @code{AC_INCLUDE}ing a file before @code{AC_INIT} or within
1944 @c @file{aclocal.m4} is different from doing so after @code{AC_INIT}: in
1945 @c the latter case, non-macro lines from included files may end up in the
1946 @c @file{configure} script, whereas in the former case, they'd be discarded
1947 @c just like any text that appear before @code{AC_INIT}.
1948 @c @end defmac
1950 Packages that do manual configuration or use the @command{install} program
1951 might need to tell @command{configure} where to find some other shell
1952 scripts by calling @code{AC_CONFIG_AUX_DIR}, though the default places
1953 it looks are correct for most cases.
1955 @defmac AC_CONFIG_AUX_DIR (@var{dir})
1956 @acindex{CONFIG_AUX_DIR}
1957 Use the auxiliary build tools (e.g., @file{install-sh},
1958 @file{config.sub}, @file{config.guess}, Cygnus @command{configure},
1959 Automake and Libtool scripts, etc.)@: that are in directory @var{dir}.
1960 These are auxiliary files used in configuration.  @var{dir} can be
1961 either absolute or relative to @file{@var{srcdir}}.  The default is
1962 @file{@var{srcdir}} or @file{@var{srcdir}/..} or
1963 @file{@var{srcdir}/../..}, whichever is the first that contains
1964 @file{install-sh}.  The other files are not checked for, so that using
1965 @code{AC_PROG_INSTALL} does not automatically require distributing the
1966 other auxiliary files.  It checks for @file{install.sh} also, but that
1967 name is obsolete because some @command{make} have a rule that creates
1968 @file{install} from it if there is no makefile.
1970 The auxiliary directory is commonly named @file{build-aux}.
1971 If you need portability to @acronym{DOS} variants, do not name the
1972 auxiliary directory @file{aux}.  @xref{File System Conventions}.
1973 @end defmac
1975 @defmac AC_REQUIRE_AUX_FILE (@var{file})
1976 @acindex{REQUIRE_AUX_FILE}
1977 Declares that @var{file} is expected in the directory defined above.  In
1978 Autoconf proper, this macro does nothing: its sole purpose is to be
1979 traced by third-party tools to produce a list of expected auxiliary
1980 files.  For instance it is called by macros like @code{AC_PROG_INSTALL}
1981 (@pxref{Particular Programs}) or @code{AC_CANONICAL_BUILD}
1982 (@pxref{Canonicalizing}) to register the auxiliary files they need.
1983 @end defmac
1985 Similarly, packages that use @command{aclocal} should declare where
1986 local macros can be found using @code{AC_CONFIG_MACRO_DIR}.
1988 @defmac AC_CONFIG_MACRO_DIR (@var{dir})
1989 @acindex{CONFIG_MACRO_DIR}
1990 Specify @var{dir} as the location of additional local Autoconf macros.
1991 This macro is intended for use by future versions of commands like
1992 @command{autoreconf} that trace macro calls.  It should be called
1993 directly from @file{configure.ac} so that tools that install macros for
1994 @command{aclocal} can find the macros' declarations.
1996 Note that if you use @command{aclocal} from Automake to generate
1997 @file{aclocal.m4}, you must also set @code{ACLOCAL_AMFLAGS = -I
1998 @var{dir}} in your top-level @file{Makefile.am}.  Due to a limitation in
1999 the Autoconf implementation of @command{autoreconf}, these include
2000 directives currently must be set on a single line in @file{Makefile.am},
2001 without any backslash-newlines.
2002 @end defmac
2005 @node Output
2006 @section Outputting Files
2007 @cindex Outputting files
2009 Every Autoconf script, e.g., @file{configure.ac}, should finish by
2010 calling @code{AC_OUTPUT}.  That is the macro that generates and runs
2011 @file{config.status}, which in turn creates the makefiles and any
2012 other files resulting from configuration.  This is the only required
2013 macro besides @code{AC_INIT} (@pxref{Input}).
2015 @anchor{AC_OUTPUT}
2016 @defmac AC_OUTPUT
2017 @acindex{OUTPUT}
2018 @cindex Instantiation
2019 Generate @file{config.status} and launch it.  Call this macro once, at
2020 the end of @file{configure.ac}.
2022 @file{config.status} performs all the configuration actions: all the
2023 output files (see @ref{Configuration Files}, macro
2024 @code{AC_CONFIG_FILES}), header files (see @ref{Configuration Headers},
2025 macro @code{AC_CONFIG_HEADERS}), commands (see @ref{Configuration
2026 Commands}, macro @code{AC_CONFIG_COMMANDS}), links (see
2027 @ref{Configuration Links}, macro @code{AC_CONFIG_LINKS}), subdirectories
2028 to configure (see @ref{Subdirectories}, macro @code{AC_CONFIG_SUBDIRS})
2029 are honored.
2031 The location of your @code{AC_OUTPUT} invocation is the exact point
2032 where configuration actions are taken: any code afterwards is
2033 executed by @command{configure} once @command{config.status} was run.  If
2034 you want to bind actions to @command{config.status} itself
2035 (independently of whether @command{configure} is being run), see
2036 @ref{Configuration Commands, , Running Arbitrary Configuration
2037 Commands}.
2038 @end defmac
2040 Historically, the usage of @code{AC_OUTPUT} was somewhat different.
2041 @xref{Obsolete Macros}, for a description of the arguments that
2042 @code{AC_OUTPUT} used to support.
2045 If you run @command{make} in subdirectories, you should run it using the
2046 @command{make} variable @code{MAKE}.  Most versions of @command{make} set
2047 @code{MAKE} to the name of the @command{make} program plus any options it
2048 was given.  (But many do not include in it the values of any variables
2049 set on the command line, so those are not passed on automatically.)
2050 Some old versions of @command{make} do not set this variable.  The
2051 following macro allows you to use it even with those versions.
2053 @anchor{AC_PROG_MAKE_SET}
2054 @defmac AC_PROG_MAKE_SET
2055 @acindex{PROG_MAKE_SET}
2056 @ovindex SET_MAKE
2057 If the Make command, @code{$MAKE} if set or else @samp{make}, predefines
2058 @code{$(MAKE)}, define output variable @code{SET_MAKE} to be empty.
2059 Otherwise, define @code{SET_MAKE} to a macro definition that sets
2060 @code{$(MAKE)}, such as @samp{MAKE=make}.  Calls @code{AC_SUBST} for
2061 @code{SET_MAKE}.
2062 @end defmac
2064 If you use this macro, place a line like this in each @file{Makefile.in}
2065 that runs @command{MAKE} on other directories:
2067 @example
2068 @@SET_MAKE@@
2069 @end example
2073 @node Configuration Actions
2074 @section Performing Configuration Actions
2075 @cindex Configuration actions
2077 @file{configure} is designed so that it appears to do everything itself,
2078 but there is actually a hidden slave: @file{config.status}.
2079 @file{configure} is in charge of examining your system, but it is
2080 @file{config.status} that actually takes the proper actions based on the
2081 results of @file{configure}.  The most typical task of
2082 @file{config.status} is to @emph{instantiate} files.
2084 This section describes the common behavior of the four standard
2085 instantiating macros: @code{AC_CONFIG_FILES}, @code{AC_CONFIG_HEADERS},
2086 @code{AC_CONFIG_COMMANDS} and @code{AC_CONFIG_LINKS}.  They all
2087 have this prototype:
2089 @c FIXME: Can't use @ovar here, Texinfo 4.0 goes lunatic and emits something
2090 @c awful.
2091 @example
2092 AC_CONFIG_FOOS(@var{tag}@dots{}, [@var{commands}], [@var{init-cmds}])
2093 @end example
2095 @noindent
2096 where the arguments are:
2098 @table @var
2099 @item tag@dots{}
2100 A blank-or-newline-separated list of tags, which are typically the names of
2101 the files to instantiate.
2103 You are encouraged to use literals as @var{tags}.  In particular, you
2104 should avoid
2106 @example
2107 @dots{} && my_foos="$my_foos fooo"
2108 @dots{} && my_foos="$my_foos foooo"
2109 AC_CONFIG_FOOS([$my_foos])
2110 @end example
2112 @noindent
2113 and use this instead:
2115 @example
2116 @dots{} && AC_CONFIG_FOOS([fooo])
2117 @dots{} && AC_CONFIG_FOOS([foooo])
2118 @end example
2120 The macros @code{AC_CONFIG_FILES} and @code{AC_CONFIG_HEADERS} use
2121 special @var{tag} values: they may have the form @samp{@var{output}} or
2122 @samp{@var{output}:@var{inputs}}.  The file @var{output} is instantiated
2123 from its templates, @var{inputs} (defaulting to @samp{@var{output}.in}).
2125 @samp{AC_CONFIG_FILES([Makefile:boiler/top.mk:boiler/bot.mk)]},
2126 for example, asks for
2127 the creation of the file @file{Makefile} that contains the expansion of the
2128 output variables in the concatenation of @file{boiler/top.mk} and
2129 @file{boiler/bot.mk}.
2131 The special value @samp{-} might be used to denote the standard output
2132 when used in @var{output}, or the standard input when used in the
2133 @var{inputs}.  You most probably don't need to use this in
2134 @file{configure.ac}, but it is convenient when using the command line
2135 interface of @file{./config.status}, see @ref{config.status Invocation},
2136 for more details.
2138 The @var{inputs} may be absolute or relative file names.  In the latter
2139 case they are first looked for in the build tree, and then in the source
2140 tree.
2142 @item commands
2143 Shell commands output literally into @file{config.status}, and
2144 associated with a tag that the user can use to tell @file{config.status}
2145 which the commands to run.  The commands are run each time a @var{tag}
2146 request is given to @file{config.status}, typically each time the file
2147 @file{@var{tag}} is created.
2149 The variables set during the execution of @command{configure} are
2150 @emph{not} available here: you first need to set them via the
2151 @var{init-cmds}.  Nonetheless the following variables are precomputed:
2153 @table @code
2154 @item srcdir
2155 The name of the top source directory, assuming that the working
2156 directory is the top build directory.  This
2157 is what the @command{configure} option @option{--srcdir} sets.
2159 @item ac_top_srcdir
2160 The name of the top source directory, assuming that the working
2161 directory is the current build directory.
2164 @item ac_top_build_prefix
2165 The name of the top build directory, assuming that the working
2166 directory is the current build directory.
2167 It can be empty, or else ends with a slash, so that you may concatenate
2170 @item ac_srcdir
2171 The name of the corresponding source directory, assuming that the
2172 working directory is the current build directory.
2173 @end table
2175 @noindent
2176 The @dfn{current} directory refers to the directory (or
2177 pseudo-directory) containing the input part of @var{tags}.  For
2178 instance, running
2180 @example
2181 AC_CONFIG_COMMANDS([deep/dir/out:in/in.in], [@dots{}], [@dots{}])
2182 @end example
2184 @noindent
2185  with @option{--srcdir=../package} produces the following values:
2187 @example
2188 # Argument of --srcdir
2189 srcdir='../package'
2190 # Reversing deep/dir
2191 ac_top_build_prefix='../../'
2192 # Concatenation of $ac_top_build_prefix and srcdir
2193 ac_top_srcdir='../../../package'
2194 # Concatenation of $ac_top_srcdir and deep/dir
2195 ac_srcdir='../../../package/deep/dir'
2196 @end example
2198 @noindent
2199 independently of @samp{in/in.in}.
2201 @item init-cmds
2202 Shell commands output @emph{unquoted} near the beginning of
2203 @file{config.status}, and executed each time @file{config.status} runs
2204 (regardless of the tag).  Because they are unquoted, for example,
2205 @samp{$var} is output as the value of @code{var}.  @var{init-cmds}
2206 is typically used by @file{configure} to give @file{config.status} some
2207 variables it needs to run the @var{commands}.
2209 You should be extremely cautious in your variable names: all the
2210 @var{init-cmds} share the same name space and may overwrite each other
2211 in unpredictable ways.  Sorry@enddots{}
2212 @end table
2214 All these macros can be called multiple times, with different
2215 @var{tag} values, of course!
2218 @node Configuration Files
2219 @section Creating Configuration Files
2220 @cindex Creating configuration files
2221 @cindex Configuration file creation
2223 Be sure to read the previous section, @ref{Configuration Actions}.
2225 @anchor{AC_CONFIG_FILES}
2226 @defmac AC_CONFIG_FILES (@var{file}@dots{}, @ovar{cmds}, @ovar{init-cmds})
2227 @acindex{CONFIG_FILES}
2228 Make @code{AC_OUTPUT} create each @file{@var{file}} by copying an input
2229 file (by default @file{@var{file}.in}), substituting the output variable
2230 values.
2231 @c Before we used to have this feature, which was later rejected
2232 @c because it complicates the writing of makefiles:
2233 @c If the file would be unchanged, it is left untouched, to preserve
2234 @c timestamp.
2235 This macro is one of the instantiating macros; see @ref{Configuration
2236 Actions}.  @xref{Makefile Substitutions}, for more information on using
2237 output variables.  @xref{Setting Output Variables}, for more information
2238 on creating them.  This macro creates the directory that the file is in
2239 if it doesn't exist.  Usually, makefiles are created this way,
2240 but other files, such as @file{.gdbinit}, can be specified as well.
2242 Typical calls to @code{AC_CONFIG_FILES} look like this:
2244 @example
2245 AC_CONFIG_FILES([Makefile src/Makefile man/Makefile X/Imakefile])
2246 AC_CONFIG_FILES([autoconf], [chmod +x autoconf])
2247 @end example
2249 You can override an input file name by appending to @var{file} a
2250 colon-separated list of input files.  Examples:
2252 @example
2253 AC_CONFIG_FILES([Makefile:boiler/top.mk:boiler/bot.mk]
2254                 [lib/Makefile:boiler/lib.mk])
2255 @end example
2257 @noindent
2258 Doing this allows you to keep your file names acceptable to
2259 @acronym{DOS} variants, or
2260 to prepend and/or append boilerplate to the file.
2261 @end defmac
2265 @node Makefile Substitutions
2266 @section Substitutions in Makefiles
2267 @cindex Substitutions in makefiles
2268 @cindex Makefile substitutions
2270 Each subdirectory in a distribution that contains something to be
2271 compiled or installed should come with a file @file{Makefile.in}, from
2272 which @command{configure} creates a file @file{Makefile} in that directory.
2273 To create @file{Makefile}, @command{configure} performs a simple variable
2274 substitution, replacing occurrences of @samp{@@@var{variable}@@} in
2275 @file{Makefile.in} with the value that @command{configure} has determined
2276 for that variable.  Variables that are substituted into output files in
2277 this way are called @dfn{output variables}.  They are ordinary shell
2278 variables that are set in @command{configure}.  To make @command{configure}
2279 substitute a particular variable into the output files, the macro
2280 @code{AC_SUBST} must be called with that variable name as an argument.
2281 Any occurrences of @samp{@@@var{variable}@@} for other variables are
2282 left unchanged.  @xref{Setting Output Variables}, for more information
2283 on creating output variables with @code{AC_SUBST}.
2285 A software package that uses a @command{configure} script should be
2286 distributed with a file @file{Makefile.in}, but no makefile; that
2287 way, the user has to properly configure the package for the local system
2288 before compiling it.
2290 @xref{Makefile Conventions, , Makefile Conventions, standards, The
2291 @acronym{GNU} Coding Standards}, for more information on what to put in
2292 makefiles.
2294 @menu
2295 * Preset Output Variables::     Output variables that are always set
2296 * Installation Directory Variables::  Other preset output variables
2297 * Changed Directory Variables:: Warnings about @file{datarootdir}
2298 * Build Directories::           Supporting multiple concurrent compiles
2299 * Automatic Remaking::          Makefile rules for configuring
2300 @end menu
2302 @node Preset Output Variables
2303 @subsection Preset Output Variables
2304 @cindex Output variables
2306 Some output variables are preset by the Autoconf macros.  Some of the
2307 Autoconf macros set additional output variables, which are mentioned in
2308 the descriptions for those macros.  @xref{Output Variable Index}, for a
2309 complete list of output variables.  @xref{Installation Directory
2310 Variables}, for the list of the preset ones related to installation
2311 directories.  Below are listed the other preset ones.  They all are
2312 precious variables (@pxref{Setting Output Variables},
2313 @code{AC_ARG_VAR}).
2315 @c Just say no to ASCII sorting!  We're humans, not computers.
2316 @c These variables are listed as they would be in a dictionary:
2317 @c actor
2318 @c Actress
2319 @c actress
2321 @defvar CFLAGS
2322 @ovindex CFLAGS
2323 Debugging and optimization options for the C compiler.  If it is not set
2324 in the environment when @command{configure} runs, the default value is set
2325 when you call @code{AC_PROG_CC} (or empty if you don't).  @command{configure}
2326 uses this variable when compiling or linking programs to test for C features.
2328 If a compiler option affects only the behavior of the preprocessor
2329 (e.g., @option{-D @var{name}}), it should be put into @code{CPPFLAGS}
2330 instead.  If it affects only the linker (e.g., @option{-L
2331 @var{directory}}), it should be put into @code{LDFLAGS} instead.  If it
2332 affects only the compiler proper, @code{CFLAGS} is the natural home for
2333 it.  If an option affects multiple phases of the compiler, though,
2334 matters get tricky.  One approach to put such options directly into
2335 @code{CC}, e.g., @code{CC='gcc -m64'}.  Another is to put them into both
2336 @code{CPPFLAGS} and @code{LDFLAGS}, but not into @code{CFLAGS}.
2338 @end defvar
2340 @defvar configure_input
2341 @ovindex configure_input
2342 A comment saying that the file was generated automatically by
2343 @command{configure} and giving the name of the input file.
2344 @code{AC_OUTPUT} adds a comment line containing this variable to the top
2345 of every makefile it creates.  For other files, you should
2346 reference this variable in a comment at the top of each input file.  For
2347 example, an input shell script should begin like this:
2349 @example
2350 #!/bin/sh
2351 # @@configure_input@@
2352 @end example
2354 @noindent
2355 The presence of that line also reminds people editing the file that it
2356 needs to be processed by @command{configure} in order to be used.
2357 @end defvar
2359 @defvar CPPFLAGS
2360 @ovindex CPPFLAGS
2361 Preprocessor options for the C, C++, and Objective C preprocessors and
2362 compilers.  If
2363 it is not set in the environment when @command{configure} runs, the default
2364 value is empty.  @command{configure} uses this variable when preprocessing
2365 or compiling programs to test for C, C++, and Objective C features.
2367 This variable's contents should contain options like @option{-I},
2368 @option{-D}, and @option{-U} that affect only the behavior of the
2369 preprocessor.  Please see the explanation of @code{CFLAGS} for what you
2370 can do if an option affects other phases of the compiler as well.
2372 Currently, @command{configure} always links as part of a single
2373 invocation of the compiler that also preprocesses and compiles, so it
2374 uses this variable also when linking programs.  However, it is unwise to
2375 depend on this behavior because the @acronym{GNU} coding standards do
2376 not require it and many packages do not use @code{CPPFLAGS} when linking
2377 programs.
2379 @xref{Special Chars in Variables}, for limitations that @code{CPPFLAGS}
2380 might run into.
2381 @end defvar
2383 @defvar CXXFLAGS
2384 @ovindex CXXFLAGS
2385 Debugging and optimization options for the C++ compiler.  It acts like
2386 @code{CFLAGS}, but for C++ instead of C.
2387 @end defvar
2389 @defvar DEFS
2390 @ovindex DEFS
2391 @option{-D} options to pass to the C compiler.  If @code{AC_CONFIG_HEADERS}
2392 is called, @command{configure} replaces @samp{@@DEFS@@} with
2393 @option{-DHAVE_CONFIG_H} instead (@pxref{Configuration Headers}).  This
2394 variable is not defined while @command{configure} is performing its tests,
2395 only when creating the output files.  @xref{Setting Output Variables}, for
2396 how to check the results of previous tests.
2397 @end defvar
2399 @defvar ECHO_C
2400 @defvarx ECHO_N
2401 @defvarx ECHO_T
2402 @ovindex ECHO_C
2403 @ovindex ECHO_N
2404 @ovindex ECHO_T
2405 How does one suppress the trailing newline from @command{echo} for
2406 question-answer message pairs?  These variables provide a way:
2408 @example
2409 echo $ECHO_N "And the winner is... $ECHO_C"
2410 sleep 100000000000
2411 echo "$@{ECHO_T@}dead."
2412 @end example
2414 @noindent
2415 Some old and uncommon @command{echo} implementations offer no means to
2416 achieve this, in which case @code{ECHO_T} is set to tab.  You might not
2417 want to use it.
2418 @end defvar
2420 @defvar ERLCFLAGS
2421 @ovindex ERLCFLAGS
2422 Debugging and optimization options for the Erlang compiler.  If it is not set
2423 in the environment when @command{configure} runs, the default value is empty.
2424 @command{configure} uses this variable when compiling
2425 programs to test for Erlang features.
2426 @end defvar
2428 @defvar FCFLAGS
2429 @ovindex FCFLAGS
2430 Debugging and optimization options for the Fortran compiler.  If it
2431 is not set in the environment when @command{configure} runs, the default
2432 value is set when you call @code{AC_PROG_FC} (or empty if you don't).
2433 @command{configure} uses this variable when compiling or linking
2434 programs to test for Fortran features.
2435 @end defvar
2437 @defvar FFLAGS
2438 @ovindex FFLAGS
2439 Debugging and optimization options for the Fortran 77 compiler.  If it
2440 is not set in the environment when @command{configure} runs, the default
2441 value is set when you call @code{AC_PROG_F77} (or empty if you don't).
2442 @command{configure} uses this variable when compiling or linking
2443 programs to test for Fortran 77 features.
2444 @end defvar
2446 @defvar LDFLAGS
2447 @ovindex LDFLAGS
2448 Options for the linker.  If it is not set
2449 in the environment when @command{configure} runs, the default value is empty.
2450 @command{configure} uses this variable when linking programs to test for
2451 C, C++, Objective C, and Fortran features.
2453 This variable's contents should contain options like @option{-s} and
2454 @option{-L} that affect only the behavior of the linker.  Please see the
2455 explanation of @code{CFLAGS} for what you can do if an option also
2456 affects other phases of the compiler.
2458 Don't use this variable to pass library names
2459 (@option{-l}) to the linker; use @code{LIBS} instead.
2460 @end defvar
2462 @defvar LIBS
2463 @ovindex LIBS
2464 @option{-l} options to pass to the linker.  The default value is empty,
2465 but some Autoconf macros may prepend extra libraries to this variable if
2466 those libraries are found and provide necessary functions, see
2467 @ref{Libraries}.  @command{configure} uses this variable when linking
2468 programs to test for C, C++, and Fortran features.
2469 @end defvar
2471 @defvar OBJCFLAGS
2472 @ovindex OBJCFLAGS
2473 Debugging and optimization options for the Objective C compiler.  It
2474 acts like @code{CFLAGS}, but for Objective C instead of C.
2475 @end defvar
2477 @defvar builddir
2478 @ovindex builddir
2479 Rigorously equal to @samp{.}.  Added for symmetry only.
2480 @end defvar
2482 @defvar abs_builddir
2483 @ovindex abs_builddir
2484 Absolute name of @code{builddir}.
2485 @end defvar
2487 @defvar top_builddir
2488 @ovindex top_builddir
2489 The relative name of the top level of the current build tree.  In the
2490 top-level directory, this is the same as @code{builddir}.
2491 @end defvar
2493 @defvar top_build_prefix
2494 @ovindex top_build_prefix
2495 The relative name of the top level of the current build tree with final
2496 slash if nonemtpy.  This is the same as @code{top_builddir}, except that
2497 it contains of zero of more runs of @code{../}, so it should not be
2498 appended with a slash for concatenation.  This helps for @command{make}
2499 implementations that otherwise do not treat @file{./file} and @file{file}
2500 as equal in the toplevel build directory.
2501 @end defvar
2503 @defvar abs_top_builddir
2504 @ovindex abs_top_builddir
2505 Absolute name of @code{top_builddir}.
2506 @end defvar
2508 @defvar srcdir
2509 @ovindex srcdir
2510 The name of the directory that contains the source code for
2511 that makefile.
2512 @end defvar
2514 @defvar abs_srcdir
2515 @ovindex abs_srcdir
2516 Absolute name of @code{srcdir}.
2517 @end defvar
2519 @defvar top_srcdir
2520 @ovindex top_srcdir
2521 The name of the top-level source code directory for the
2522 package.  In the top-level directory, this is the same as @code{srcdir}.
2523 @end defvar
2525 @defvar abs_top_srcdir
2526 @ovindex abs_top_srcdir
2527 Absolute name of @code{top_srcdir}.
2528 @end defvar
2530 @node Installation Directory Variables
2531 @subsection Installation Directory Variables
2532 @cindex Installation directories
2533 @cindex Directories, installation
2535 The following variables specify the directories for
2536 package installation, see @ref{Directory Variables, , Variables for
2537 Installation Directories, standards, The @acronym{GNU} Coding
2538 Standards}, for more information.  Each variable corresponds to an
2539 argument of @command{configure}; trailing slashes are stripped so that
2540 expressions such as @samp{$@{prefix@}/lib} expand with only one slash
2541 between directory names.  See the end of this section for
2542 details on when and how to use these variables.
2544 @defvar bindir
2545 @ovindex bindir
2546 The directory for installing executables that users run.
2547 @end defvar
2549 @defvar datadir
2550 @ovindex datadir
2551 The directory for installing idiosyncratic read-only
2552 architecture-independent data.
2553 @end defvar
2555 @defvar datarootdir
2556 @ovindex datarootdir
2557 The root of the directory tree for read-only architecture-independent
2558 data files.
2559 @end defvar
2561 @defvar docdir
2562 @ovindex docdir
2563 The directory for installing documentation files (other than Info and
2564 man).
2565 @end defvar
2567 @defvar dvidir
2568 @ovindex dvidir
2569 The directory for installing documentation files in DVI format.
2570 @end defvar
2572 @defvar exec_prefix
2573 @ovindex exec_prefix
2574 The installation prefix for architecture-dependent files.  By default
2575 it's the same as @var{prefix}.  You should avoid installing anything
2576 directly to @var{exec_prefix}.  However, the default value for
2577 directories containing architecture-dependent files should be relative
2578 to @var{exec_prefix}.
2579 @end defvar
2581 @defvar htmldir
2582 @ovindex htmldir
2583 The directory for installing HTML documentation.
2584 @end defvar
2586 @defvar includedir
2587 @ovindex includedir
2588 The directory for installing C header files.
2589 @end defvar
2591 @defvar infodir
2592 @ovindex infodir
2593 The directory for installing documentation in Info format.
2594 @end defvar
2596 @defvar libdir
2597 @ovindex libdir
2598 The directory for installing object code libraries.
2599 @end defvar
2601 @defvar libexecdir
2602 @ovindex libexecdir
2603 The directory for installing executables that other programs run.
2604 @end defvar
2606 @defvar localedir
2607 @ovindex localedir
2608 The directory for installing locale-dependent but
2609 architecture-independent data, such as message catalogs.  This directory
2610 usually has a subdirectory per locale.
2611 @end defvar
2613 @defvar localstatedir
2614 @ovindex localstatedir
2615 The directory for installing modifiable single-machine data.
2616 @end defvar
2618 @defvar mandir
2619 @ovindex mandir
2620 The top-level directory for installing documentation in man format.
2621 @end defvar
2623 @defvar oldincludedir
2624 @ovindex oldincludedir
2625 The directory for installing C header files for non-@acronym{GCC} compilers.
2626 @end defvar
2628 @defvar pdfdir
2629 @ovindex pdfdir
2630 The directory for installing PDF documentation.
2631 @end defvar
2633 @defvar prefix
2634 @ovindex prefix
2635 The common installation prefix for all files.  If @var{exec_prefix}
2636 is defined to a different value, @var{prefix} is used only for
2637 architecture-independent files.
2638 @end defvar
2640 @defvar psdir
2641 @ovindex psdir
2642 The directory for installing PostScript documentation.
2643 @end defvar
2645 @defvar sbindir
2646 @ovindex sbindir
2647 The directory for installing executables that system
2648 administrators run.
2649 @end defvar
2651 @defvar sharedstatedir
2652 @ovindex sharedstatedir
2653 The directory for installing modifiable architecture-independent data.
2654 @end defvar
2656 @defvar sysconfdir
2657 @ovindex sysconfdir
2658 The directory for installing read-only single-machine data.
2659 @end defvar
2662 Most of these variables have values that rely on @code{prefix} or
2663 @code{exec_prefix}.  It is deliberate that the directory output
2664 variables keep them unexpanded: typically @samp{@@datarootdir@@} is
2665 replaced by @samp{$@{prefix@}/share}, not @samp{/usr/local/share}, and
2666 @samp{@@datadir@@} is replaced by @samp{$@{datarootdir@}}.
2668 This behavior is mandated by the @acronym{GNU} coding standards, so that when
2669 the user runs:
2671 @table @samp
2672 @item make
2673 she can still specify a different prefix from the one specified to
2674 @command{configure}, in which case, if needed, the package should hard
2675 code dependencies corresponding to the make-specified prefix.
2677 @item make install
2678 she can specify a different installation location, in which case the
2679 package @emph{must} still depend on the location which was compiled in
2680 (i.e., never recompile when @samp{make install} is run).  This is an
2681 extremely important feature, as many people may decide to install all
2682 the files of a package grouped together, and then install links from
2683 the final locations to there.
2684 @end table
2686 In order to support these features, it is essential that
2687 @code{datarootdir} remains being defined as @samp{$@{prefix@}/share} to
2688 depend upon the current value of @code{prefix}.
2690 A corollary is that you should not use these variables except in
2691 makefiles.  For instance, instead of trying to evaluate @code{datadir}
2692 in @file{configure} and hard-coding it in makefiles using
2693 e.g., @samp{AC_DEFINE_UNQUOTED([DATADIR], ["$datadir"], [Data directory.])},
2694 you should add
2695 @option{-DDATADIR='$(datadir)'} to your makefile's definition of
2696 @code{CPPFLAGS} (@code{AM_CPPFLAGS} if you are also using Automake).
2698 Similarly, you should not rely on @code{AC_CONFIG_FILES} to replace
2699 @code{datadir} and friends in your shell scripts and other files; instead,
2700 let @command{make} manage their replacement.  For instance Autoconf
2701 ships templates of its shell scripts ending with @samp{.in}, and uses a
2702 makefile snippet similar to the following to build scripts like
2703 @command{autoheader} and @command{autom4te}:
2705 @example
2706 @group
2707 edit = sed \
2708         -e 's|@@datadir[@@]|$(pkgdatadir)|g' \
2709         -e 's|@@prefix[@@]|$(prefix)|g'
2710 @end group
2712 @group
2713 autoheader autom4te: Makefile
2714         rm -f $@@ $@@.tmp
2715         $(edit) '$(srcdir)/$@@.in' >$@@.tmp
2716         chmod +x $@@.tmp
2717         chmod a-w $@@.tmp
2718         mv $@@.tmp $@@
2719 @end group
2721 @group
2722 autoheader: $(srcdir)/autoheader.in
2723 autom4te: $(srcdir)/autom4te.in
2724 @end group
2725 @end example
2727 Some details are noteworthy:
2729 @table @asis
2730 @item @samp{@@datadir[@@]}
2731 The brackets prevent @command{configure} from replacing
2732 @samp{@@datadir@@} in the Sed expression itself.
2733 Brackets are preferable to a backslash here, since
2734 Posix says @samp{\@@} is not portable.
2736 @item @samp{$(pkgdatadir)}
2737 Don't use @samp{@@pkgdatadir@@}!  Use the matching makefile variable
2738 instead.
2740 @item @samp{/}
2741 Don't use @samp{/} in the Sed expressions that replace file names since
2742 most likely the
2743 variables you use, such as @samp{$(pkgdatadir)}, contain @samp{/}.
2744 Use a shell metacharacter instead, such as @samp{|}.
2746 @item special characters
2747 File names, file name components, and the value of @code{VPATH} should
2748 not contain shell metacharacters or white
2749 space.  @xref{Special Chars in Variables}.
2751 @item dependency on @file{Makefile}
2752 Since @code{edit} uses values that depend on the configuration specific
2753 values (@code{prefix}, etc.)@: and not only on @code{VERSION} and so forth,
2754 the output depends on @file{Makefile}, not @file{configure.ac}.
2756 @item @samp{$@@}
2757 The main rule is generic, and uses @samp{$@@} extensively to
2758 avoid the need for multiple copies of the rule.
2760 @item Separated dependencies and single suffix rules
2761 You can't use them!  The above snippet cannot be (portably) rewritten
2764 @example
2765 autoconf autoheader: Makefile
2766 @group
2767 .in:
2768         rm -f $@@ $@@.tmp
2769         $(edit) $< >$@@.tmp
2770         chmod +x $@@.tmp
2771         mv $@@.tmp $@@
2772 @end group
2773 @end example
2775 @xref{Single Suffix Rules}, for details.
2777 @item @samp{$(srcdir)}
2778 Be sure to specify the name of the source directory,
2779 otherwise the package won't support separated builds.
2780 @end table
2782 For the more specific installation of Erlang libraries, the following variables
2783 are defined:
2785 @defvar ERLANG_INSTALL_LIB_DIR
2786 @ovindex ERLANG_INSTALL_LIB_DIR
2787 @acindex{ERLANG_SUBST_INSTALL_LIB_DIR}
2788 The common parent directory of Erlang library installation directories.
2789 This variable is set by calling the @code{AC_ERLANG_SUBST_INSTALL_LIB_DIR}
2790 macro in @file{configure.ac}.
2791 @end defvar
2793 @defvar ERLANG_INSTALL_LIB_DIR_@var{library}
2794 @ovindex ERLANG_INSTALL_LIB_DIR_@var{library}
2795 @acindex{ERLANG_SUBST_INSTALL_LIB_SUBDIR}
2796 The installation directory for Erlang library @var{library}.
2797 This variable is set by calling the
2798 @samp{AC_ERLANG_SUBST_INSTALL_LIB_SUBDIR(@var{library}, @var{version}}
2799 macro in @file{configure.ac}.
2800 @end defvar
2802 @xref{Erlang Libraries}, for details.
2805 @node Changed Directory Variables
2806 @subsection Changed Directory Variables
2807 @cindex @file{datarootdir}
2809 In Autoconf 2.60, the set of directory variables has changed, and the
2810 defaults of some variables have been adjusted
2811 (@pxref{Installation Directory Variables}) to changes in the
2812 @acronym{GNU} Coding Standards.  Notably, @file{datadir}, @file{infodir}, and
2813 @file{mandir} are now expressed in terms of @file{datarootdir}.  If you are
2814 upgrading from an earlier Autoconf version, you may need to adjust your files
2815 to ensure that the directory variables are substituted correctly
2816 (@pxref{Defining Directories}), and that a definition of @file{datarootdir} is
2817 in place.  For example, in a @file{Makefile.in}, adding
2819 @example
2820 datarootdir = @@datarootdir@@
2821 @end example
2823 @noindent
2824 is usually sufficient.  If you use Automake to create @file{Makefile.in},
2825 it will add this for you.
2827 To help with the transition, Autoconf warns about files that seem to use
2828 @code{datarootdir} without defining it.  In some cases, it then expands
2829 the value of @code{$datarootdir} in substitutions of the directory
2830 variables.  The following example shows such a warning:
2832 @example
2833 $ @kbd{cat configure.ac}
2834 AC_INIT
2835 AC_CONFIG_FILES([Makefile])
2836 AC_OUTPUT
2837 $ @kbd{cat Makefile.in}
2838 prefix = @@prefix@@
2839 datadir = @@datadir@@
2840 $ @kbd{autoconf}
2841 $ @kbd{configure}
2842 configure: creating ./config.status
2843 config.status: creating Makefile
2844 config.status: WARNING:
2845                Makefile.in seems to ignore the --datarootdir setting
2846 $ @kbd{cat Makefile}
2847 prefix = /usr/local
2848 datadir = $@{prefix@}/share
2849 @end example
2851 Usually one can easily change the file to accommodate both older and newer
2852 Autoconf releases:
2854 @example
2855 $ @kbd{cat Makefile.in}
2856 prefix = @@prefix@@
2857 datarootdir = @@datarootdir@@
2858 datadir = @@datadir@@
2859 $ @kbd{configure}
2860 configure: creating ./config.status
2861 config.status: creating Makefile
2862 $ @kbd{cat Makefile}
2863 prefix = /usr/local
2864 datarootdir = $@{prefix@}/share
2865 datadir = $@{datarootdir@}
2866 @end example
2868 @acindex{DATAROOTDIR_CHECKED}
2869 In some cases, however, the checks may not be able to detect that a suitable
2870 initialization of @code{datarootdir} is in place, or they may fail to detect
2871 that such an initialization is necessary in the output file.  If, after
2872 auditing your package, there are still spurious @file{configure} warnings about
2873 @code{datarootdir}, you may add the line
2875 @example
2876 AC_DEFUN([AC_DATAROOTDIR_CHECKED])
2877 @end example
2879 @noindent
2880 to your @file{configure.ac} to disable the warnings.  This is an exception
2881 to the usual rule that you should not define a macro whose name begins with
2882 @code{AC_} (@pxref{Macro Names}).
2886 @node Build Directories
2887 @subsection Build Directories
2888 @cindex Build directories
2889 @cindex Directories, build
2891 You can support compiling a software package for several architectures
2892 simultaneously from the same copy of the source code.  The object files
2893 for each architecture are kept in their own directory.
2895 To support doing this, @command{make} uses the @code{VPATH} variable to
2896 find the files that are in the source directory.  @acronym{GNU} Make
2897 can do this.  Most other recent @command{make} programs can do this as
2898 well, though they may have difficulties and it is often simpler to
2899 recommend @acronym{GNU} @command{make} (@pxref{VPATH and Make}).  Older
2900 @command{make} programs do not support @code{VPATH}; when using them, the
2901 source code must be in the same directory as the object files.
2903 If you are using @acronym{GNU} Automake, the remaining details in this
2904 section are already covered for you, based on the contents of your
2905 @file{Makefile.am}.  But if you are using Autoconf in isolation, then
2906 supporting @code{VPATH} requires the following in your
2907 @file{Makefile.in}:
2909 @example
2910 srcdir = @@srcdir@@
2911 VPATH = @@srcdir@@
2912 @end example
2914 Do not set @code{VPATH} to the value of another variable, for example
2915 @samp{VPATH = $(srcdir)}, because some versions of @command{make} do not do
2916 variable substitutions on the value of @code{VPATH}.
2918 @command{configure} substitutes the correct value for @code{srcdir} when
2919 it produces @file{Makefile}.
2921 Do not use the @command{make} variable @code{$<}, which expands to the
2922 file name of the file in the source directory (found with @code{VPATH}),
2923 except in implicit rules.  (An implicit rule is one such as @samp{.c.o},
2924 which tells how to create a @file{.o} file from a @file{.c} file.)  Some
2925 versions of @command{make} do not set @code{$<} in explicit rules; they
2926 expand it to an empty value.
2928 Instead, Make command lines should always refer to source
2929 files by prefixing them with @samp{$(srcdir)/}.  For example:
2931 @example
2932 time.info: time.texinfo
2933         $(MAKEINFO) '$(srcdir)/time.texinfo'
2934 @end example
2936 @node Automatic Remaking
2937 @subsection Automatic Remaking
2938 @cindex Automatic remaking
2939 @cindex Remaking automatically
2941 You can put rules like the following in the top-level @file{Makefile.in}
2942 for a package to automatically update the configuration information when
2943 you change the configuration files.  This example includes all of the
2944 optional files, such as @file{aclocal.m4} and those related to
2945 configuration header files.  Omit from the @file{Makefile.in} rules for
2946 any of these files that your package does not use.
2948 The @samp{$(srcdir)/} prefix is included because of limitations in the
2949 @code{VPATH} mechanism.
2951 The @file{stamp-} files are necessary because the timestamps of
2952 @file{config.h.in} and @file{config.h} are not changed if remaking
2953 them does not change their contents.  This feature avoids unnecessary
2954 recompilation.  You should include the file @file{stamp-h.in} your
2955 package's distribution, so that @command{make} considers
2956 @file{config.h.in} up to date.  Don't use @command{touch}
2957 (@pxref{Limitations of Usual Tools}); instead, use @command{echo} (using
2958 @command{date} would cause needless differences, hence @acronym{CVS}
2959 conflicts, etc.).
2961 @example
2962 @group
2963 $(srcdir)/configure: configure.ac aclocal.m4
2964         cd '$(srcdir)' && autoconf
2966 # autoheader might not change config.h.in, so touch a stamp file.
2967 $(srcdir)/config.h.in: stamp-h.in
2968 $(srcdir)/stamp-h.in: configure.ac aclocal.m4
2969         cd '$(srcdir)' && autoheader
2970         echo timestamp > '$(srcdir)/stamp-h.in'
2972 config.h: stamp-h
2973 stamp-h: config.h.in config.status
2974         ./config.status
2976 Makefile: Makefile.in config.status
2977         ./config.status
2979 config.status: configure
2980         ./config.status --recheck
2981 @end group
2982 @end example
2984 @noindent
2985 (Be careful if you copy these lines directly into your makefile, as you
2986 need to convert the indented lines to start with the tab character.)
2988 In addition, you should use
2990 @example
2991 AC_CONFIG_FILES([stamp-h], [echo timestamp > stamp-h])
2992 @end example
2994 @noindent
2995 so @file{config.status} ensures that @file{config.h} is considered up to
2996 date.  @xref{Output}, for more information about @code{AC_OUTPUT}.
2998 @xref{config.status Invocation}, for more examples of handling
2999 configuration-related dependencies.
3001 @node Configuration Headers
3002 @section Configuration Header Files
3003 @cindex Configuration Header
3004 @cindex @file{config.h}
3006 When a package contains more than a few tests that define C preprocessor
3007 symbols, the command lines to pass @option{-D} options to the compiler
3008 can get quite long.  This causes two problems.  One is that the
3009 @command{make} output is hard to visually scan for errors.  More
3010 seriously, the command lines can exceed the length limits of some
3011 operating systems.  As an alternative to passing @option{-D} options to
3012 the compiler, @command{configure} scripts can create a C header file
3013 containing @samp{#define} directives.  The @code{AC_CONFIG_HEADERS}
3014 macro selects this kind of output.  Though it can be called anywhere
3015 between @code{AC_INIT} and @code{AC_OUTPUT}, it is customary to call
3016 it right after @code{AC_INIT}.
3018 The package should @samp{#include} the configuration header file before
3019 any other header files, to prevent inconsistencies in declarations (for
3020 example, if it redefines @code{const}).
3022 To provide for VPATH builds, remember to pass the C compiler a @option{-I.}
3023 option (or @option{-I..}; whichever directory contains @file{config.h}).
3024 Even if you use @samp{#include "config.h"}, the preprocessor searches only
3025 the directory of the currently read file, i.e., the source directory, not
3026 the build directory.
3028 With the appropriate @option{-I} option, you can use
3029 @samp{#include <config.h>}.  Actually, it's a good habit to use it,
3030 because in the rare case when the source directory contains another
3031 @file{config.h}, the build directory should be searched first.
3034 @defmac AC_CONFIG_HEADERS (@var{header} @dots{}, @ovar{cmds}, @ovar{init-cmds})
3035 @acindex{CONFIG_HEADERS}
3036 @cvindex HAVE_CONFIG_H
3037 This macro is one of the instantiating macros; see @ref{Configuration
3038 Actions}.  Make @code{AC_OUTPUT} create the file(s) in the
3039 blank-or-newline-separated list @var{header} containing C preprocessor
3040 @code{#define} statements, and replace @samp{@@DEFS@@} in generated
3041 files with @option{-DHAVE_CONFIG_H} instead of the value of @code{DEFS}.
3042 The usual name for @var{header} is @file{config.h}.
3044 If @var{header} already exists and its contents are identical to what
3045 @code{AC_OUTPUT} would put in it, it is left alone.  Doing this allows
3046 making some changes in the configuration without needlessly causing
3047 object files that depend on the header file to be recompiled.
3049 Usually the input file is named @file{@var{header}.in}; however, you can
3050 override the input file name by appending to @var{header} a
3051 colon-separated list of input files.  For example, you might need to make
3052 the input file name acceptable to @acronym{DOS} variants:
3054 @example
3055 AC_CONFIG_HEADERS([config.h:config.hin])
3056 @end example
3058 @end defmac
3060 @defmac AH_HEADER
3061 @ahindex{HEADER}
3062 This macro is defined as the name of the first declared config header
3063 and undefined if no config headers have been declared up to this point.
3064 A third-party macro may, for example, require use of a config header
3065 without invoking AC_CONFIG_HEADERS twice, like this:
3067 @example
3068 AC_CONFIG_COMMANDS_PRE(
3069         [m4_ifndef([AH_HEADER], [AC_CONFIG_HEADERS([config.h])])])
3070 @end example
3072 @end defmac
3074 @xref{Configuration Actions}, for more details on @var{header}.
3076 @menu
3077 * Header Templates::            Input for the configuration headers
3078 * autoheader Invocation::       How to create configuration templates
3079 * Autoheader Macros::           How to specify CPP templates
3080 @end menu
3082 @node Header Templates
3083 @subsection Configuration Header Templates
3084 @cindex Configuration Header Template
3085 @cindex Header templates
3086 @cindex @file{config.h.in}
3088 Your distribution should contain a template file that looks as you want
3089 the final header file to look, including comments, with @code{#undef}
3090 statements which are used as hooks.  For example, suppose your
3091 @file{configure.ac} makes these calls:
3093 @example
3094 AC_CONFIG_HEADERS([conf.h])
3095 AC_CHECK_HEADERS([unistd.h])
3096 @end example
3098 @noindent
3099 Then you could have code like the following in @file{conf.h.in}.
3100 The @file{conf.h} created by @command{configure} defines @samp{HAVE_UNISTD_H}
3101 to 1, if and only if the system has @file{unistd.h}.
3103 @example
3104 @group
3105 /* Define as 1 if you have unistd.h.  */
3106 #undef HAVE_UNISTD_H
3107 @end group
3108 @end example
3110 The format of the template file is stricter than what the C preprocessor
3111 is required to accept.  A directive line should contain only whitespace,
3112 @samp{#undef}, and @samp{HAVE_UNISTD_H}.  The use of @samp{#define}
3113 instead of @samp{#undef}, or of comments on the same line as
3114 @samp{#undef}, is strongly discouraged.  Each hook should only be listed
3115 once.  Other preprocessor lines, such as @samp{#ifdef} or
3116 @samp{#include}, are copied verbatim from the template into the
3117 generated header.
3119 Since it is a tedious task to keep a template header up to date, you may
3120 use @command{autoheader} to generate it, see @ref{autoheader Invocation}.
3122 During the instantiation of the header, each @samp{#undef} line in the
3123 template file for each symbol defined by @samp{AC_DEFINE} is changed to an
3124 appropriate @samp{#define}. If the corresponding @samp{AC_DEFINE} has not
3125 been executed during the @command{configure} run, the @samp{#undef} line is
3126 commented out.  (This is important, e.g., for @samp{_POSIX_SOURCE}:
3127 on many systems, it can be implicitly defined by the compiler, and
3128 undefining it in the header would then break compilation of subsequent
3129 headers.)
3131 Currently, @emph{all} remaining @samp{#undef} lines in the header
3132 template are commented out, whether or not there was a corresponding
3133 @samp{AC_DEFINE} for the macro name; but this behavior is not guaranteed
3134 for future releases of Autoconf.
3136 Generally speaking, since you should not use @samp{#define}, and you
3137 cannot guarantee whether a @samp{#undef} directive in the header
3138 template will be converted to a @samp{#define} or commented out in the
3139 generated header file, the template file cannot be used for conditional
3140 definition effects.  Consequently, if you need to use the construct
3142 @example
3143 @group
3144 #ifdef THIS
3145 # define THAT
3146 #endif
3147 @end group
3148 @end example
3150 @noindent
3151 you must place it outside of the template.
3152 If you absolutely need to hook it to the config header itself, please put
3153 the directives to a separate file, and @samp{#include} that file from the
3154 config header template.  If you are using @command{autoheader}, you would
3155 probably use @samp{AH_BOTTOM} to append the @samp{#include} directive.
3158 @node autoheader Invocation
3159 @subsection Using @command{autoheader} to Create @file{config.h.in}
3160 @cindex @command{autoheader}
3162 The @command{autoheader} program can create a template file of C
3163 @samp{#define} statements for @command{configure} to use.
3164 It searches for the first invocation of @code{AC_CONFIG_HEADERS} in
3165 @file{configure} sources to determine the name of the template.
3166 (If the first call of @code{AC_CONFIG_HEADERS} specifies more than one
3167 input file name, @command{autoheader} uses the first one.)
3169 It is recommended that only one input file is used.  If you want to append
3170 a boilerplate code, it is preferable to use
3171 @samp{AH_BOTTOM([#include <conf_post.h>])}.
3172 File @file{conf_post.h} is not processed during the configuration then,
3173 which make things clearer.  Analogically, @code{AH_TOP} can be used to
3174 prepend a boilerplate code.
3176 In order to do its job, @command{autoheader} needs you to document all
3177 of the symbols that you might use.  Typically this is done via an
3178 @code{AC_DEFINE} or @code{AC_DEFINE_UNQUOTED} call whose first argument
3179 is a literal symbol and whose third argument describes the symbol
3180 (@pxref{Defining Symbols}).  Alternatively, you can use
3181 @code{AH_TEMPLATE} (@pxref{Autoheader Macros}), or you can supply a
3182 suitable input file for a subsequent configuration header file.
3183 Symbols defined by Autoconf's builtin tests are already documented properly;
3184 you need to document only those that you
3185 define yourself.
3187 You might wonder why @command{autoheader} is needed: after all, why
3188 would @command{configure} need to ``patch'' a @file{config.h.in} to
3189 produce a @file{config.h} instead of just creating @file{config.h} from
3190 scratch?  Well, when everything rocks, the answer is just that we are
3191 wasting our time maintaining @command{autoheader}: generating
3192 @file{config.h} directly is all that is needed.  When things go wrong,
3193 however, you'll be thankful for the existence of @command{autoheader}.
3195 The fact that the symbols are documented is important in order to
3196 @emph{check} that @file{config.h} makes sense.  The fact that there is a
3197 well-defined list of symbols that should be defined (or not) is
3198 also important for people who are porting packages to environments where
3199 @command{configure} cannot be run: they just have to @emph{fill in the
3200 blanks}.
3202 But let's come back to the point: the invocation of @command{autoheader}@dots{}
3204 If you give @command{autoheader} an argument, it uses that file instead
3205 of @file{configure.ac} and writes the header file to the standard output
3206 instead of to @file{config.h.in}.  If you give @command{autoheader} an
3207 argument of @option{-}, it reads the standard input instead of
3208 @file{configure.ac} and writes the header file to the standard output.
3210 @command{autoheader} accepts the following options:
3212 @table @option
3213 @item --help
3214 @itemx -h
3215 Print a summary of the command line options and exit.
3217 @item --version
3218 @itemx -V
3219 Print the version number of Autoconf and exit.
3221 @item --verbose
3222 @itemx -v
3223 Report processing steps.
3225 @item --debug
3226 @itemx -d
3227 Don't remove the temporary files.
3229 @item --force
3230 @itemx -f
3231 Remake the template file even if newer than its input files.
3233 @item --include=@var{dir}
3234 @itemx -I @var{dir}
3235 Append @var{dir} to the include path.  Multiple invocations accumulate.
3237 @item --prepend-include=@var{dir}
3238 @itemx -B @var{dir}
3239 Prepend @var{dir} to the include path.  Multiple invocations accumulate.
3241 @item --warnings=@var{category}
3242 @itemx -W @var{category}
3243 @evindex WARNINGS
3244 Report the warnings related to @var{category} (which can actually be a
3245 comma separated list).  Current categories include:
3247 @table @samp
3248 @item obsolete
3249 report the uses of obsolete constructs
3251 @item all
3252 report all the warnings
3254 @item none
3255 report none
3257 @item error
3258 treats warnings as errors
3260 @item no-@var{category}
3261 disable warnings falling into @var{category}
3262 @end table
3264 @end table
3268 @node Autoheader Macros
3269 @subsection Autoheader Macros
3270 @cindex Autoheader macros
3272 @command{autoheader} scans @file{configure.ac} and figures out which C
3273 preprocessor symbols it might define.  It knows how to generate
3274 templates for symbols defined by @code{AC_CHECK_HEADERS},
3275 @code{AC_CHECK_FUNCS} etc., but if you @code{AC_DEFINE} any additional
3276 symbol, you must define a template for it.  If there are missing
3277 templates, @command{autoheader} fails with an error message.
3279 The template for a @var{symbol} is created
3280 by @command{autoheader} from
3281 the @var{description} argument to an @code{AC_DEFINE};
3282 see @ref{Defining Symbols}.
3284 For special needs, you can use the following macros.
3287 @defmac AH_TEMPLATE (@var{key}, @var{description})
3288 @ahindex{TEMPLATE}
3289 Tell @command{autoheader} to generate a template for @var{key}.  This macro
3290 generates standard templates just like @code{AC_DEFINE} when a
3291 @var{description} is given.
3293 For example:
3295 @example
3296 AH_TEMPLATE([CRAY_STACKSEG_END],
3297             [Define to one of _getb67, GETB67, getb67
3298              for Cray-2 and Cray-YMP systems.  This
3299              function is required for alloca.c support
3300              on those systems.])
3301 @end example
3303 @noindent
3304 generates the following template, with the description properly
3305 justified.
3307 @example
3308 /* Define to one of _getb67, GETB67, getb67 for Cray-2 and
3309    Cray-YMP systems.  This function is required for alloca.c
3310    support on those systems.  */
3311 #undef CRAY_STACKSEG_END
3312 @end example
3313 @end defmac
3316 @defmac AH_VERBATIM (@var{key}, @var{template})
3317 @ahindex{VERBATIM}
3318 Tell @command{autoheader} to include the @var{template} as-is in the header
3319 template file.  This @var{template} is associated with the @var{key},
3320 which is used to sort all the different templates and guarantee their
3321 uniqueness.  It should be a symbol that can be defined via @code{AC_DEFINE}.
3322 @end defmac
3325 @defmac AH_TOP (@var{text})
3326 @ahindex{TOP}
3327 Include @var{text} at the top of the header template file.
3328 @end defmac
3331 @defmac AH_BOTTOM (@var{text})
3332 @ahindex{BOTTOM}
3333 Include @var{text} at the bottom of the header template file.
3334 @end defmac
3337 Please note that @var{text} gets included ``verbatim'' to the template file,
3338 not to the resulting config header, so it can easily get mangled when the
3339 template is processed.  There is rarely a need for something other than
3341 @example
3342 AH_BOTTOM([#include <custom.h>])
3343 @end example
3347 @node Configuration Commands
3348 @section Running Arbitrary Configuration Commands
3349 @cindex Configuration commands
3350 @cindex Commands for configuration
3352 You can execute arbitrary commands before, during, and after
3353 @file{config.status} is run.  The three following macros accumulate the
3354 commands to run when they are called multiple times.
3355 @code{AC_CONFIG_COMMANDS} replaces the obsolete macro
3356 @code{AC_OUTPUT_COMMANDS}; see @ref{Obsolete Macros}, for details.
3358 @anchor{AC_CONFIG_COMMANDS}
3359 @defmac AC_CONFIG_COMMANDS (@var{tag}@dots{}, @ovar{cmds}, @ovar{init-cmds})
3360 @acindex{CONFIG_COMMANDS}
3361 Specify additional shell commands to run at the end of
3362 @file{config.status}, and shell commands to initialize any variables
3363 from @command{configure}.  Associate the commands with @var{tag}.
3364 Since typically the @var{cmds} create a file, @var{tag} should
3365 naturally be the name of that file.  If needed, the directory hosting
3366 @var{tag} is created.  This macro is one of the instantiating macros;
3367 see @ref{Configuration Actions}.
3369 Here is an unrealistic example:
3370 @example
3371 fubar=42
3372 AC_CONFIG_COMMANDS([fubar],
3373                    [echo this is extra $fubar, and so on.],
3374                    [fubar=$fubar])
3375 @end example
3377 Here is a better one:
3378 @example
3379 AC_CONFIG_COMMANDS([timestamp], [date >timestamp])
3380 @end example
3381 @end defmac
3383 The following two macros look similar, but in fact they are not of the same
3384 breed: they are executed directly by @file{configure}, so you cannot use
3385 @file{config.status} to rerun them.
3387 @c Yet it is good to leave them here.  The user sees them together and
3388 @c decides which best fits their needs.
3390 @defmac AC_CONFIG_COMMANDS_PRE (@var{cmds})
3391 @acindex{CONFIG_COMMANDS_PRE}
3392 Execute the @var{cmds} right before creating @file{config.status}.
3394 This macro presents the last opportunity to call @code{AC_SUBST},
3395 @code{AC_DEFINE}, or @code{AC_CONFIG_FOOS} macros.
3396 @end defmac
3398 @defmac AC_CONFIG_COMMANDS_POST (@var{cmds})
3399 @acindex{CONFIG_COMMANDS_POST}
3400 Execute the @var{cmds} right after creating @file{config.status}.
3401 @end defmac
3406 @node Configuration Links
3407 @section Creating Configuration Links
3408 @cindex Configuration links
3409 @cindex Links for configuration
3411 You may find it convenient to create links whose destinations depend upon
3412 results of tests.  One can use @code{AC_CONFIG_COMMANDS} but the
3413 creation of relative symbolic links can be delicate when the package is
3414 built in a directory different from the source directory.
3416 @anchor{AC_CONFIG_LINKS}
3417 @defmac AC_CONFIG_LINKS (@var{dest}:@var{source}@dots{}, @ovar{cmds}, @
3418   @ovar{init-cmds})
3419 @acindex{CONFIG_LINKS}
3420 @cindex Links
3421 Make @code{AC_OUTPUT} link each of the existing files @var{source} to
3422 the corresponding link name @var{dest}.  Makes a symbolic link if
3423 possible, otherwise a hard link if possible, otherwise a copy.  The
3424 @var{dest} and @var{source} names should be relative to the top level
3425 source or build directory.  This macro is one of the instantiating
3426 macros; see @ref{Configuration Actions}.
3428 For example, this call:
3430 @example
3431 AC_CONFIG_LINKS([host.h:config/$machine.h
3432                 object.h:config/$obj_format.h])
3433 @end example
3435 @noindent
3436 creates in the current directory @file{host.h} as a link to
3437 @file{@var{srcdir}/config/$machine.h}, and @file{object.h} as a
3438 link to @file{@var{srcdir}/config/$obj_format.h}.
3440 The tempting value @samp{.} for @var{dest} is invalid: it makes it
3441 impossible for @samp{config.status} to guess the links to establish.
3443 One can then run:
3444 @example
3445 ./config.status host.h object.h
3446 @end example
3447 @noindent
3448 to create the links.
3449 @end defmac
3453 @node Subdirectories
3454 @section Configuring Other Packages in Subdirectories
3455 @cindex Configure subdirectories
3456 @cindex Subdirectory configure
3458 In most situations, calling @code{AC_OUTPUT} is sufficient to produce
3459 makefiles in subdirectories.  However, @command{configure} scripts
3460 that control more than one independent package can use
3461 @code{AC_CONFIG_SUBDIRS} to run @command{configure} scripts for other
3462 packages in subdirectories.
3464 @defmac AC_CONFIG_SUBDIRS (@var{dir} @dots{})
3465 @acindex{CONFIG_SUBDIRS}
3466 @ovindex subdirs
3467 Make @code{AC_OUTPUT} run @command{configure} in each subdirectory
3468 @var{dir} in the given blank-or-newline-separated list.  Each @var{dir} should
3469 be a literal, i.e., please do not use:
3471 @example
3472 if test "$package_foo_enabled" = yes; then
3473   $my_subdirs="$my_subdirs foo"
3475 AC_CONFIG_SUBDIRS([$my_subdirs])
3476 @end example
3478 @noindent
3479 because this prevents @samp{./configure --help=recursive} from
3480 displaying the options of the package @code{foo}.  Instead, you should
3481 write:
3483 @example
3484 if test "$package_foo_enabled" = yes; then
3485   AC_CONFIG_SUBDIRS([foo])
3487 @end example
3489 If a given @var{dir} is not found, an error is reported: if the
3490 subdirectory is optional, write:
3492 @example
3493 if test -d "$srcdir/foo"; then
3494   AC_CONFIG_SUBDIRS([foo])
3496 @end example
3498 @c NB: Yes, below we mean configure.in, not configure.ac.
3499 If a given @var{dir} contains @command{configure.gnu}, it is run instead
3500 of @command{configure}.  This is for packages that might use a
3501 non-Autoconf script @command{Configure}, which can't be called through a
3502 wrapper @command{configure} since it would be the same file on
3503 case-insensitive file systems.  Likewise, if a @var{dir} contains
3504 @file{configure.in} but no @command{configure}, the Cygnus
3505 @command{configure} script found by @code{AC_CONFIG_AUX_DIR} is used.
3507 The subdirectory @command{configure} scripts are given the same command
3508 line options that were given to this @command{configure} script, with minor
3509 changes if needed, which include:
3511 @itemize @minus
3512 @item
3513 adjusting a relative name for the cache file;
3515 @item
3516 adjusting a relative name for the source directory;
3518 @item
3519 propagating the current value of @code{$prefix}, including if it was
3520 defaulted, and if the default values of the top level and of the subdirectory
3521 @file{configure} differ.
3522 @end itemize
3524 This macro also sets the output variable @code{subdirs} to the list of
3525 directories @samp{@var{dir} @dots{}}.  Make rules can use
3526 this variable to determine which subdirectories to recurse into.
3528 This macro may be called multiple times.
3529 @end defmac
3531 @node Default Prefix
3532 @section Default Prefix
3533 @cindex Install prefix
3534 @cindex Prefix for install
3536 By default, @command{configure} sets the prefix for files it installs to
3537 @file{/usr/local}.  The user of @command{configure} can select a different
3538 prefix using the @option{--prefix} and @option{--exec-prefix} options.
3539 There are two ways to change the default: when creating
3540 @command{configure}, and when running it.
3542 Some software packages might want to install in a directory other than
3543 @file{/usr/local} by default.  To accomplish that, use the
3544 @code{AC_PREFIX_DEFAULT} macro.
3546 @defmac AC_PREFIX_DEFAULT (@var{prefix})
3547 @acindex{PREFIX_DEFAULT}
3548 Set the default installation prefix to @var{prefix} instead of
3549 @file{/usr/local}.
3550 @end defmac
3552 It may be convenient for users to have @command{configure} guess the
3553 installation prefix from the location of a related program that they
3554 have already installed.  If you wish to do that, you can call
3555 @code{AC_PREFIX_PROGRAM}.
3557 @anchor{AC_PREFIX_PROGRAM}
3558 @defmac AC_PREFIX_PROGRAM (@var{program})
3559 @acindex{PREFIX_PROGRAM}
3560 If the user did not specify an installation prefix (using the
3561 @option{--prefix} option), guess a value for it by looking for
3562 @var{program} in @env{PATH}, the way the shell does.  If @var{program}
3563 is found, set the prefix to the parent of the directory containing
3564 @var{program}, else default the prefix as described above
3565 (@file{/usr/local} or @code{AC_PREFIX_DEFAULT}).  For example, if
3566 @var{program} is @code{gcc} and the @env{PATH} contains
3567 @file{/usr/local/gnu/bin/gcc}, set the prefix to @file{/usr/local/gnu}.
3568 @end defmac
3572 @c ======================================================== Existing tests
3574 @node Existing Tests
3575 @chapter Existing Tests
3577 These macros test for particular system features that packages might
3578 need or want to use.  If you need to test for a kind of feature that
3579 none of these macros check for, you can probably do it by calling
3580 primitive test macros with appropriate arguments (@pxref{Writing
3581 Tests}).
3583 These tests print messages telling the user which feature they're
3584 checking for, and what they find.  They cache their results for future
3585 @command{configure} runs (@pxref{Caching Results}).
3587 Some of these macros set output variables.  @xref{Makefile
3588 Substitutions}, for how to get their values.  The phrase ``define
3589 @var{name}'' is used below as a shorthand to mean ``define the C
3590 preprocessor symbol @var{name} to the value 1''.  @xref{Defining
3591 Symbols}, for how to get those symbol definitions into your program.
3593 @menu
3594 * Common Behavior::             Macros' standard schemes
3595 * Alternative Programs::        Selecting between alternative programs
3596 * Files::                       Checking for the existence of files
3597 * Libraries::                   Library archives that might be missing
3598 * Library Functions::           C library functions that might be missing
3599 * Header Files::                Header files that might be missing
3600 * Declarations::                Declarations that may be missing
3601 * Structures::                  Structures or members that might be missing
3602 * Types::                       Types that might be missing
3603 * Compilers and Preprocessors::  Checking for compiling programs
3604 * System Services::             Operating system services
3605 * Posix Variants::              Special kludges for specific Posix variants
3606 * Erlang Libraries::            Checking for the existence of Erlang libraries
3607 @end menu
3609 @node Common Behavior
3610 @section Common Behavior
3611 @cindex Common autoconf behavior
3613 Much effort has been expended to make Autoconf easy to learn.  The most
3614 obvious way to reach this goal is simply to enforce standard interfaces
3615 and behaviors, avoiding exceptions as much as possible.  Because of
3616 history and inertia, unfortunately, there are still too many exceptions
3617 in Autoconf; nevertheless, this section describes some of the common
3618 rules.
3620 @menu
3621 * Standard Symbols::            Symbols defined by the macros
3622 * Default Includes::            Includes used by the generic macros
3623 @end menu
3625 @node Standard Symbols
3626 @subsection Standard Symbols
3627 @cindex Standard symbols
3629 All the generic macros that @code{AC_DEFINE} a symbol as a result of
3630 their test transform their @var{argument} values to a standard alphabet.
3631 First, @var{argument} is converted to upper case and any asterisks
3632 (@samp{*}) are each converted to @samp{P}.  Any remaining characters
3633 that are not alphanumeric are converted to underscores.
3635 For instance,
3637 @example
3638 AC_CHECK_TYPES([struct $Expensive*])
3639 @end example
3641 @noindent
3642 defines the symbol @samp{HAVE_STRUCT__EXPENSIVEP} if the check
3643 succeeds.
3646 @node Default Includes
3647 @subsection Default Includes
3648 @cindex Default includes
3649 @cindex Includes, default
3651 Several tests depend upon a set of header files.  Since these headers
3652 are not universally available, tests actually have to provide a set of
3653 protected includes, such as:
3655 @example
3656 @group
3657 #ifdef TIME_WITH_SYS_TIME
3658 # include <sys/time.h>
3659 # include <time.h>
3660 #else
3661 # ifdef HAVE_SYS_TIME_H
3662 #  include <sys/time.h>
3663 # else
3664 #  include <time.h>
3665 # endif
3666 #endif
3667 @end group
3668 @end example
3670 @noindent
3671 Unless you know exactly what you are doing, you should avoid using
3672 unconditional includes, and check the existence of the headers you
3673 include beforehand (@pxref{Header Files}).
3675 Most generic macros use the following macro to provide the default set
3676 of includes:
3678 @defmac AC_INCLUDES_DEFAULT (@ovar{include-directives})
3679 @acindex{INCLUDES_DEFAULT}
3680 Expand to @var{include-directives} if defined, otherwise to:
3682 @example
3683 @group
3684 #include <stdio.h>
3685 #ifdef HAVE_SYS_TYPES_H
3686 # include <sys/types.h>
3687 #endif
3688 #ifdef HAVE_SYS_STAT_H
3689 # include <sys/stat.h>
3690 #endif
3691 #ifdef STDC_HEADERS
3692 # include <stdlib.h>
3693 # include <stddef.h>
3694 #else
3695 # ifdef HAVE_STDLIB_H
3696 #  include <stdlib.h>
3697 # endif
3698 #endif
3699 #ifdef HAVE_STRING_H
3700 # if !defined STDC_HEADERS && defined HAVE_MEMORY_H
3701 #  include <memory.h>
3702 # endif
3703 # include <string.h>
3704 #endif
3705 #ifdef HAVE_STRINGS_H
3706 # include <strings.h>
3707 #endif
3708 #ifdef HAVE_INTTYPES_H
3709 # include <inttypes.h>
3710 #endif
3711 #ifdef HAVE_STDINT_H
3712 # include <stdint.h>
3713 #endif
3714 #ifdef HAVE_UNISTD_H
3715 # include <unistd.h>
3716 #endif
3717 @end group
3718 @end example
3720 If the default includes are used, then check for the presence of these
3721 headers and their compatibility, i.e., you don't need to run
3722 @code{AC_HEADER_STDC}, nor check for @file{stdlib.h} etc.
3724 These headers are checked for in the same order as they are included.
3725 For instance, on some systems @file{string.h} and @file{strings.h} both
3726 exist, but conflict.  Then @code{HAVE_STRING_H} is defined, not
3727 @code{HAVE_STRINGS_H}.
3728 @end defmac
3730 @node Alternative Programs
3731 @section Alternative Programs
3732 @cindex Programs, checking
3734 These macros check for the presence or behavior of particular programs.
3735 They are used to choose between several alternative programs and to
3736 decide what to do once one has been chosen.  If there is no macro
3737 specifically defined to check for a program you need, and you don't need
3738 to check for any special properties of it, then you can use one of the
3739 general program-check macros.
3741 @menu
3742 * Particular Programs::         Special handling to find certain programs
3743 * Generic Programs::            How to find other programs
3744 @end menu
3746 @node Particular Programs
3747 @subsection Particular Program Checks
3749 These macros check for particular programs---whether they exist, and
3750 in some cases whether they support certain features.
3752 @defmac AC_PROG_AWK
3753 @acindex{PROG_AWK}
3754 @ovindex AWK
3755 Check for @code{gawk}, @code{mawk}, @code{nawk}, and @code{awk}, in that
3756 order, and set output variable @code{AWK} to the first one that is found.
3757 It tries @code{gawk} first because that is reported to be the
3758 best implementation.
3759 @end defmac
3761 @defmac AC_PROG_GREP
3762 @acindex{PROG_GREP}
3763 @ovindex GREP
3764 Look for the best available @code{grep} or @code{ggrep} that accepts the
3765 longest input lines possible, and that supports multiple @option{-e} options.
3766 Set the output variable @code{GREP} to whatever is chosen.
3767 @xref{Limitations of Usual Tools}, for more information about
3768 portability problems with the @command{grep} command family.
3769 @end defmac
3771 @defmac AC_PROG_EGREP
3772 @acindex{PROG_EGREP}
3773 @ovindex EGREP
3774 Check whether @code{$GREP -E} works, or else look for the best available
3775 @code{egrep} or @code{gegrep} that accepts the longest input lines possible.
3776 Set the output variable @code{EGREP} to whatever is chosen.
3777 @end defmac
3779 @defmac AC_PROG_FGREP
3780 @acindex{PROG_FGREP}
3781 @ovindex FGREP
3782 Check whether @code{$GREP -F} works, or else look for the best available
3783 @code{fgrep} or @code{gfgrep} that accepts the longest input lines possible.
3784 Set the output variable @code{FGREP} to whatever is chosen.
3785 @end defmac
3787 @defmac AC_PROG_INSTALL
3788 @acindex{PROG_INSTALL}
3789 @ovindex INSTALL
3790 @ovindex INSTALL_PROGRAM
3791 @ovindex INSTALL_DATA
3792 @ovindex INSTALL_SCRIPT
3793 Set output variable @code{INSTALL} to the name of a @acronym{BSD}-compatible
3794 @command{install} program, if one is found in the current @env{PATH}.
3795 Otherwise, set @code{INSTALL} to @samp{@var{dir}/install-sh -c},
3796 checking the directories specified to @code{AC_CONFIG_AUX_DIR} (or its
3797 default directories) to determine @var{dir} (@pxref{Output}).  Also set
3798 the variables @code{INSTALL_PROGRAM} and @code{INSTALL_SCRIPT} to
3799 @samp{$@{INSTALL@}} and @code{INSTALL_DATA} to @samp{$@{INSTALL@} -m 644}.
3801 @samp{@@INSTALL@@} is special, as its value may vary for different
3802 configuration files.
3804 This macro screens out various instances of @command{install} known not to
3805 work.  It prefers to find a C program rather than a shell script, for
3806 speed.  Instead of @file{install-sh}, it can also use @file{install.sh},
3807 but that name is obsolete because some @command{make} programs have a rule
3808 that creates @file{install} from it if there is no makefile.  Further, this
3809 macro requires @command{install} to be able to install multiple files into a
3810 target directory in a single invocation.
3812 Autoconf comes with a copy of @file{install-sh} that you can use.  If
3813 you use @code{AC_PROG_INSTALL}, you must include either
3814 @file{install-sh} or @file{install.sh} in your distribution; otherwise
3815 @command{configure} produces an error message saying it can't find
3816 them---even if the system you're on has a good @command{install} program.
3817 This check is a safety measure to prevent you from accidentally leaving
3818 that file out, which would prevent your package from installing on
3819 systems that don't have a @acronym{BSD}-compatible @command{install} program.
3821 If you need to use your own installation program because it has features
3822 not found in standard @command{install} programs, there is no reason to use
3823 @code{AC_PROG_INSTALL}; just put the file name of your program into your
3824 @file{Makefile.in} files.
3825 @end defmac
3827 @defmac AC_PROG_MKDIR_P
3828 @acindex{PROG_MKDIR_P}
3829 @ovindex MKDIR_P
3830 Set output variable @code{MKDIR_P} to a program that ensures that for
3831 each argument, a directory named by this argument exists, creating it
3832 and its parent directories if needed, and without race conditions when
3833 two instances of the program attempt to make the same directory at
3834 nearly the same time.
3836 This macro uses the @samp{mkdir -p} command if possible.  Otherwise, it
3837 falls back on invoking @command{install-sh} with the @option{-d} option,
3838 so your package should
3839 contain @file{install-sh} as described under @code{AC_PROG_INSTALL}.
3840 An @file{install-sh} file that predates Autoconf 2.60 or Automake 1.10
3841 is vulnerable to race conditions, so if you want to support parallel
3842 installs from
3843 different packages into the same directory you need to make sure you
3844 have an up-to-date @file{install-sh}.  In particular, be careful about
3845 using @samp{autoreconf -if} if your Automake predates Automake 1.10.
3847 This macro is related to the @code{AS_MKDIR_P} macro (@pxref{Programming
3848 in M4sh}), but it sets an output variable intended for use in other
3849 files, whereas @code{AS_MKDIR_P} is intended for use in scripts like
3850 @command{configure}.  Also, @code{AS_MKDIR_P} does not accept options,
3851 but @code{MKDIR_P} supports the @option{-m} option, e.g., a makefile
3852 might invoke @code{$(MKDIR_P) -m 0 dir} to create an inaccessible
3853 directory, and conversely a makefile should use @code{$(MKDIR_P) --
3854 $(FOO)} if @var{FOO} might yield a value that begins with @samp{-}.
3855 Finally, @code{AS_MKDIR_P} does not check for race condition
3856 vulnerability, whereas @code{AC_PROG_MKDIR_P} does.
3858 @samp{@@MKDIR_P@@} is special, as its value may vary for different
3859 configuration files.
3860 @end defmac
3862 @anchor{AC_PROG_LEX}
3863 @defmac AC_PROG_LEX
3864 @acindex{PROG_LEX}
3865 @ovindex LEX
3866 @ovindex LEXLIB
3867 @cvindex YYTEXT_POINTER
3868 @ovindex LEX_OUTPUT_ROOT
3869 If @code{flex} is found, set output variable @code{LEX} to @samp{flex}
3870 and @code{LEXLIB} to @option{-lfl}, if that library is in a standard
3871 place.  Otherwise set @code{LEX} to @samp{lex} and @code{LEXLIB} to
3872 @option{-ll}.
3874 Define @code{YYTEXT_POINTER} if @code{yytext} defaults to @samp{char *} instead
3875 of to @samp{char []}.  Also set output variable @code{LEX_OUTPUT_ROOT} to
3876 the base of the file name that the lexer generates; usually
3877 @file{lex.yy}, but sometimes something else.  These results vary
3878 according to whether @code{lex} or @code{flex} is being used.
3880 You are encouraged to use Flex in your sources, since it is both more
3881 pleasant to use than plain Lex and the C source it produces is portable.
3882 In order to ensure portability, however, you must either provide a
3883 function @code{yywrap} or, if you don't use it (e.g., your scanner has
3884 no @samp{#include}-like feature), simply include a @samp{%noyywrap}
3885 statement in the scanner's source.  Once this done, the scanner is
3886 portable (unless @emph{you} felt free to use nonportable constructs) and
3887 does not depend on any library.  In this case, and in this case only, it
3888 is suggested that you use this Autoconf snippet:
3890 @example
3891 AC_PROG_LEX
3892 if test "$LEX" != flex; then
3893   LEX="$SHELL $missing_dir/missing flex"
3894   AC_SUBST([LEX_OUTPUT_ROOT], [lex.yy])
3895   AC_SUBST([LEXLIB], [''])
3897 @end example
3899 The shell script @command{missing} can be found in the Automake
3900 distribution.
3902 To ensure backward compatibility, Automake's @code{AM_PROG_LEX} invokes
3903 (indirectly) this macro twice, which causes an annoying but benign
3904 ``@code{AC_PROG_LEX} invoked multiple times'' warning.  Future versions
3905 of Automake will fix this issue; meanwhile, just ignore this message.
3907 As part of running the test, this macro may delete any file in the
3908 configuration directory named @file{lex.yy.c} or @file{lexyy.c}.
3909 @end defmac
3911 @anchor{AC_PROG_LN_S}
3912 @defmac AC_PROG_LN_S
3913 @acindex{PROG_LN_S}
3914 @ovindex LN_S
3915 If @samp{ln -s} works on the current file system (the operating system
3916 and file system support symbolic links), set the output variable
3917 @code{LN_S} to @samp{ln -s}; otherwise, if @samp{ln} works, set
3918 @code{LN_S} to @samp{ln}, and otherwise set it to @samp{cp -p}.
3920 If you make a link in a directory other than the current directory, its
3921 meaning depends on whether @samp{ln} or @samp{ln -s} is used.  To safely
3922 create links using @samp{$(LN_S)}, either find out which form is used
3923 and adjust the arguments, or always invoke @code{ln} in the directory
3924 where the link is to be created.
3926 In other words, it does not work to do:
3927 @example
3928 $(LN_S) foo /x/bar
3929 @end example
3931 Instead, do:
3933 @example
3934 (cd /x && $(LN_S) foo bar)
3935 @end example
3936 @end defmac
3938 @defmac AC_PROG_RANLIB
3939 @acindex{PROG_RANLIB}
3940 @ovindex RANLIB
3941 Set output variable @code{RANLIB} to @samp{ranlib} if @code{ranlib}
3942 is found, and otherwise to @samp{:} (do nothing).
3943 @end defmac
3945 @defmac AC_PROG_SED
3946 @acindex{PROG_SED}
3947 @ovindex SED
3948 Set output variable @code{SED} to a Sed implementation that conforms to
3949 Posix and does not have arbitrary length limits.  Report an error if no
3950 acceptable Sed is found.  @xref{Limitations of Usual Tools}, for more
3951 information about portability problems with Sed.
3952 @end defmac
3954 @defmac AC_PROG_YACC
3955 @acindex{PROG_YACC}
3956 @ovindex YACC
3957 If @code{bison} is found, set output variable @code{YACC} to @samp{bison
3958 -y}.  Otherwise, if @code{byacc} is found, set @code{YACC} to
3959 @samp{byacc}.  Otherwise set @code{YACC} to @samp{yacc}.
3960 @end defmac
3962 @node Generic Programs
3963 @subsection Generic Program and File Checks
3965 These macros are used to find programs not covered by the ``particular''
3966 test macros.  If you need to check the behavior of a program as well as
3967 find out whether it is present, you have to write your own test for it
3968 (@pxref{Writing Tests}).  By default, these macros use the environment
3969 variable @env{PATH}.  If you need to check for a program that might not
3970 be in the user's @env{PATH}, you can pass a modified path to use
3971 instead, like this:
3973 @example
3974 AC_PATH_PROG([INETD], [inetd], [/usr/libexec/inetd],
3975              [$PATH$PATH_SEPARATOR/usr/libexec$PATH_SEPARATOR]dnl
3976 [/usr/sbin$PATH_SEPARATOR/usr/etc$PATH_SEPARATOR/etc])
3977 @end example
3979 You are strongly encouraged to declare the @var{variable} passed to
3980 @code{AC_CHECK_PROG} etc.@: as precious, @xref{Setting Output Variables},
3981 @code{AC_ARG_VAR}, for more details.
3983 @anchor{AC_CHECK_PROG}
3984 @defmac AC_CHECK_PROG (@var{variable}, @var{prog-to-check-for}, @
3985   @var{value-if-found}, @ovar{value-if-not-found}, @dvar{path, $PATH}, @
3986   @ovar{reject})
3987 @acindex{CHECK_PROG}
3988 Check whether program @var{prog-to-check-for} exists in @var{path}.  If
3989 it is found, set @var{variable} to @var{value-if-found}, otherwise to
3990 @var{value-if-not-found}, if given.  Always pass over @var{reject} (an
3991 absolute file name) even if it is the first found in the search path; in
3992 that case, set @var{variable} using the absolute file name of the
3993 @var{prog-to-check-for} found that is not @var{reject}.  If
3994 @var{variable} was already set, do nothing.  Calls @code{AC_SUBST} for
3995 @var{variable}.
3996 @end defmac
3998 @anchor{AC_CHECK_PROGS}
3999 @defmac AC_CHECK_PROGS (@var{variable}, @var{progs-to-check-for}, @
4000   @ovar{value-if-not-found}, @dvar{path, $PATH})
4001 @acindex{CHECK_PROGS}
4002 Check for each program in the blank-separated list
4003 @var{progs-to-check-for} existing in the @var{path}.  If one is found, set
4004 @var{variable} to the name of that program.  Otherwise, continue
4005 checking the next program in the list.  If none of the programs in the
4006 list are found, set @var{variable} to @var{value-if-not-found}; if
4007 @var{value-if-not-found} is not specified, the value of @var{variable}
4008 is not changed.  Calls @code{AC_SUBST} for @var{variable}.
4009 @end defmac
4011 @defmac AC_CHECK_TARGET_TOOL (@var{variable}, @var{prog-to-check-for}, @
4012   @ovar{value-if-not-found}, @dvar{path, $PATH})
4013 @acindex{CHECK_TARGET_TOOL}
4014 Like @code{AC_CHECK_PROG}, but first looks for @var{prog-to-check-for}
4015 with a prefix of the target type as determined by
4016 @code{AC_CANONICAL_TARGET}, followed by a dash (@pxref{Canonicalizing}).
4017 If the tool cannot be found with a prefix, and if the build and target
4018 types are equal, then it is also searched for without a prefix.
4020 As noted in @ref{Specifying Names, , Specifying the system type}, the
4021 target is rarely specified, because most of the time it is the same
4022 as the host: it is the type of system for which any compiler tool in
4023 the package produces code.  What this macro looks for is,
4024 for example, @emph{a tool @r{(assembler, linker, etc.)}@: that the
4025 compiler driver @r{(@command{gcc} for the @acronym{GNU} C Compiler)}
4026 uses to produce objects, archives or executables}.
4027 @end defmac
4029 @defmac AC_CHECK_TOOL (@var{variable}, @var{prog-to-check-for}, @
4030   @ovar{value-if-not-found}, @dvar{path, $PATH})
4031 @acindex{CHECK_TOOL}
4032 Like @code{AC_CHECK_PROG}, but first looks for @var{prog-to-check-for}
4033 with a prefix of the host type as specified by @option{--host}, followed by a
4034 dash.  For example, if the user runs
4035 @samp{configure --build=x86_64-gnu --host=i386-gnu}, then this call:
4036 @example
4037 AC_CHECK_TOOL([RANLIB], [ranlib], [:])
4038 @end example
4039 @noindent
4040 sets @code{RANLIB} to @file{i386-gnu-ranlib} if that program exists in
4041 @var{path}, or otherwise to @samp{ranlib} if that program exists in
4042 @var{path}, or to @samp{:} if neither program exists.
4044 When cross-compiling, this macro will issue a warning if no program
4045 prefixed with the host type could be found.
4046 For more information, see @ref{Specifying Names, , Specifying the
4047 system type}.
4048 @end defmac
4050 @defmac AC_CHECK_TARGET_TOOLS (@var{variable}, @var{progs-to-check-for}, @
4051   @ovar{value-if-not-found}, @dvar{path, $PATH})
4052 @acindex{CHECK_TARGET_TOOLS}
4053 Like @code{AC_CHECK_TARGET_TOOL}, each of the tools in the list
4054 @var{progs-to-check-for} are checked with a prefix of the target type as
4055 determined by @code{AC_CANONICAL_TARGET}, followed by a dash
4056 (@pxref{Canonicalizing}).  If none of the tools can be found with a
4057 prefix, and if the build and target types are equal, then the first one
4058 without a prefix is used.  If a tool is found, set @var{variable} to
4059 the name of that program.  If none of the tools in the list are found,
4060 set @var{variable} to @var{value-if-not-found}; if @var{value-if-not-found}
4061 is not specified, the value of @var{variable} is not changed.  Calls
4062 @code{AC_SUBST} for @var{variable}.
4063 @end defmac
4065 @defmac AC_CHECK_TOOLS (@var{variable}, @var{progs-to-check-for}, @
4066   @ovar{value-if-not-found}, @dvar{path, $PATH})
4067 @acindex{CHECK_TOOLS}
4068 Like @code{AC_CHECK_TOOL}, each of the tools in the list
4069 @var{progs-to-check-for} are checked with a prefix of the host type as
4070 determined by @code{AC_CANONICAL_HOST}, followed by a dash
4071 (@pxref{Canonicalizing}).  If none of the tools can be found with a
4072 prefix, then the first one without a prefix is used.  If a tool is found,
4073 set @var{variable} to the name of that program.  If none of the tools in
4074 the list are found, set @var{variable} to @var{value-if-not-found}; if
4075 @var{value-if-not-found} is not specified, the value of @var{variable}
4076 is not changed.  Calls @code{AC_SUBST} for @var{variable}.
4078 When cross-compiling, this macro will issue a warning if no program
4079 prefixed with the host type could be found.
4080 For more information, see @ref{Specifying Names, , Specifying the
4081 system type}.
4082 @end defmac
4084 @anchor{AC_PATH_PROG}
4085 @defmac AC_PATH_PROG (@var{variable}, @var{prog-to-check-for}, @
4086   @ovar{value-if-not-found}, @dvar{path, $PATH})
4087 @acindex{PATH_PROG}
4088 Like @code{AC_CHECK_PROG}, but set @var{variable} to the absolute
4089 name of @var{prog-to-check-for} if found.
4090 @end defmac
4092 @anchor{AC_PATH_PROGS}
4093 @defmac AC_PATH_PROGS (@var{variable}, @var{progs-to-check-for}, @
4094   @ovar{value-if-not-found}, @dvar{path, $PATH})
4095 @acindex{PATH_PROGS}
4096 Like @code{AC_CHECK_PROGS}, but if any of @var{progs-to-check-for}
4097 are found, set @var{variable} to the absolute name of the program
4098 found.
4099 @end defmac
4101 @defmac AC_PATH_PROGS_FEATURE_CHECK (@var{variable}, @
4102   @var{progs-to-check-for}, @var{feature-test}, @
4103   @ovar{action-if-not-found}, @dvar{path, $PATH})
4104 @acindex{PATH_PROGS_FEATURE_CHECK}
4105 This macro was introduced in Autoconf 2.62.  If @var{variable} is not
4106 empty, then set the cache variable @code{$ac_cv_path_@var{variable}} to
4107 its value.  Otherwise, check for each program in the blank-separated
4108 list @var{progs-to-check-for} existing in @var{path}.  For each program
4109 found, execute @var{feature-test} with @code{$ac_path_@var{variable}}
4110 set to the absolute name of the candidate program.  If no invocation of
4111 @var{feature-test} sets the shell variable
4112 @code{$ac_cv_path_@var{variable}}, then @var{action-if-not-found} is
4113 executed.  @var{feature-test} will be run even when
4114 @code{ac_cv_path_@var{variable}} is set, to provide the ability to
4115 choose a better candidate found later in @var{path}; to accept the
4116 current setting and bypass all futher checks, @var{feature-test} can
4117 execute @code{ac_path_@var{variable}_found=:}.
4119 Note that this macro has some subtle differences from
4120 @code{AC_CHECK_PROGS}.  It is designed to be run inside
4121 @code{AC_CACHE_VAL}, therefore, it should have no side effects.  In
4122 particular, @var{variable} is not set to the final value of
4123 @code{ac_cv_path_@var{variable}}, nor is @code{AC_SUBST} automatically
4124 run.  Also, on failure, any action can be performed, whereas
4125 @code{AC_CHECK_PROGS} only performs
4126 @code{@var{variable}=@var{value-if-not-found}}.
4128 Here is an example, similar to what Autoconf uses in its own configure
4129 script.  It will search for an implementation of @command{m4} that
4130 supports the @code{indir} builtin, even if it goes by the name
4131 @command{gm4} or is not the first implementation on @env{PATH}.
4133 @example
4134 AC_CACHE_CHECK([for m4 that supports indir], [ac_cv_path_M4],
4135   [AC_PATH_PROGS_FEATURE_CHECK([M4], [m4 gm4],
4136     [[m4out=`echo 'changequote([,])indir([divnum])' | $ac_path_M4`
4137       test "x$m4out" = x0 \
4138       && ac_cv_path_M4=$ac_path_M4 ac_path_M4_found=:]],
4139     [AC_MSG_ERROR([could not find m4 that supports indir])])])
4140 AC_SUBST([M4], [$ac_cv_path_M4])
4141 @end example
4142 @end defmac
4144 @defmac AC_PATH_TARGET_TOOL (@var{variable}, @var{prog-to-check-for}, @
4145   @ovar{value-if-not-found}, @dvar{path, $PATH})
4146 @acindex{PATH_TARGET_TOOL}
4147 Like @code{AC_CHECK_TARGET_TOOL}, but set @var{variable} to the absolute
4148 name of the program if it is found.
4149 @end defmac
4151 @defmac AC_PATH_TOOL (@var{variable}, @var{prog-to-check-for}, @
4152   @ovar{value-if-not-found}, @dvar{path, $PATH})
4153 @acindex{PATH_TOOL}
4154 Like @code{AC_CHECK_TOOL}, but set @var{variable} to the absolute
4155 name of the program if it is found.
4157 When cross-compiling, this macro will issue a warning if no program
4158 prefixed with the host type could be found.
4159 For more information, see @ref{Specifying Names, , Specifying the
4160 system type}.
4161 @end defmac
4164 @node Files
4165 @section Files
4166 @cindex File, checking
4168 You might also need to check for the existence of files.  Before using
4169 these macros, ask yourself whether a runtime test might not be a better
4170 solution.  Be aware that, like most Autoconf macros, they test a feature
4171 of the host machine, and therefore, they die when cross-compiling.
4173 @defmac AC_CHECK_FILE (@var{file}, @ovar{action-if-found}, @
4174   @ovar{action-if-not-found})
4175 @acindex{CHECK_FILE}
4176 Check whether file @var{file} exists on the native system.  If it is
4177 found, execute @var{action-if-found}, otherwise do
4178 @var{action-if-not-found}, if given.
4179 @end defmac
4181 @defmac AC_CHECK_FILES (@var{files}, @ovar{action-if-found}, @
4182   @ovar{action-if-not-found})
4183 @acindex{CHECK_FILES}
4184 Executes @code{AC_CHECK_FILE} once for each file listed in @var{files}.
4185 Additionally, defines @samp{HAVE_@var{file}} (@pxref{Standard Symbols})
4186 for each file found.
4187 @end defmac
4190 @node Libraries
4191 @section Library Files
4192 @cindex Library, checking
4194 The following macros check for the presence of certain C, C++, or Fortran
4195 library archive files.
4197 @anchor{AC_CHECK_LIB}
4198 @defmac AC_CHECK_LIB (@var{library}, @var{function}, @
4199   @ovar{action-if-found}, @ovar{action-if-not-found}, @ovar{other-libraries})
4200 @acindex{CHECK_LIB}
4201 Test whether the library @var{library} is available by trying to link
4202 a test program that calls function @var{function} with the library.
4203 @var{function} should be a function provided by the library.
4204 Use the base
4205 name of the library; e.g., to check for @option{-lmp}, use @samp{mp} as
4206 the @var{library} argument.
4208 @var{action-if-found} is a list of shell commands to run if the link
4209 with the library succeeds; @var{action-if-not-found} is a list of shell
4210 commands to run if the link fails.  If @var{action-if-found} is not
4211 specified, the default action prepends @option{-l@var{library}} to
4212 @code{LIBS} and defines @samp{HAVE_LIB@var{library}} (in all
4213 capitals).  This macro is intended to support building @code{LIBS} in
4214 a right-to-left (least-dependent to most-dependent) fashion such that
4215 library dependencies are satisfied as a natural side effect of
4216 consecutive tests.  Linkers are sensitive to library ordering
4217 so the order in which @code{LIBS} is generated is important to reliable
4218 detection of libraries.
4220 If linking with @var{library} results in unresolved symbols that would
4221 be resolved by linking with additional libraries, give those libraries
4222 as the @var{other-libraries} argument, separated by spaces:
4223 e.g., @option{-lXt -lX11}.  Otherwise, this macro fails to detect
4224 that @var{library} is present, because linking the test program
4225 always fails with unresolved symbols.  The @var{other-libraries} argument
4226 should be limited to cases where it is desirable to test for one library
4227 in the presence of another that is not already in @code{LIBS}.
4229 @code{AC_CHECK_LIB} requires some care in usage, and should be avoided
4230 in some common cases.  Many standard functions like @code{gethostbyname}
4231 appear in the standard C library on some hosts, and in special libraries
4232 like @code{nsl} on other hosts.  On some hosts the special libraries
4233 contain variant implementations that you may not want to use.  These
4234 days it is normally better to use @code{AC_SEARCH_LIBS([gethostbyname],
4235 [nsl])} instead of @code{AC_CHECK_LIB([nsl], [gethostbyname])}.
4236 @end defmac
4238 @anchor{AC_SEARCH_LIBS}
4239 @defmac AC_SEARCH_LIBS (@var{function}, @var{search-libs}, @
4240   @ovar{action-if-found}, @ovar{action-if-not-found}, @ovar{other-libraries})
4241 @acindex{SEARCH_LIBS}
4242 Search for a library defining @var{function} if it's not already
4243 available.  This equates to calling
4244 @samp{AC_LINK_IFELSE([AC_LANG_CALL([], [@var{function}])])} first with
4245 no libraries, then for each library listed in @var{search-libs}.
4247 Add @option{-l@var{library}} to @code{LIBS} for the first library found
4248 to contain @var{function}, and run @var{action-if-found}.  If the
4249 function is not found, run @var{action-if-not-found}.
4251 If linking with @var{library} results in unresolved symbols that would
4252 be resolved by linking with additional libraries, give those libraries
4253 as the @var{other-libraries} argument, separated by spaces:
4254 e.g., @option{-lXt -lX11}.  Otherwise, this macro fails to detect
4255 that @var{function} is present, because linking the test program
4256 always fails with unresolved symbols.
4257 @end defmac
4261 @node Library Functions
4262 @section Library Functions
4264 The following macros check for particular C library functions.
4265 If there is no macro specifically defined to check for a function you need,
4266 and you don't need to check for any special properties of
4267 it, then you can use one of the general function-check macros.
4269 @menu
4270 * Function Portability::        Pitfalls with usual functions
4271 * Particular Functions::        Special handling to find certain functions
4272 * Generic Functions::           How to find other functions
4273 @end menu
4275 @node Function Portability
4276 @subsection Portability of C Functions
4277 @cindex Portability of C functions
4278 @cindex C function portability
4280 Most usual functions can either be missing, or be buggy, or be limited
4281 on some architectures.  This section tries to make an inventory of these
4282 portability issues.  By definition, this list always requires
4283 additions.  Please help us keeping it as complete as possible.
4285 @table @asis
4286 @item @code{exit}
4287 @c @fuindex exit
4288 @prindex @code{exit}
4289 On ancient hosts, @code{exit} returned @code{int}.
4290 This is because @code{exit} predates @code{void}, and there was a long
4291 tradition of it returning @code{int}.
4293 On current hosts, the problem more likely is that @code{exit} is not
4294 declared, due to C++ problems of some sort or another.  For this reason
4295 we suggest that test programs not invoke @code{exit}, but return from
4296 @code{main} instead.
4298 @item @code{free}
4299 @c @fuindex free
4300 @prindex @code{free}
4301 The C standard says a call @code{free (NULL)} does nothing, but
4302 some old systems don't support this (e.g., NextStep).
4304 @item @code{isinf}
4305 @itemx @code{isnan}
4306 @c @fuindex isinf
4307 @c @fuindex isnan
4308 @prindex @code{isinf}
4309 @prindex @code{isnan}
4310 The C99 standard says that @code{isinf} and @code{isnan} are
4311 macros.  On some systems just macros are available
4312 (e.g., @acronym{HP-UX} and Solaris 10), on
4313 some systems both macros and functions (e.g., glibc 2.3.2), and on some
4314 systems only functions (e.g., IRIX 6 and Solaris 9).  In some cases
4315 these functions are declared in nonstandard headers like
4316 @code{<sunmath.h>} and defined in non-default libraries like
4317 @option{-lm} or @option{-lsunmath}.
4319 The C99 @code{isinf} and @code{isnan} macros work correctly with
4320 @code{long double} arguments, but pre-C99 systems that use functions
4321 typically assume @code{double} arguments.  On such a system,
4322 @code{isinf} incorrectly returns true for a finite @code{long double}
4323 argument that is outside the range of @code{double}.
4325 The best workaround for these issues is to use gnulib modules
4326 @code{isinf} and @code{isnan} (@pxref{Gnulib}).  But a lighter weight
4327 solution involves code like the following.
4329 @smallexample
4330 #include <math.h>
4332 #ifndef isnan
4333 # define isnan(x) \
4334     (sizeof (x) == sizeof (long double) ? isnan_ld (x) \
4335      : sizeof (x) == sizeof (double) ? isnan_d (x) \
4336      : isnan_f (x))
4337 static inline int isnan_f  (float       x) @{ return x != x; @}
4338 static inline int isnan_d  (double      x) @{ return x != x; @}
4339 static inline int isnan_ld (long double x) @{ return x != x; @}
4340 #endif
4342 #ifndef isinf
4343 # define isinf(x) \
4344     (sizeof (x) == sizeof (long double) ? isinf_ld (x) \
4345      : sizeof (x) == sizeof (double) ? isinf_d (x) \
4346      : isinf_f (x))
4347 static inline int isinf_f  (float       x)
4348 @{ return !isnan (x) && isnan (x - x); @}
4349 static inline int isinf_d  (double      x)
4350 @{ return !isnan (x) && isnan (x - x); @}
4351 static inline int isinf_ld (long double x)
4352 @{ return !isnan (x) && isnan (x - x); @}
4353 #endif
4354 @end smallexample
4356 Use @code{AC_C_INLINE} (@pxref{C Compiler}) so that this code works on
4357 compilers that lack the @code{inline} keyword.  Some optimizing
4358 compilers mishandle these definitions, but systems with that bug
4359 typically have many other floating point corner-case compliance problems
4360 anyway, so it's probably not worth worrying about.
4362 @item @code{malloc}
4363 @c @fuindex malloc
4364 @prindex @code{malloc}
4365 The C standard says a call @code{malloc (0)} is implementation
4366 dependent.  It can return either @code{NULL} or a new non-null pointer.
4367 The latter is more common (e.g., the @acronym{GNU} C Library) but is by
4368 no means universal.  @code{AC_FUNC_MALLOC}
4369 can be used to insist on non-@code{NULL} (@pxref{Particular Functions}).
4371 @item @code{putenv}
4372 @c @fuindex putenv
4373 @prindex @code{putenv}
4374 Posix prefers @code{setenv} to @code{putenv}; among other things,
4375 @code{putenv} is not required of all Posix implementations, but
4376 @code{setenv} is.
4378 Posix specifies that @code{putenv} puts the given string directly in
4379 @code{environ}, but some systems make a copy of it instead (e.g.,
4380 glibc 2.0, or @acronym{BSD}).  And when a copy is made, @code{unsetenv} might
4381 not free it, causing a memory leak (e.g., Free@acronym{BSD} 4).
4383 On some systems @code{putenv ("FOO")} removes @samp{FOO} from the
4384 environment, but this is not standard usage and it dumps core
4385 on some systems (e.g., AIX).
4387 On MinGW, a call @code{putenv ("FOO=")} removes @samp{FOO} from the
4388 environment, rather than inserting it with an empty value.
4390 @item @code{realloc}
4391 @c @fuindex realloc
4392 @prindex @code{realloc}
4393 The C standard says a call @code{realloc (NULL, size)} is equivalent
4394 to @code{malloc (size)}, but some old systems don't support this (e.g.,
4395 NextStep).
4397 @item @code{signal} handler
4398 @c @fuindex signal
4399 @prindex @code{signal}
4400 @prindex @code{sigaction}
4401 Normally @code{signal} takes a handler function with a return type of
4402 @code{void}, but some old systems required @code{int} instead.  Any
4403 actual @code{int} value returned is not used; this is only a
4404 difference in the function prototype demanded.
4406 All systems we know of in current use return @code{void}.  The
4407 @code{int} was to support K&R C, where of course @code{void} is not
4408 available.  The obsolete macro @code{AC_TYPE_SIGNAL}
4409 (@pxref{AC_TYPE_SIGNAL}) can be used to establish the correct type in
4410 all cases.
4412 In most cases, it is more robust to use @code{sigaction} when it is
4413 available, rather than @code{signal}.
4415 @item @code{snprintf}
4416 @c @fuindex snprintf
4417 @prindex @code{snprintf}
4418 @c @fuindex vsnprintf
4419 @prindex @code{vsnprintf}
4420 The C99 standard says that if the output array isn't big enough
4421 and if no other errors occur, @code{snprintf} and @code{vsnprintf}
4422 truncate the output and return the number of bytes that ought to have
4423 been produced.  Some older systems return the truncated length (e.g.,
4424 @acronym{GNU} C Library 2.0.x or @sc{irix} 6.5), some a negative value
4425 (e.g., earlier @acronym{GNU} C Library versions), and some the buffer
4426 length without truncation (e.g., 32-bit Solaris 7).  Also, some buggy
4427 older systems ignore the length and overrun the buffer (e.g., 64-bit
4428 Solaris 7).
4430 @item @code{sprintf}
4431 @c @fuindex sprintf
4432 @prindex @code{sprintf}
4433 @c @fuindex vsprintf
4434 @prindex @code{vsprintf}
4435 The C standard says @code{sprintf} and @code{vsprintf} return the
4436 number of bytes written.  On some ancient systems (SunOS 4 for
4437 instance) they return the buffer pointer instead, but these no
4438 longer need to be worried about.
4440 @item @code{sscanf}
4441 @c @fuindex sscanf
4442 @prindex @code{sscanf}
4443 On various old systems, e.g., @acronym{HP-UX} 9, @code{sscanf} requires
4444 that its
4445 input string be writable (though it doesn't actually change it).  This
4446 can be a problem when using @command{gcc} since it normally puts
4447 constant strings in read-only memory (@pxref{Incompatibilities,
4448 Incompatibilities of @acronym{GCC}, , gcc, Using and
4449 Porting the @acronym{GNU} Compiler Collection}).  Apparently in some cases even
4450 having format strings read-only can be a problem.
4452 @item @code{strerror_r}
4453 @c @fuindex strerror_r
4454 @prindex @code{strerror_r}
4455 Posix specifies that @code{strerror_r} returns an @code{int}, but many
4456 systems (e.g., @acronym{GNU} C Library version 2.2.4) provide a
4457 different version returning a @code{char *}.  @code{AC_FUNC_STRERROR_R}
4458 can detect which is in use (@pxref{Particular Functions}).
4460 @item @code{strnlen}
4461 @c @fuindex strnlen
4462 @prindex @code{strnlen}
4463 @acronym{AIX} 4.3 provides a broken version which produces the
4464 following results:
4466 @example
4467 strnlen ("foobar", 0) = 0
4468 strnlen ("foobar", 1) = 3
4469 strnlen ("foobar", 2) = 2
4470 strnlen ("foobar", 3) = 1
4471 strnlen ("foobar", 4) = 0
4472 strnlen ("foobar", 5) = 6
4473 strnlen ("foobar", 6) = 6
4474 strnlen ("foobar", 7) = 6
4475 strnlen ("foobar", 8) = 6
4476 strnlen ("foobar", 9) = 6
4477 @end example
4479 @item @code{sysconf}
4480 @c @fuindex sysconf
4481 @prindex @code{sysconf}
4482 @code{_SC_PAGESIZE} is standard, but some older systems (e.g., @acronym{HP-UX}
4483 9) have @code{_SC_PAGE_SIZE} instead.  This can be tested with
4484 @code{#ifdef}.
4486 @item @code{unlink}
4487 @c @fuindex unlink
4488 @prindex @code{unlink}
4489 The Posix spec says that @code{unlink} causes the given file to be
4490 removed only after there are no more open file handles for it.  Some
4491 non-Posix hosts have trouble with this requirement, though,
4492 and some @acronym{DOS} variants even corrupt the file system.
4494 @item @code{unsetenv}
4495 @c @fuindex unsetenv
4496 @prindex @code{unsetenv}
4497 On MinGW, @code{unsetenv} is not available, but a variable @samp{FOO}
4498 can be removed with a call @code{putenv ("FOO=")}, as described under
4499 @code{putenv} above.
4501 @item @code{va_copy}
4502 @c @fuindex va_copy
4503 @prindex @code{va_copy}
4504 The C99 standard provides @code{va_copy} for copying
4505 @code{va_list} variables.  It may be available in older environments
4506 too, though possibly as @code{__va_copy} (e.g., @command{gcc} in strict
4507 pre-C99 mode).  These can be tested with @code{#ifdef}.  A fallback to
4508 @code{memcpy (&dst, &src, sizeof (va_list))} gives maximum
4509 portability.
4511 @item @code{va_list}
4512 @c @fuindex va_list
4513 @prindex @code{va_list}
4514 @code{va_list} is not necessarily just a pointer.  It can be a
4515 @code{struct} (e.g., @command{gcc} on Alpha), which means @code{NULL} is
4516 not portable.  Or it can be an array (e.g., @command{gcc} in some
4517 PowerPC configurations), which means as a function parameter it can be
4518 effectively call-by-reference and library routines might modify the
4519 value back in the caller (e.g., @code{vsnprintf} in the @acronym{GNU} C Library
4520 2.1).
4522 @item Signed @code{>>}
4523 Normally the C @code{>>} right shift of a signed type replicates the
4524 high bit, giving a so-called ``arithmetic'' shift.  But care should be
4525 taken since Standard C doesn't require that behavior.  On those
4526 few processors without a native arithmetic shift (for instance Cray
4527 vector systems) zero bits may be shifted in, the same as a shift of an
4528 unsigned type.
4530 @item Integer @code{/}
4531 C divides signed integers by truncating their quotient toward zero,
4532 yielding the same result as Fortran.  However, before C99 the standard
4533 allowed C implementations to take the floor or ceiling of the quotient
4534 in some cases.  Hardly any implementations took advantage of this
4535 freedom, though, and it's probably not worth worrying about this issue
4536 nowadays.
4537 @end table
4540 @node Particular Functions
4541 @subsection Particular Function Checks
4542 @cindex Function, checking
4544 These macros check for particular C functions---whether they exist, and
4545 in some cases how they respond when given certain arguments.
4547 @anchor{AC_FUNC_ALLOCA}
4548 @defmac AC_FUNC_ALLOCA
4549 @acindex{FUNC_ALLOCA}
4550 @cvindex C_ALLOCA
4551 @cvindex HAVE_ALLOCA_H
4552 @ovindex ALLOCA
4553 @c @fuindex alloca
4554 @prindex @code{alloca}
4555 @hdrindex{alloca.h}
4556 Check how to get @code{alloca}.  Tries to get a builtin version by
4557 checking for @file{alloca.h} or the predefined C preprocessor macros
4558 @code{__GNUC__} and @code{_AIX}.  If this macro finds @file{alloca.h},
4559 it defines @code{HAVE_ALLOCA_H}.
4561 If those attempts fail, it looks for the function in the standard C
4562 library.  If any of those methods succeed, it defines
4563 @code{HAVE_ALLOCA}.  Otherwise, it sets the output variable
4564 @code{ALLOCA} to @samp{$@{LIBOBJDIR@}alloca.o} and defines
4565 @code{C_ALLOCA} (so programs can periodically call @samp{alloca (0)} to
4566 garbage collect).  This variable is separate from @code{LIBOBJS} so
4567 multiple programs can share the value of @code{ALLOCA} without needing
4568 to create an actual library, in case only some of them use the code in
4569 @code{LIBOBJS}.  The @samp{$@{LIBOBJDIR@}} prefix serves the same
4570 purpose as in @code{LIBOBJS} (@pxref{AC_LIBOBJ vs LIBOBJS}).
4572 This macro does not try to get @code{alloca} from the System V R3
4573 @file{libPW} or the System V R4 @file{libucb} because those libraries
4574 contain some incompatible functions that cause trouble.  Some versions
4575 do not even contain @code{alloca} or contain a buggy version.  If you
4576 still want to use their @code{alloca}, use @code{ar} to extract
4577 @file{alloca.o} from them instead of compiling @file{alloca.c}.
4579 Source files that use @code{alloca} should start with a piece of code
4580 like the following, to declare it properly.
4582 @example
4583 @group
4584 #ifdef HAVE_ALLOCA_H
4585 # include <alloca.h>
4586 #elif defined __GNUC__
4587 # define alloca __builtin_alloca
4588 #elif defined _AIX
4589 # define alloca __alloca
4590 #elif defined _MSC_VER
4591 # include <malloc.h>
4592 # define alloca _alloca
4593 #else
4594 # include <stddef.h>
4595 # ifdef  __cplusplus
4596 extern "C"
4597 # endif
4598 void *alloca (size_t);
4599 #endif
4600 @end group
4601 @end example
4602 @end defmac
4604 @defmac AC_FUNC_CHOWN
4605 @acindex{FUNC_CHOWN}
4606 @cvindex HAVE_CHOWN
4607 @c @fuindex chown
4608 @prindex @code{chown}
4609 If the @code{chown} function is available and works (in particular, it
4610 should accept @option{-1} for @code{uid} and @code{gid}), define
4611 @code{HAVE_CHOWN}.
4612 @end defmac
4614 @anchor{AC_FUNC_CLOSEDIR_VOID}
4615 @defmac AC_FUNC_CLOSEDIR_VOID
4616 @acindex{FUNC_CLOSEDIR_VOID}
4617 @cvindex CLOSEDIR_VOID
4618 @c @fuindex closedir
4619 @prindex @code{closedir}
4620 If the @code{closedir} function does not return a meaningful value,
4621 define @code{CLOSEDIR_VOID}.  Otherwise, callers ought to check its
4622 return value for an error indicator.
4624 Currently this test is implemented by running a test program.  When
4625 cross compiling the pessimistic assumption that @code{closedir} does not
4626 return a meaningful value is made.
4628 This macro is obsolescent, as @code{closedir} returns a meaningful value
4629 on current systems.  New programs need not use this macro.
4630 @end defmac
4632 @defmac AC_FUNC_ERROR_AT_LINE
4633 @acindex{FUNC_ERROR_AT_LINE}
4634 @c @fuindex error_at_line
4635 @prindex @code{error_at_line}
4636 If the @code{error_at_line} function is not found, require an
4637 @code{AC_LIBOBJ} replacement of @samp{error}.
4638 @end defmac
4640 @defmac AC_FUNC_FNMATCH
4641 @acindex{FUNC_FNMATCH}
4642 @c @fuindex fnmatch
4643 @prindex @code{fnmatch}
4644 If the @code{fnmatch} function conforms to Posix, define
4645 @code{HAVE_FNMATCH}.  Detect common implementation bugs, for example,
4646 the bugs in Solaris 2.4.
4648 Unlike the other specific
4649 @code{AC_FUNC} macros, @code{AC_FUNC_FNMATCH} does not replace a
4650 broken/missing @code{fnmatch}.  This is for historical reasons.
4651 See @code{AC_REPLACE_FNMATCH} below.
4653 This macro is obsolescent.  New programs should use Gnulib's
4654 @code{fnmatch-posix} module.  @xref{Gnulib}.
4655 @end defmac
4657 @defmac AC_FUNC_FNMATCH_GNU
4658 @acindex{FUNC_FNMATCH_GNU}
4659 @c @fuindex fnmatch
4660 @prindex @code{fnmatch}
4661 Behave like @code{AC_REPLACE_FNMATCH} (@emph{replace}) but also test
4662 whether @code{fnmatch} supports @acronym{GNU} extensions.  Detect common
4663 implementation bugs, for example, the bugs in the @acronym{GNU} C
4664 Library 2.1.
4666 This macro is obsolescent.  New programs should use Gnulib's
4667 @code{fnmatch-gnu} module.  @xref{Gnulib}.
4668 @end defmac
4670 @anchor{AC_FUNC_FORK}
4671 @defmac AC_FUNC_FORK
4672 @acindex{FUNC_FORK}
4673 @cvindex HAVE_VFORK_H
4674 @cvindex HAVE_WORKING_FORK
4675 @cvindex HAVE_WORKING_VFORK
4676 @cvindex vfork
4677 @c @fuindex fork
4678 @prindex @code{fork}
4679 @c @fuindex vfork
4680 @prindex @code{vfork}
4681 @hdrindex{vfork.h}
4682 This macro checks for the @code{fork} and @code{vfork} functions.  If a
4683 working @code{fork} is found, define @code{HAVE_WORKING_FORK}.  This macro
4684 checks whether @code{fork} is just a stub by trying to run it.
4686 If @file{vfork.h} is found, define @code{HAVE_VFORK_H}.  If a working
4687 @code{vfork} is found, define @code{HAVE_WORKING_VFORK}.  Otherwise,
4688 define @code{vfork} to be @code{fork} for backward compatibility with
4689 previous versions of @command{autoconf}.  This macro checks for several known
4690 errors in implementations of @code{vfork} and considers the system to not
4691 have a working @code{vfork} if it detects any of them.  It is not considered
4692 to be an implementation error if a child's invocation of @code{signal}
4693 modifies the parent's signal handler, since child processes rarely change
4694 their signal handlers.
4696 Since this macro defines @code{vfork} only for backward compatibility with
4697 previous versions of @command{autoconf} you're encouraged to define it
4698 yourself in new code:
4699 @example
4700 @group
4701 #ifndef HAVE_WORKING_VFORK
4702 # define vfork fork
4703 #endif
4704 @end group
4705 @end example
4706 @end defmac
4708 @defmac AC_FUNC_FSEEKO
4709 @acindex{FUNC_FSEEKO}
4710 @cvindex _LARGEFILE_SOURCE
4711 @cvindex HAVE_FSEEKO
4712 @c @fuindex fseeko
4713 @prindex @code{fseeko}
4714 @c @fuindex ftello
4715 @prindex @code{ftello}
4716 If the @code{fseeko} function is available, define @code{HAVE_FSEEKO}.
4717 Define @code{_LARGEFILE_SOURCE} if necessary to make the prototype
4718 visible on some systems (e.g., glibc 2.2).  Otherwise linkage problems
4719 may occur when compiling with @code{AC_SYS_LARGEFILE} on
4720 largefile-sensitive systems where @code{off_t} does not default to a
4721 64bit entity.  All systems with @code{fseeko} also supply @code{ftello}.
4722 @end defmac
4724 @defmac AC_FUNC_GETGROUPS
4725 @acindex{FUNC_GETGROUPS}
4726 @cvindex HAVE_GETGROUPS
4727 @ovindex GETGROUPS_LIBS
4728 @c @fuindex getgroups
4729 @prindex @code{getgroups}
4730 If the @code{getgroups} function is available and works (unlike on
4731 Ultrix 4.3, where @samp{getgroups (0, 0)} always fails), define
4732 @code{HAVE_GETGROUPS}.  Set @code{GETGROUPS_LIBS} to any libraries
4733 needed to get that function.  This macro runs @code{AC_TYPE_GETGROUPS}.
4734 @end defmac
4736 @anchor{AC_FUNC_GETLOADAVG}
4737 @defmac AC_FUNC_GETLOADAVG
4738 @acindex{FUNC_GETLOADAVG}
4739 @cvindex SVR4
4740 @cvindex DGUX
4741 @cvindex UMAX
4742 @cvindex UMAX4_3
4743 @cvindex HAVE_NLIST_H
4744 @cvindex NLIST_NAME_UNION
4745 @cvindex GETLOADAVG_PRIVILEGED
4746 @cvindex NEED_SETGID
4747 @cvindex C_GETLOADAVG
4748 @ovindex LIBOBJS
4749 @ovindex NEED_SETGID
4750 @ovindex KMEM_GROUP
4751 @ovindex GETLOADAVG_LIBS
4752 @c @fuindex getloadavg
4753 @prindex @code{getloadavg}
4754 Check how to get the system load averages.  To perform its tests
4755 properly, this macro needs the file @file{getloadavg.c}; therefore, be
4756 sure to set the @code{AC_LIBOBJ} replacement directory properly (see
4757 @ref{Generic Functions}, @code{AC_CONFIG_LIBOBJ_DIR}).
4759 If the system has the @code{getloadavg} function, define
4760 @code{HAVE_GETLOADAVG}, and set @code{GETLOADAVG_LIBS} to any libraries
4761 necessary to get that function.  Also add @code{GETLOADAVG_LIBS} to
4762 @code{LIBS}.  Otherwise, require an @code{AC_LIBOBJ} replacement for
4763 @samp{getloadavg} with source code in @file{@var{dir}/getloadavg.c}, and
4764 possibly define several other C preprocessor macros and output
4765 variables:
4767 @enumerate
4768 @item
4769 Define @code{C_GETLOADAVG}.
4771 @item
4772 Define @code{SVR4}, @code{DGUX}, @code{UMAX}, or @code{UMAX4_3} if on
4773 those systems.
4775 @item
4776 @hdrindex{nlist.h}
4777 If @file{nlist.h} is found, define @code{HAVE_NLIST_H}.
4779 @item
4780 If @samp{struct nlist} has an @samp{n_un.n_name} member, define
4781 @code{HAVE_STRUCT_NLIST_N_UN_N_NAME}.  The obsolete symbol
4782 @code{NLIST_NAME_UNION} is still defined, but do not depend upon it.
4784 @item
4785 Programs may need to be installed set-group-ID (or set-user-ID) for
4786 @code{getloadavg} to work.  In this case, define
4787 @code{GETLOADAVG_PRIVILEGED}, set the output variable @code{NEED_SETGID}
4788 to @samp{true} (and otherwise to @samp{false}), and set
4789 @code{KMEM_GROUP} to the name of the group that should own the installed
4790 program.
4791 @end enumerate
4793 The @code{AC_FUNC_GETLOADAVG} macro is obsolescent.  New programs should
4794 use Gnulib's @code{getloadavg} module.  @xref{Gnulib}.
4795 @end defmac
4797 @anchor{AC_FUNC_GETMNTENT}
4798 @defmac AC_FUNC_GETMNTENT
4799 @acindex{FUNC_GETMNTENT}
4800 @cvindex HAVE_GETMNTENT
4801 @c @fuindex getmntent
4802 @prindex @code{getmntent}
4803 Check for @code{getmntent} in the standard C library, and then in the
4804 @file{sun}, @file{seq}, and @file{gen} libraries, for @sc{unicos},
4805 @sc{irix} 4, @sc{ptx}, and UnixWare, respectively.  Then, if
4806 @code{getmntent} is available, define @code{HAVE_GETMNTENT}.
4807 @end defmac
4809 @defmac AC_FUNC_GETPGRP
4810 @acindex{FUNC_GETPGRP}
4811 @cvindex GETPGRP_VOID
4812 @c @fuindex getpgid
4813 @c @fuindex getpgrp
4814 @prindex @code{getpgid}
4815 @prindex @code{getpgrp}
4816 Define @code{GETPGRP_VOID} if it is an error to pass 0 to
4817 @code{getpgrp}; this is the Posix behavior.  On older @acronym{BSD}
4818 systems, you must pass 0 to @code{getpgrp}, as it takes an argument and
4819 behaves like Posix's @code{getpgid}.
4821 @example
4822 #ifdef GETPGRP_VOID
4823   pid = getpgrp ();
4824 #else
4825   pid = getpgrp (0);
4826 #endif
4827 @end example
4829 This macro does not check whether
4830 @code{getpgrp} exists at all; if you need to work in that situation,
4831 first call @code{AC_CHECK_FUNC} for @code{getpgrp}.
4833 This macro is obsolescent, as current systems have a @code{getpgrp}
4834 whose signature conforms to Posix.  New programs need not use this macro.
4835 @end defmac
4837 @defmac AC_FUNC_LSTAT_FOLLOWS_SLASHED_SYMLINK
4838 @acindex{FUNC_LSTAT_FOLLOWS_SLASHED_SYMLINK}
4839 @cvindex LSTAT_FOLLOWS_SLASHED_SYMLINK
4840 @c @fuindex lstat
4841 @prindex @code{lstat}
4842 If @file{link} is a symbolic link, then @code{lstat} should treat
4843 @file{link/} the same as @file{link/.}.  However, many older
4844 @code{lstat} implementations incorrectly ignore trailing slashes.
4846 It is safe to assume that if @code{lstat} incorrectly ignores
4847 trailing slashes, then other symbolic-link-aware functions like
4848 @code{unlink} also incorrectly ignore trailing slashes.
4850 If @code{lstat} behaves properly, define
4851 @code{LSTAT_FOLLOWS_SLASHED_SYMLINK}, otherwise require an
4852 @code{AC_LIBOBJ} replacement of @code{lstat}.
4853 @end defmac
4855 @defmac AC_FUNC_MALLOC
4856 @acindex{FUNC_MALLOC}
4857 @cvindex HAVE_MALLOC
4858 @cvindex malloc
4859 @c @fuindex malloc
4860 @prindex @code{malloc}
4861 If the @code{malloc} function is compatible with the @acronym{GNU} C
4862 library @code{malloc} (i.e., @samp{malloc (0)} returns a valid
4863 pointer), define @code{HAVE_MALLOC} to 1.  Otherwise define
4864 @code{HAVE_MALLOC} to 0, ask for an @code{AC_LIBOBJ} replacement for
4865 @samp{malloc}, and define @code{malloc} to @code{rpl_malloc} so that the
4866 native @code{malloc} is not used in the main project.
4868 Typically, the replacement file @file{malloc.c} should look like (note
4869 the @samp{#undef malloc}):
4871 @verbatim
4872 #include <config.h>
4873 #undef malloc
4875 #include <sys/types.h>
4877 void *malloc ();
4879 /* Allocate an N-byte block of memory from the heap.
4880    If N is zero, allocate a 1-byte block.  */
4882 void *
4883 rpl_malloc (size_t n)
4885   if (n == 0)
4886     n = 1;
4887   return malloc (n);
4889 @end verbatim
4890 @end defmac
4892 @defmac AC_FUNC_MEMCMP
4893 @acindex{FUNC_MEMCMP}
4894 @ovindex LIBOBJS
4895 @c @fuindex memcmp
4896 @prindex @code{memcmp}
4897 If the @code{memcmp} function is not available, or does not work on
4898 8-bit data (like the one on SunOS 4.1.3), or fails when comparing 16
4899 bytes or more and with at least one buffer not starting on a 4-byte
4900 boundary (such as the one on NeXT x86 OpenStep), require an
4901 @code{AC_LIBOBJ} replacement for @samp{memcmp}.
4903 This macro is obsolescent, as current systems have a working
4904 @code{memcmp}.  New programs need not use this macro.
4905 @end defmac
4907 @defmac AC_FUNC_MBRTOWC
4908 @acindex{FUNC_MBRTOWC}
4909 @cvindex HAVE_MBRTOWC
4910 @c @fuindex mbrtowc
4911 @prindex @code{mbrtowc}
4912 Define @code{HAVE_MBRTOWC} to 1 if the function @code{mbrtowc} and the
4913 type @code{mbstate_t} are properly declared.
4914 @end defmac
4916 @defmac AC_FUNC_MKTIME
4917 @acindex{FUNC_MKTIME}
4918 @ovindex LIBOBJS
4919 @c @fuindex mktime
4920 @prindex @code{mktime}
4921 If the @code{mktime} function is not available, or does not work
4922 correctly, require an @code{AC_LIBOBJ} replacement for @samp{mktime}.
4923 For the purposes of this test, @code{mktime} should conform to the
4924 Posix standard and should be the inverse of
4925 @code{localtime}.
4926 @end defmac
4928 @anchor{AC_FUNC_MMAP}
4929 @defmac AC_FUNC_MMAP
4930 @acindex{FUNC_MMAP}
4931 @cvindex HAVE_MMAP
4932 @c @fuindex mmap
4933 @prindex @code{mmap}
4934 If the @code{mmap} function exists and works correctly, define
4935 @code{HAVE_MMAP}.  This checks only private fixed mapping of already-mapped
4936 memory.
4937 @end defmac
4939 @defmac AC_FUNC_OBSTACK
4940 @acindex{FUNC_OBSTACK}
4941 @cvindex HAVE_OBSTACK
4942 @cindex obstack
4943 If the obstacks are found, define @code{HAVE_OBSTACK}, else require an
4944 @code{AC_LIBOBJ} replacement for @samp{obstack}.
4945 @end defmac
4947 @defmac AC_FUNC_REALLOC
4948 @acindex{FUNC_REALLOC}
4949 @cvindex HAVE_REALLOC
4950 @cvindex realloc
4951 @c @fuindex realloc
4952 @prindex @code{realloc}
4953 If the @code{realloc} function is compatible with the @acronym{GNU} C
4954 library @code{realloc} (i.e., @samp{realloc (NULL, 0)} returns a
4955 valid pointer), define @code{HAVE_REALLOC} to 1.  Otherwise define
4956 @code{HAVE_REALLOC} to 0, ask for an @code{AC_LIBOBJ} replacement for
4957 @samp{realloc}, and define @code{realloc} to @code{rpl_realloc} so that
4958 the native @code{realloc} is not used in the main project.  See
4959 @code{AC_FUNC_MALLOC} for details.
4960 @end defmac
4962 @defmac AC_FUNC_SELECT_ARGTYPES
4963 @acindex{FUNC_SELECT_ARGTYPES}
4964 @cvindex SELECT_TYPE_ARG1
4965 @cvindex SELECT_TYPE_ARG234
4966 @cvindex SELECT_TYPE_ARG5
4967 @c @fuindex select
4968 @prindex @code{select}
4969 Determines the correct type to be passed for each of the
4970 @code{select} function's arguments, and defines those types
4971 in @code{SELECT_TYPE_ARG1}, @code{SELECT_TYPE_ARG234}, and
4972 @code{SELECT_TYPE_ARG5} respectively.  @code{SELECT_TYPE_ARG1} defaults
4973 to @samp{int}, @code{SELECT_TYPE_ARG234} defaults to @samp{int *},
4974 and @code{SELECT_TYPE_ARG5} defaults to @samp{struct timeval *}.
4976 This macro is obsolescent, as current systems have a @code{select} whose
4977 signature conforms to Posix.  New programs need not use this macro.
4978 @end defmac
4980 @defmac AC_FUNC_SETPGRP
4981 @acindex{FUNC_SETPGRP}
4982 @cvindex SETPGRP_VOID
4983 @c @fuindex setpgrp
4984 @prindex @code{setpgrp}
4985 If @code{setpgrp} takes no argument (the Posix version), define
4986 @code{SETPGRP_VOID}.  Otherwise, it is the @acronym{BSD} version, which takes
4987 two process IDs as arguments.  This macro does not check whether
4988 @code{setpgrp} exists at all; if you need to work in that situation,
4989 first call @code{AC_CHECK_FUNC} for @code{setpgrp}.
4991 This macro is obsolescent, as current systems have a @code{setpgrp}
4992 whose signature conforms to Posix.  New programs need not use this macro.
4993 @end defmac
4995 @defmac AC_FUNC_STAT
4996 @defmacx AC_FUNC_LSTAT
4997 @acindex{FUNC_STAT}
4998 @acindex{FUNC_LSTAT}
4999 @cvindex HAVE_STAT_EMPTY_STRING_BUG
5000 @cvindex HAVE_LSTAT_EMPTY_STRING_BUG
5001 @c @fuindex stat
5002 @prindex @code{stat}
5003 @c @fuindex lstat
5004 @prindex @code{lstat}
5005 Determine whether @code{stat} or @code{lstat} have the bug that it
5006 succeeds when given the zero-length file name as argument.  The @code{stat}
5007 and @code{lstat} from SunOS 4.1.4 and the Hurd (as of 1998-11-01) do
5008 this.
5010 If it does, then define @code{HAVE_STAT_EMPTY_STRING_BUG} (or
5011 @code{HAVE_LSTAT_EMPTY_STRING_BUG}) and ask for an @code{AC_LIBOBJ}
5012 replacement of it.
5014 These macros are obsolescent, as no current systems have the bug.
5015 New programs need not use these macros.
5016 @end defmac
5018 @anchor{AC_FUNC_STRCOLL}
5019 @defmac AC_FUNC_STRCOLL
5020 @acindex{FUNC_STRCOLL}
5021 @cvindex HAVE_STRCOLL
5022 @c @fuindex strcoll
5023 @prindex @code{strcoll}
5024 If the @code{strcoll} function exists and works correctly, define
5025 @code{HAVE_STRCOLL}.  This does a bit more than
5026 @samp{AC_CHECK_FUNCS(strcoll)}, because some systems have incorrect
5027 definitions of @code{strcoll} that should not be used.
5028 @end defmac
5030 @defmac AC_FUNC_STRERROR_R
5031 @acindex{FUNC_STRERROR_R}
5032 @cvindex HAVE_STRERROR_R
5033 @cvindex HAVE_DECL_STRERROR_R
5034 @cvindex STRERROR_R_CHAR_P
5035 @c @fuindex strerror_r
5036 @prindex @code{strerror_r}
5037 If @code{strerror_r} is available, define @code{HAVE_STRERROR_R}, and if
5038 it is declared, define @code{HAVE_DECL_STRERROR_R}.  If it returns a
5039 @code{char *} message, define @code{STRERROR_R_CHAR_P}; otherwise it
5040 returns an @code{int} error number.  The Thread-Safe Functions option of
5041 Posix requires @code{strerror_r} to return @code{int}, but
5042 many systems (including, for example, version 2.2.4 of the @acronym{GNU} C
5043 Library) return a @code{char *} value that is not necessarily equal to
5044 the buffer argument.
5045 @end defmac
5047 @anchor{AC_FUNC_STRFTIME}
5048 @defmac AC_FUNC_STRFTIME
5049 @acindex{FUNC_STRFTIME}
5050 @cvindex HAVE_STRFTIME
5051 @c @fuindex strftime
5052 @prindex @code{strftime}
5053 Check for @code{strftime} in the @file{intl} library, for SCO Unix.
5054 Then, if @code{strftime} is available, define @code{HAVE_STRFTIME}.
5056 This macro is obsolescent, as no current systems require the @file{intl}
5057 library for @code{strftime}.  New programs need not use this macro.
5058 @end defmac
5060 @defmac AC_FUNC_STRTOD
5061 @acindex{FUNC_STRTOD}
5062 @ovindex POW_LIB
5063 @c @fuindex strtod
5064 @prindex @code{strtod}
5065 If the @code{strtod} function does not exist or doesn't work correctly,
5066 ask for an @code{AC_LIBOBJ} replacement of @samp{strtod}.  In this case,
5067 because @file{strtod.c} is likely to need @samp{pow}, set the output
5068 variable @code{POW_LIB} to the extra library needed.
5069 @end defmac
5071 @defmac AC_FUNC_STRTOLD
5072 @acindex{FUNC_STRTOLD}
5073 @cvindex HAVE_STRTOLD
5074 @prindex @code{strtold}
5075 If the @code{strtold} function exists and conforms to C99, define
5076 @code{HAVE_STRTOLD}.
5077 @end defmac
5079 @defmac AC_FUNC_STRNLEN
5080 @acindex{FUNC_STRNLEN}
5081 @cvindex HAVE_STRNLEN
5082 @c @fuindex strnlen
5083 @prindex @code{strnlen}
5084 If the @code{strnlen} function is not available, or is buggy (like the one
5085 from @acronym{AIX} 4.3), require an @code{AC_LIBOBJ} replacement for it.
5086 @end defmac
5088 @anchor{AC_FUNC_UTIME_NULL}
5089 @defmac AC_FUNC_UTIME_NULL
5090 @acindex{FUNC_UTIME_NULL}
5091 @cvindex HAVE_UTIME_NULL
5092 @c @fuindex utime
5093 @prindex @code{utime}
5094 If @samp{utime (@var{file}, NULL)} sets @var{file}'s timestamp to
5095 the present, define @code{HAVE_UTIME_NULL}.
5097 This macro is obsolescent, as all current systems have a @code{utime}
5098 that behaves this way.  New programs need not use this macro.
5099 @end defmac
5101 @anchor{AC_FUNC_VPRINTF}
5102 @defmac AC_FUNC_VPRINTF
5103 @acindex{FUNC_VPRINTF}
5104 @cvindex HAVE_VPRINTF
5105 @cvindex HAVE_DOPRNT
5106 @c @fuindex vprintf
5107 @prindex @code{vprintf}
5108 @c @fuindex vsprintf
5109 @prindex @code{vsprintf}
5110 If @code{vprintf} is found, define @code{HAVE_VPRINTF}.  Otherwise, if
5111 @code{_doprnt} is found, define @code{HAVE_DOPRNT}.  (If @code{vprintf}
5112 is available, you may assume that @code{vfprintf} and @code{vsprintf}
5113 are also available.)
5115 This macro is obsolescent, as all current systems have @code{vprintf}.
5116 New programs need not use this macro.
5117 @end defmac
5119 @defmac AC_REPLACE_FNMATCH
5120 @acindex{REPLACE_FNMATCH}
5121 @c @fuindex fnmatch
5122 @prindex @code{fnmatch}
5123 @hdrindex{fnmatch.h}
5124 If the @code{fnmatch} function does not conform to Posix (see
5125 @code{AC_FUNC_FNMATCH}), ask for its @code{AC_LIBOBJ} replacement.
5127 The files @file{fnmatch.c}, @file{fnmatch_loop.c}, and @file{fnmatch_.h}
5128 in the @code{AC_LIBOBJ} replacement directory are assumed to contain a
5129 copy of the source code of @acronym{GNU} @code{fnmatch}.  If necessary,
5130 this source code is compiled as an @code{AC_LIBOBJ} replacement, and the
5131 @file{fnmatch_.h} file is linked to @file{fnmatch.h} so that it can be
5132 included in place of the system @code{<fnmatch.h>}.
5134 This macro is obsolescent, as it assumes the use of particular source
5135 files.  New programs should use Gnulib's @code{fnmatch-posix} module,
5136 which provides this macro along with the source files.  @xref{Gnulib}.
5137 @end defmac
5141 @node Generic Functions
5142 @subsection Generic Function Checks
5144 These macros are used to find functions not covered by the ``particular''
5145 test macros.  If the functions might be in libraries other than the
5146 default C library, first call @code{AC_CHECK_LIB} for those libraries.
5147 If you need to check the behavior of a function as well as find out
5148 whether it is present, you have to write your own test for
5149 it (@pxref{Writing Tests}).
5151 @anchor{AC_CHECK_FUNC}
5152 @defmac AC_CHECK_FUNC (@var{function}, @ovar{action-if-found}, @
5153   @ovar{action-if-not-found})
5154 @acindex{CHECK_FUNC}
5155 If C function @var{function} is available, run shell commands
5156 @var{action-if-found}, otherwise @var{action-if-not-found}.  If you just
5157 want to define a symbol if the function is available, consider using
5158 @code{AC_CHECK_FUNCS} instead.  This macro checks for functions with C
5159 linkage even when @code{AC_LANG(C++)} has been called, since C is more
5160 standardized than C++.  (@pxref{Language Choice}, for more information
5161 about selecting the language for checks.)
5162 @end defmac
5164 @anchor{AC_CHECK_FUNCS}
5165 @defmac AC_CHECK_FUNCS (@var{function}@dots{}, @ovar{action-if-found}, @
5166   @ovar{action-if-not-found})
5167 @acindex{CHECK_FUNCS}
5168 @cvindex HAVE_@var{function}
5169 For each @var{function} enumerated in the blank-or-newline-separated argument
5170 list, define @code{HAVE_@var{function}} (in all capitals) if it is available.
5171 If @var{action-if-found} is given, it is additional shell code to
5172 execute when one of the functions is found.  You can give it a value of
5173 @samp{break} to break out of the loop on the first match.  If
5174 @var{action-if-not-found} is given, it is executed when one of the
5175 functions is not found.
5176 @end defmac
5178 @defmac AC_CHECK_FUNCS_ONCE (@var{function}@dots{})
5179 @acindex{CHECK_FUNCS_ONCE}
5180 @cvindex HAVE_@var{function}
5181 For each @var{function} enumerated in the blank-or-newline-separated argument
5182 list, define @code{HAVE_@var{function}} (in all capitals) if it is available.
5183 This is a once-only variant of @code{AC_CHECK_FUNCS}.  It generates the
5184 checking code at most once, so that @command{configure} is smaller and
5185 faster; but the checks cannot be conditionalized and are always done once,
5186 early during the @command{configure} run.
5187 @end defmac
5189 @sp 1
5191 Autoconf follows a philosophy that was formed over the years by those
5192 who have struggled for portability: isolate the portability issues in
5193 specific files, and then program as if you were in a Posix
5194 environment.  Some functions may be missing or unfixable, and your
5195 package must be ready to replace them.
5197 Suitable replacements for many such problem functions are available from
5198 Gnulib (@pxref{Gnulib}).
5200 @defmac AC_LIBOBJ (@var{function})
5201 @acindex{LIBOBJ}
5202 @ovindex LIBOBJS
5203 Specify that @samp{@var{function}.c} must be included in the executables
5204 to replace a missing or broken implementation of @var{function}.
5206 Technically, it adds @samp{@var{function}.$ac_objext} to the output
5207 variable @code{LIBOBJS} if it is not already in, and calls
5208 @code{AC_LIBSOURCE} for @samp{@var{function}.c}.  You should not
5209 directly change @code{LIBOBJS}, since this is not traceable.
5210 @end defmac
5212 @defmac AC_LIBSOURCE (@var{file})
5213 @acindex{LIBSOURCE}
5214 Specify that @var{file} might be needed to compile the project.  If you
5215 need to know what files might be needed by a @file{configure.ac}, you
5216 should trace @code{AC_LIBSOURCE}.  @var{file} must be a literal.
5218 This macro is called automatically from @code{AC_LIBOBJ}, but you must
5219 call it explicitly if you pass a shell variable to @code{AC_LIBOBJ}.  In
5220 that case, since shell variables cannot be traced statically, you must
5221 pass to @code{AC_LIBSOURCE} any possible files that the shell variable
5222 might cause @code{AC_LIBOBJ} to need.  For example, if you want to pass
5223 a variable @code{$foo_or_bar} to @code{AC_LIBOBJ} that holds either
5224 @code{"foo"} or @code{"bar"}, you should do:
5226 @example
5227 AC_LIBSOURCE([foo.c])
5228 AC_LIBSOURCE([bar.c])
5229 AC_LIBOBJ([$foo_or_bar])
5230 @end example
5232 @noindent
5233 There is usually a way to avoid this, however, and you are encouraged to
5234 simply call @code{AC_LIBOBJ} with literal arguments.
5236 Note that this macro replaces the obsolete @code{AC_LIBOBJ_DECL}, with
5237 slightly different semantics: the old macro took the function name,
5238 e.g., @code{foo}, as its argument rather than the file name.
5239 @end defmac
5241 @defmac AC_LIBSOURCES (@var{files})
5242 @acindex{LIBSOURCES}
5243 Like @code{AC_LIBSOURCE}, but accepts one or more @var{files} in a
5244 comma-separated M4 list.  Thus, the above example might be rewritten:
5246 @example
5247 AC_LIBSOURCES([foo.c, bar.c])
5248 AC_LIBOBJ([$foo_or_bar])
5249 @end example
5250 @end defmac
5252 @defmac AC_CONFIG_LIBOBJ_DIR (@var{directory})
5253 @acindex{CONFIG_LIBOBJ_DIR}
5254 Specify that @code{AC_LIBOBJ} replacement files are to be found in
5255 @var{directory}, a name relative to the top level of the
5256 source tree.  The replacement directory defaults to @file{.}, the top
5257 level directory, and the most typical value is @file{lib}, corresponding
5258 to @samp{AC_CONFIG_LIBOBJ_DIR([lib])}.
5260 @command{configure} might need to know the replacement directory for the
5261 following reasons: (i) some checks use the replacement files, (ii) some
5262 macros bypass broken system headers by installing links to the
5263 replacement headers (iii) when used in conjunction with Automake,
5264 within each makefile, @var{directory} is used as a relative path
5265 from @code{$(top_srcdir)} to each object named in @code{LIBOBJS} and
5266 @code{LTLIBOBJS}, etc.
5267 @end defmac
5269 @sp 1
5271 It is common to merely check for the existence of a function, and ask
5272 for its @code{AC_LIBOBJ} replacement if missing.  The following macro is
5273 a convenient shorthand.
5275 @defmac AC_REPLACE_FUNCS (@var{function}@dots{})
5276 @acindex{REPLACE_FUNCS}
5277 @cvindex HAVE_@var{function}
5278 @ovindex LIBOBJS
5279 Like @code{AC_CHECK_FUNCS}, but uses @samp{AC_LIBOBJ(@var{function})} as
5280 @var{action-if-not-found}.  You can declare your replacement function by
5281 enclosing the prototype in @samp{#ifndef HAVE_@var{function}}.  If the
5282 system has the function, it probably declares it in a header file you
5283 should be including, so you shouldn't redeclare it lest your declaration
5284 conflict.
5285 @end defmac
5287 @node Header Files
5288 @section Header Files
5289 @cindex Header, checking
5291 The following macros check for the presence of certain C header files.
5292 If there is no macro specifically defined to check for a header file you need,
5293 and you don't need to check for any special properties of
5294 it, then you can use one of the general header-file check macros.
5296 @menu
5297 * Header Portability::          Collected knowledge on common headers
5298 * Particular Headers::          Special handling to find certain headers
5299 * Generic Headers::             How to find other headers
5300 @end menu
5302 @node Header Portability
5303 @subsection Portability of Headers
5304 @cindex Portability of headers
5305 @cindex Header portability
5307 This section tries to collect knowledge about common headers, and the
5308 problems they cause.  By definition, this list always requires
5309 additions.  Please help us keeping it as complete as possible.
5311 @table @asis
5313 @item @file{limits.h}
5314 C99 says that @file{limits.h} defines @code{LLONG_MIN},
5315 @code{LLONG_MAX}, and @code{ULLONG_MAX}, but many almost-C99
5316 environments (e.g., default @acronym{GCC} 4.0.2 + glibc 2.4) do not
5317 define them.
5319 @item @file{inttypes.h} vs.@: @file{stdint.h}
5320 @hdrindex{inttypes.h}
5321 @hdrindex{stdint.h}
5322 The C99 standard says that @file{inttypes.h} includes
5323 @file{stdint.h}, so there's no need to include @file{stdint.h}
5324 separately in a standard environment.  Some implementations have
5325 @file{inttypes.h} but not @file{stdint.h} (e.g., Solaris 7), but we don't
5326 know of any implementation that has @file{stdint.h} but not
5327 @file{inttypes.h}.
5329 @item @file{linux/irda.h}
5330 @hdrindex{linux/irda.h}
5331 It requires @file{linux/types.h} and @file{sys/socket.h}.
5333 @item @file{linux/random.h}
5334 @hdrindex{linux/random.h}
5335 It requires @file{linux/types.h}.
5337 @item @file{net/if.h}
5338 @hdrindex{net/if.h}
5339 On Darwin, this file requires that @file{sys/socket.h} be included
5340 beforehand.  One should run:
5342 @example
5343 AC_CHECK_HEADERS([sys/socket.h])
5344 AC_CHECK_HEADERS([net/if.h], [], [],
5345 [#include <stdio.h>
5346 #ifdef STDC_HEADERS
5347 # include <stdlib.h>
5348 # include <stddef.h>
5349 #else
5350 # ifdef HAVE_STDLIB_H
5351 #  include <stdlib.h>
5352 # endif
5353 #endif
5354 #ifdef HAVE_SYS_SOCKET_H
5355 # include <sys/socket.h>
5356 #endif
5358 @end example
5360 @item @file{netinet/if_ether.h}
5361 @hdrindex{netinet/if_ether.h}
5362 On Darwin, this file requires that @file{stdio.h} and
5363 @file{sys/socket.h} be included beforehand.  One should run:
5365 @example
5366 AC_CHECK_HEADERS([sys/socket.h])
5367 AC_CHECK_HEADERS([netinet/if_ether.h], [], [],
5368 [#include <stdio.h>
5369 #ifdef STDC_HEADERS
5370 # include <stdlib.h>
5371 # include <stddef.h>
5372 #else
5373 # ifdef HAVE_STDLIB_H
5374 #  include <stdlib.h>
5375 # endif
5376 #endif
5377 #ifdef HAVE_SYS_SOCKET_H
5378 # include <sys/socket.h>
5379 #endif
5381 @end example
5383 @item @file{stdint.h}
5384 See above, item @file{inttypes.h} vs.@: @file{stdint.h}.
5386 @item @file{stdlib.h}
5387 @hdrindex{stdlib.h}
5388 On many systems (e.g., Darwin), @file{stdio.h} is a prerequisite.
5390 @item @file{sys/mount.h}
5391 @hdrindex{sys/mount.h}
5392 On Free@acronym{BSD} 4.8 on ia32 and using gcc version 2.95.4,
5393 @file{sys/params.h} is a prerequisite.
5395 @item @file{sys/ptem.h}
5396 @hdrindex{sys/ptem.h}
5397 On Solaris 8, @file{sys/stream.h} is a prerequisite.
5399 @item @file{sys/socket.h}
5400 @hdrindex{sys/socket.h}
5401 On Darwin, @file{stdlib.h} is a prerequisite.
5403 @item @file{sys/ucred.h}
5404 @hdrindex{sys/ucred.h}
5405 On Tru64 5.1, @file{sys/types.h} is a prerequisite.
5407 @item @file{X11/extensions/scrnsaver.h}
5408 @hdrindex{X11/extensions/scrnsaver.h}
5409 Using XFree86, this header requires @file{X11/Xlib.h}, which is probably
5410 so required that you might not even consider looking for it.
5412 @example
5413 AC_CHECK_HEADERS([X11/extensions/scrnsaver.h], [], [],
5414 [[#include <X11/Xlib.h>
5416 @end example
5417 @end table
5420 @node Particular Headers
5421 @subsection Particular Header Checks
5423 These macros check for particular system header files---whether they
5424 exist, and in some cases whether they declare certain symbols.
5426 @defmac AC_HEADER_ASSERT
5427 @acindex{HEADER_ASSERT}
5428 @cvindex NDEBUG
5429 @hdrindex{assert.h}
5430 Check whether to enable assertions in the style of @file{assert.h}.
5431 Assertions are enabled by default, but the user can override this by
5432 invoking @command{configure} with the @option{--disable-assert} option.
5433 @end defmac
5435 @anchor{AC_HEADER_DIRENT}
5436 @defmac AC_HEADER_DIRENT
5437 @acindex{HEADER_DIRENT}
5438 @cvindex HAVE_DIRENT_H
5439 @cvindex HAVE_NDIR_H
5440 @cvindex HAVE_SYS_DIR_H
5441 @cvindex HAVE_SYS_NDIR_H
5442 @hdrindex{dirent.h}
5443 @hdrindex{sys/ndir.h}
5444 @hdrindex{sys/dir.h}
5445 @hdrindex{ndir.h}
5446 Check for the following header files.  For the first one that is
5447 found and defines @samp{DIR}, define the listed C preprocessor macro:
5449 @multitable {@file{sys/ndir.h}} {@code{HAVE_SYS_NDIR_H}}
5450 @item @file{dirent.h}   @tab @code{HAVE_DIRENT_H}
5451 @item @file{sys/ndir.h} @tab @code{HAVE_SYS_NDIR_H}
5452 @item @file{sys/dir.h}  @tab @code{HAVE_SYS_DIR_H}
5453 @item @file{ndir.h}     @tab @code{HAVE_NDIR_H}
5454 @end multitable
5456 The directory-library declarations in your source code should look
5457 something like the following:
5459 @example
5460 @group
5461 #include <sys/types.h>
5462 #ifdef HAVE_DIRENT_H
5463 # include <dirent.h>
5464 # define NAMLEN(dirent) strlen ((dirent)->d_name)
5465 #else
5466 # define dirent direct
5467 # define NAMLEN(dirent) ((dirent)->d_namlen)
5468 # ifdef HAVE_SYS_NDIR_H
5469 #  include <sys/ndir.h>
5470 # endif
5471 # ifdef HAVE_SYS_DIR_H
5472 #  include <sys/dir.h>
5473 # endif
5474 # ifdef HAVE_NDIR_H
5475 #  include <ndir.h>
5476 # endif
5477 #endif
5478 @end group
5479 @end example
5481 Using the above declarations, the program would declare variables to be
5482 of type @code{struct dirent}, not @code{struct direct}, and would access
5483 the length of a directory entry name by passing a pointer to a
5484 @code{struct dirent} to the @code{NAMLEN} macro.
5486 This macro also checks for the SCO Xenix @file{dir} and @file{x} libraries.
5488 This macro is obsolescent, as all current systems with directory
5489 libraries have @code{<dirent.h>}.  New programs need not use this macro.
5491 Also see @code{AC_STRUCT_DIRENT_D_INO} and
5492 @code{AC_STRUCT_DIRENT_D_TYPE} (@pxref{Particular Structures}).
5493 @end defmac
5495 @anchor{AC_HEADER_MAJOR}
5496 @defmac AC_HEADER_MAJOR
5497 @acindex{HEADER_MAJOR}
5498 @cvindex MAJOR_IN_MKDEV
5499 @cvindex MAJOR_IN_SYSMACROS
5500 @hdrindex{sys/mkdev.h}
5501 @hdrindex{sys/sysmacros.h}
5502 If @file{sys/types.h} does not define @code{major}, @code{minor}, and
5503 @code{makedev}, but @file{sys/mkdev.h} does, define
5504 @code{MAJOR_IN_MKDEV}; otherwise, if @file{sys/sysmacros.h} does, define
5505 @code{MAJOR_IN_SYSMACROS}.
5506 @end defmac
5508 @defmac AC_HEADER_RESOLV
5509 @acindex{HEADER_RESOLV}
5510 @cvindex HAVE_RESOLV_H
5511 @hdrindex{resolv.h}
5512 Checks for header @file{resolv.h}, checking for prerequisites first.
5513 To properly use @file{resolv.h}, your code should contain something like
5514 the following:
5516 @verbatim
5517 #ifdef HAVE_SYS_TYPES_H
5518 #  include <sys/types.h>
5519 #endif
5520 #ifdef HAVE_NETINET_IN_H
5521 #  include <netinet/in.h>   /* inet_ functions / structs */
5522 #endif
5523 #ifdef HAVE_ARPA_NAMESER_H
5524 #  include <arpa/nameser.h> /* DNS HEADER struct */
5525 #endif
5526 #ifdef HAVE_NETDB_H
5527 #  include <netdb.h>
5528 #endif
5529 #include <resolv.h>
5530 @end verbatim
5531 @end defmac
5533 @anchor{AC_HEADER_STAT}
5534 @defmac AC_HEADER_STAT
5535 @acindex{HEADER_STAT}
5536 @cvindex STAT_MACROS_BROKEN
5537 @hdrindex{sys/stat.h}
5538 If the macros @code{S_ISDIR}, @code{S_ISREG}, etc.@: defined in
5539 @file{sys/stat.h} do not work properly (returning false positives),
5540 define @code{STAT_MACROS_BROKEN}.  This is the case on Tektronix UTekV,
5541 Amdahl UTS and Motorola System V/88.
5543 This macro is obsolescent, as no current systems have the bug.
5544 New programs need not use this macro.
5545 @end defmac
5547 @defmac AC_HEADER_STDBOOL
5548 @acindex{HEADER_STDBOOL}
5549 @cvindex HAVE_STDBOOL_H
5550 @cvindex HAVE__BOOL
5551 @hdrindex{stdbool.h}
5552 @hdrindex{system.h}
5553 If @file{stdbool.h} exists and conforms to C99, define
5554 @code{HAVE_STDBOOL_H} to 1; if the type @code{_Bool} is defined, define
5555 @code{HAVE__BOOL} to 1.  To fulfill the C99 requirements, your
5556 @file{system.h} could contain the following code:
5558 @verbatim
5559 #ifdef HAVE_STDBOOL_H
5560 # include <stdbool.h>
5561 #else
5562 # ifndef HAVE__BOOL
5563 #  ifdef __cplusplus
5564 typedef bool _Bool;
5565 #  else
5566 #   define _Bool signed char
5567 #  endif
5568 # endif
5569 # define bool _Bool
5570 # define false 0
5571 # define true 1
5572 # define __bool_true_false_are_defined 1
5573 #endif
5574 @end verbatim
5576 Alternatively you can use the @samp{stdbool} package of Gnulib
5577 (@pxref{Gnulib}); it packages the above code into a replacement header
5578 and contains a few other bells and whistles.
5580 @end defmac
5582 @anchor{AC_HEADER_STDC}
5583 @defmac AC_HEADER_STDC
5584 @acindex{HEADER_STDC}
5585 @cvindex STDC_HEADERS
5586 @hdrindex{stdlib.h}
5587 @hdrindex{stdarg.h}
5588 @hdrindex{string.h}
5589 @hdrindex{float.h}
5590 @hdrindex{ctype.h}
5591 Define @code{STDC_HEADERS} if the system has C header files
5592 conforming to @acronym{ANSI} C89 (@acronym{ISO} C90).
5593 Specifically, this macro checks for @file{stdlib.h}, @file{stdarg.h},
5594 @file{string.h}, and @file{float.h}; if the system has those, it
5595 probably has the rest of the C89 header files.  This macro also
5596 checks whether @file{string.h} declares @code{memchr} (and thus
5597 presumably the other @code{mem} functions), whether @file{stdlib.h}
5598 declare @code{free} (and thus presumably @code{malloc} and other related
5599 functions), and whether the @file{ctype.h} macros work on characters
5600 with the high bit set, as the C standard requires.
5602 If you use this macro, your code can refer to @code{STDC_HEADERS} to
5603 determine whether the system has conforming header files (and probably C
5604 library functions).
5606 This macro is obsolescent, as current systems have conforming header
5607 files.  New programs need not use this macro.
5609 @hdrindex{string.h}
5610 @hdrindex{strings.h}
5611 Nowadays @file{string.h} is part of the C standard and declares functions like
5612 @code{strcpy}, and @file{strings.h} is standardized by Posix and declares
5613 @acronym{BSD} functions like @code{bcopy}; but
5614 historically, string functions were a major sticking point in this area.
5615 If you still want to worry about portability to ancient systems without
5616 standard headers, there is so much variation
5617 that it is probably easier to declare the functions you use than to
5618 figure out exactly what the system header files declare.  Some ancient systems
5619 contained a mix of functions from the C standard and from @acronym{BSD};
5620 some were mostly standard but lacked @samp{memmove}; some defined the
5621 @acronym{BSD} functions as macros in @file{string.h} or
5622 @file{strings.h}; some had only the @acronym{BSD} functions but
5623 @file{string.h}; some declared the memory functions in @file{memory.h},
5624 some in @file{string.h}; etc.  It is probably sufficient to check for
5625 one string function and one memory function; if the library had the
5626 standard versions of those then it probably had most of the others.
5627 If you put the following in @file{configure.ac}:
5629 @example
5630 # This example is obsolescent.
5631 # Nowadays you can omit these macro calls.
5632 AC_HEADER_STDC
5633 AC_CHECK_FUNCS([strchr memcpy])
5634 @end example
5636 @noindent
5637 then, in your code, you can use declarations like this:
5639 @example
5640 @group
5641 /* This example is obsolescent.
5642    Nowadays you can just #include <string.h>.  */
5643 #ifdef STDC_HEADERS
5644 # include <string.h>
5645 #else
5646 # ifndef HAVE_STRCHR
5647 #  define strchr index
5648 #  define strrchr rindex
5649 # endif
5650 char *strchr (), *strrchr ();
5651 # ifndef HAVE_MEMCPY
5652 #  define memcpy(d, s, n) bcopy ((s), (d), (n))
5653 #  define memmove(d, s, n) bcopy ((s), (d), (n))
5654 # endif
5655 #endif
5656 @end group
5657 @end example
5659 @noindent
5660 If you use a function like @code{memchr}, @code{memset}, @code{strtok},
5661 or @code{strspn}, which have no @acronym{BSD} equivalent, then macros don't
5662 suffice to port to ancient hosts; you must provide an implementation of
5663 each function.  An easy
5664 way to incorporate your implementations only when needed (since the ones
5665 in system C libraries may be hand optimized) is to, taking @code{memchr}
5666 for example, put it in @file{memchr.c} and use
5667 @samp{AC_REPLACE_FUNCS([memchr])}.
5668 @end defmac
5670 @defmac AC_HEADER_SYS_WAIT
5671 @acindex{HEADER_SYS_WAIT}
5672 @cvindex HAVE_SYS_WAIT_H
5673 @hdrindex{sys/wait.h}
5674 If @file{sys/wait.h} exists and is compatible with Posix, define
5675 @code{HAVE_SYS_WAIT_H}.  Incompatibility can occur if @file{sys/wait.h}
5676 does not exist, or if it uses the old @acronym{BSD} @code{union wait} instead
5677 of @code{int} to store a status value.  If @file{sys/wait.h} is not
5678 Posix compatible, then instead of including it, define the
5679 Posix macros with their usual interpretations.  Here is an
5680 example:
5682 @example
5683 @group
5684 #include <sys/types.h>
5685 #ifdef HAVE_SYS_WAIT_H
5686 # include <sys/wait.h>
5687 #endif
5688 #ifndef WEXITSTATUS
5689 # define WEXITSTATUS(stat_val) ((unsigned int) (stat_val) >> 8)
5690 #endif
5691 #ifndef WIFEXITED
5692 # define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
5693 #endif
5694 @end group
5695 @end example
5697 @noindent
5698 This macro is obsolescent, as current systems are compatible with Posix.
5699 New programs need not use this macro.
5700 @end defmac
5702 @cvindex _POSIX_VERSION
5703 @hdrindex{unistd.h}
5704 @code{_POSIX_VERSION} is defined when @file{unistd.h} is included on
5705 Posix systems.  If there is no @file{unistd.h}, it is definitely
5706 not a Posix system.  However, some non-Posix systems do
5707 have @file{unistd.h}.
5709 The way to check whether the system supports Posix is:
5711 @example
5712 @group
5713 #ifdef HAVE_UNISTD_H
5714 # include <sys/types.h>
5715 # include <unistd.h>
5716 #endif
5718 #ifdef _POSIX_VERSION
5719 /* Code for Posix systems.  */
5720 #endif
5721 @end group
5722 @end example
5724 @anchor{AC_HEADER_TIME}
5725 @defmac AC_HEADER_TIME
5726 @acindex{HEADER_TIME}
5727 @cvindex TIME_WITH_SYS_TIME
5728 @hdrindex{time.h}
5729 @hdrindex{sys/time.h}
5730 If a program may include both @file{time.h} and @file{sys/time.h},
5731 define @code{TIME_WITH_SYS_TIME}.  On some ancient systems,
5732 @file{sys/time.h} included @file{time.h}, but @file{time.h} was not
5733 protected against multiple inclusion, so programs could not explicitly
5734 include both files.  This macro is useful in programs that use, for
5735 example, @code{struct timeval} as well as
5736 @code{struct tm}.  It is best used in conjunction with
5737 @code{HAVE_SYS_TIME_H}, which can be checked for using
5738 @code{AC_CHECK_HEADERS([sys/time.h])}.
5740 @example
5741 @group
5742 #ifdef TIME_WITH_SYS_TIME
5743 # include <sys/time.h>
5744 # include <time.h>
5745 #else
5746 # ifdef HAVE_SYS_TIME_H
5747 #  include <sys/time.h>
5748 # else
5749 #  include <time.h>
5750 # endif
5751 #endif
5752 @end group
5753 @end example
5755 @noindent
5756 This macro is obsolescent, as current systems can include both files
5757 when they exist.  New programs need not use this macro.
5758 @end defmac
5761 @defmac AC_HEADER_TIOCGWINSZ
5762 @acindex{HEADER_TIOCGWINSZ}
5763 @cvindex GWINSZ_IN_SYS_IOCTL
5764 @hdrindex{sys/ioctl.h}
5765 @hdrindex{termios.h}
5766 @c FIXME: I need clarifications from Jim.
5767 If the use of @code{TIOCGWINSZ} requires @file{<sys/ioctl.h>}, then
5768 define @code{GWINSZ_IN_SYS_IOCTL}.  Otherwise @code{TIOCGWINSZ} can be
5769 found in @file{<termios.h>}.
5771 Use:
5773 @example
5774 @group
5775 #ifdef HAVE_TERMIOS_H
5776 # include <termios.h>
5777 #endif
5779 #ifdef GWINSZ_IN_SYS_IOCTL
5780 # include <sys/ioctl.h>
5781 #endif
5782 @end group
5783 @end example
5784 @end defmac
5786 @node Generic Headers
5787 @subsection Generic Header Checks
5789 These macros are used to find system header files not covered by the
5790 ``particular'' test macros.  If you need to check the contents of a header
5791 as well as find out whether it is present, you have to write your own
5792 test for it (@pxref{Writing Tests}).
5794 @anchor{AC_CHECK_HEADER}
5795 @defmac AC_CHECK_HEADER (@var{header-file}, @ovar{action-if-found}, @
5796   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
5797 @acindex{CHECK_HEADER}
5798 If the system header file @var{header-file} is compilable, execute shell
5799 commands @var{action-if-found}, otherwise execute
5800 @var{action-if-not-found}.  If you just want to define a symbol if the
5801 header file is available, consider using @code{AC_CHECK_HEADERS}
5802 instead.
5804 @var{includes} is a series of include directives, defaulting to
5805 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
5806 prior to the header under test.
5808 For compatibility issues with older versions of Autoconf, please read
5809 below.
5810 @end defmac
5812 @anchor{AC_CHECK_HEADERS}
5813 @defmac AC_CHECK_HEADERS (@var{header-file}@dots{}, @
5814   @ovar{action-if-found}, @ovar{action-if-not-found}, @
5815   @dvar{includes, AC_INCLUDES_DEFAULT})
5816 @acindex{CHECK_HEADERS}
5817 @cvindex HAVE_@var{header}
5818 For each given system header file @var{header-file} in the
5819 blank-separated argument list that exists, define
5820 @code{HAVE_@var{header-file}} (in all capitals).  If @var{action-if-found}
5821 is given, it is additional shell code to execute when one of the header
5822 files is found.  You can give it a value of @samp{break} to break out of
5823 the loop on the first match.  If @var{action-if-not-found} is given, it
5824 is executed when one of the header files is not found.
5826 @var{includes} is a series of include directives, defaulting to
5827 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
5828 prior to the headers under test.
5830 For compatibility issues with older versions of Autoconf, please read
5831 below.
5832 @end defmac
5834 Previous versions of Autoconf merely checked whether the header was
5835 accepted by the preprocessor.  This was changed because the old test was
5836 inappropriate for typical uses.  Headers are typically used to compile,
5837 not merely to preprocess, and the old behavior sometimes accepted
5838 headers that clashed at compile-time.  If you need to check whether a
5839 header is preprocessable, you can use @code{AC_PREPROC_IFELSE}
5840 (@pxref{Running the Preprocessor}).
5842 This scheme, which improves the robustness of the test, also requires
5843 that you make sure that headers that must be included before the
5844 @var{header-file} be part of the @var{includes}, (@pxref{Default
5845 Includes}).  If looking for @file{bar.h}, which requires that
5846 @file{foo.h} be included before if it exists, we suggest the following
5847 scheme:
5849 @verbatim
5850 AC_CHECK_HEADERS([foo.h])
5851 AC_CHECK_HEADERS([bar.h], [], [],
5852 [#ifdef HAVE_FOO_H
5853 # include <foo.h>
5854 # endif
5856 @end verbatim
5858 The following variant generates smaller, faster @command{configure}
5859 files if you do not need the full power of @code{AC_CHECK_HEADERS}.
5861 @defmac AC_CHECK_HEADERS_ONCE (@var{header-file}@dots{})
5862 @acindex{CHECK_HEADERS_ONCE}
5863 @cvindex HAVE_@var{header}
5864 For each given system header file @var{header-file} in the
5865 blank-separated argument list that exists, define
5866 @code{HAVE_@var{header-file}} (in all capitals).
5867 This is a once-only variant of @code{AC_CHECK_HEADERS}.  It generates the
5868 checking code at most once, so that @command{configure} is smaller and
5869 faster; but the checks cannot be conditionalized and are always done once,
5870 early during the @command{configure} run.
5871 @end defmac
5873 @node Declarations
5874 @section Declarations
5875 @cindex Declaration, checking
5877 The following macros check for the declaration of variables and
5878 functions.  If there is no macro specifically defined to check for a
5879 symbol you need, then you can use the general macros (@pxref{Generic
5880 Declarations}) or, for more complex tests, you may use
5881 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}).
5883 @menu
5884 * Particular Declarations::     Macros to check for certain declarations
5885 * Generic Declarations::        How to find other declarations
5886 @end menu
5888 @node Particular Declarations
5889 @subsection Particular Declaration Checks
5891 There are no specific macros for declarations.
5893 @node Generic Declarations
5894 @subsection Generic Declaration Checks
5896 These macros are used to find declarations not covered by the ``particular''
5897 test macros.
5899 @defmac AC_CHECK_DECL (@var{symbol}, @ovar{action-if-found}, @
5900   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
5901 @acindex{CHECK_DECL}
5902 If @var{symbol} (a function, variable, or constant) is not declared in
5903 @var{includes} and a declaration is needed, run the shell commands
5904 @var{action-if-not-found}, otherwise @var{action-if-found}.
5905 @var{includes} is a series of include directives, defaulting to
5906 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
5907 prior to the declaration under test.
5909 This macro actually tests whether @var{symbol} is defined as a macro or
5910 can be used as an r-value, not whether it is really declared, because it
5911 is much safer to avoid
5912 introducing extra declarations when they are not needed.
5913 @end defmac
5915 @anchor{AC_CHECK_DECLS}
5916 @defmac AC_CHECK_DECLS (@var{symbols}, @ovar{action-if-found}, @
5917   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
5918 @acindex{CHECK_DECLS}
5919 @cvindex HAVE_DECL_@var{symbol}
5920 For each of the @var{symbols} (@emph{comma}-separated list), define
5921 @code{HAVE_DECL_@var{symbol}} (in all capitals) to @samp{1} if
5922 @var{symbol} is declared, otherwise to @samp{0}.  If
5923 @var{action-if-not-found} is given, it is additional shell code to
5924 execute when one of the function declarations is needed, otherwise
5925 @var{action-if-found} is executed.
5927 @var{includes} is a series of include directives, defaulting to
5928 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
5929 prior to the declarations under test.
5931 This macro uses an M4 list as first argument:
5932 @example
5933 AC_CHECK_DECLS([strdup])
5934 AC_CHECK_DECLS([strlen])
5935 AC_CHECK_DECLS([malloc, realloc, calloc, free])
5936 AC_CHECK_DECLS([j0], [], [], [[#include <math.h>]])
5937 @end example
5939 Unlike the other @samp{AC_CHECK_*S} macros, when a @var{symbol} is not
5940 declared, @code{HAVE_DECL_@var{symbol}} is defined to @samp{0} instead
5941 of leaving @code{HAVE_DECL_@var{symbol}} undeclared.  When you are
5942 @emph{sure} that the check was performed, use
5943 @code{HAVE_DECL_@var{symbol}} in @code{#if}:
5945 @example
5946 #if !HAVE_DECL_SYMBOL
5947 extern char *symbol;
5948 #endif
5949 @end example
5951 @noindent
5952 If the test may have not been performed, however, because it is safer
5953 @emph{not} to declare a symbol than to use a declaration that conflicts
5954 with the system's one, you should use:
5956 @example
5957 #if defined HAVE_DECL_MALLOC && !HAVE_DECL_MALLOC
5958 void *malloc (size_t *s);
5959 #endif
5960 @end example
5962 @noindent
5963 You fall into the second category only in extreme situations: either
5964 your files may be used without being configured, or they are used during
5965 the configuration.  In most cases the traditional approach is enough.
5966 @end defmac
5968 @defmac AC_CHECK_DECLS_ONCE (@var{symbols})
5969 @acindex{CHECK_DECLS_ONCE}
5970 @cvindex HAVE_DECL_@var{symbol}
5971 For each of the @var{symbols} (@emph{comma}-separated list), define
5972 @code{HAVE_DECL_@var{symbol}} (in all capitals) to @samp{1} if
5973 @var{symbol} is declared in the default include files, otherwise to
5974 @samp{0}.  This is a once-only variant of @code{AC_CHECK_DECLS}.  It
5975 generates the checking code at most once, so that @command{configure} is
5976 smaller and faster; but the checks cannot be conditionalized and are
5977 always done once, early during the @command{configure} run.
5978 @end defmac
5981 @node Structures
5982 @section Structures
5983 @cindex Structure, checking
5985 The following macros check for the presence of certain members in C
5986 structures.  If there is no macro specifically defined to check for a
5987 member you need, then you can use the general structure-member macros
5988 (@pxref{Generic Structures}) or, for more complex tests, you may use
5989 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}).
5991 @menu
5992 * Particular Structures::       Macros to check for certain structure members
5993 * Generic Structures::          How to find other structure members
5994 @end menu
5996 @node Particular Structures
5997 @subsection Particular Structure Checks
5999 The following macros check for certain structures or structure members.
6001 @defmac AC_STRUCT_DIRENT_D_INO
6002 @acindex{STRUCT_DIRENT_D_INO}
6003 @cvindex HAVE_STRUCT_DIRENT_D_INO
6004 Perform all the actions of @code{AC_HEADER_DIRENT} (@pxref{Particular
6005 Headers}).  Then, if @code{struct dirent} contains a @code{d_ino}
6006 member, define @code{HAVE_STRUCT_DIRENT_D_INO}.
6008 @code{HAVE_STRUCT_DIRENT_D_INO} indicates only the presence of
6009 @code{d_ino}, not whether its contents are always reliable.
6010 Traditionally, a zero @code{d_ino} indicated a deleted directory entry,
6011 though current systems hide this detail from the user and never return
6012 zero @code{d_ino} values.
6013 Many current systems report an incorrect @code{d_ino} for a directory
6014 entry that is a mount point.
6015 @end defmac
6017 @defmac AC_STRUCT_DIRENT_D_TYPE
6018 @acindex{STRUCT_DIRENT_D_TYPE}
6019 @cvindex HAVE_STRUCT_DIRENT_D_TYPE
6020 Perform all the actions of @code{AC_HEADER_DIRENT} (@pxref{Particular
6021 Headers}).  Then, if @code{struct dirent} contains a @code{d_type}
6022 member, define @code{HAVE_STRUCT_DIRENT_D_TYPE}.
6023 @end defmac
6025 @anchor{AC_STRUCT_ST_BLOCKS}
6026 @defmac AC_STRUCT_ST_BLOCKS
6027 @acindex{STRUCT_ST_BLOCKS}
6028 @cvindex HAVE_STRUCT_STAT_ST_BLOCKS
6029 @cvindex HAVE_ST_BLOCKS
6030 @ovindex LIBOBJS
6031 If @code{struct stat} contains an @code{st_blocks} member, define
6032 @code{HAVE_STRUCT_STAT_ST_BLOCKS}.  Otherwise, require an
6033 @code{AC_LIBOBJ} replacement of @samp{fileblocks}.  The former name,
6034 @code{HAVE_ST_BLOCKS} is to be avoided, as its support will cease in the
6035 future.
6036 @end defmac
6038 @defmac AC_STRUCT_TM
6039 @acindex{STRUCT_TM}
6040 @cvindex TM_IN_SYS_TIME
6041 @hdrindex{time.h}
6042 @hdrindex{sys/time.h}
6043 If @file{time.h} does not define @code{struct tm}, define
6044 @code{TM_IN_SYS_TIME}, which means that including @file{sys/time.h}
6045 had better define @code{struct tm}.
6047 This macro is obsolescent, as @file{time.h} defines @code{struct tm} in
6048 current systems.  New programs need not use this macro.
6049 @end defmac
6051 @anchor{AC_STRUCT_TIMEZONE}
6052 @defmac AC_STRUCT_TIMEZONE
6053 @acindex{STRUCT_TIMEZONE}
6054 @cvindex HAVE_DECL_TZNAME
6055 @cvindex HAVE_STRUCT_TM_TM_ZONE
6056 @cvindex HAVE_TM_ZONE
6057 @cvindex HAVE_TZNAME
6058 Figure out how to get the current timezone.  If @code{struct tm} has a
6059 @code{tm_zone} member, define @code{HAVE_STRUCT_TM_TM_ZONE} (and the
6060 obsoleted @code{HAVE_TM_ZONE}).  Otherwise, if the external array
6061 @code{tzname} is found, define @code{HAVE_TZNAME}; if it is declared,
6062 define @code{HAVE_DECL_TZNAME}.
6063 @end defmac
6065 @node Generic Structures
6066 @subsection Generic Structure Checks
6068 These macros are used to find structure members not covered by the
6069 ``particular'' test macros.
6071 @defmac AC_CHECK_MEMBER (@var{aggregate}.@var{member}, @
6072   @ovar{action-if-found}, @ovar{action-if-not-found}, @
6073   @dvar{includes, AC_INCLUDES_DEFAULT})
6074 @acindex{CHECK_MEMBER}
6075 Check whether @var{member} is a member of the aggregate @var{aggregate}.
6076 If no @var{includes} are specified, the default includes are used
6077 (@pxref{Default Includes}).
6079 @example
6080 AC_CHECK_MEMBER([struct passwd.pw_gecos], [],
6081                 [AC_MSG_ERROR([We need `passwd.pw_gecos'!])],
6082                 [[#include <pwd.h>]])
6083 @end example
6085 You can use this macro for submembers:
6087 @example
6088 AC_CHECK_MEMBER(struct top.middle.bot)
6089 @end example
6090 @end defmac
6092 @anchor{AC_CHECK_MEMBERS}
6093 @defmac AC_CHECK_MEMBERS (@var{members}, @ovar{action-if-found}, @
6094   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6095 @acindex{CHECK_MEMBERS}
6096 @cvindex HAVE_@var{aggregate}_@var{member}
6097 Check for the existence of each @samp{@var{aggregate}.@var{member}} of
6098 @var{members} using the previous macro.  When @var{member} belongs to
6099 @var{aggregate}, define @code{HAVE_@var{aggregate}_@var{member}} (in all
6100 capitals, with spaces and dots replaced by underscores).  If
6101 @var{action-if-found} is given, it is executed for each of the found
6102 members.  If @var{action-if-not-found} is given, it is executed for each
6103 of the members that could not be found.
6105 @var{includes} is a series of include directives, defaulting to
6106 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
6107 prior to the members under test.
6109 This macro uses M4 lists:
6110 @example
6111 AC_CHECK_MEMBERS([struct stat.st_rdev, struct stat.st_blksize])
6112 @end example
6113 @end defmac
6116 @node Types
6117 @section Types
6118 @cindex Types
6119 @cindex C types
6121 The following macros check for C types, either builtin or typedefs.  If
6122 there is no macro specifically defined to check for a type you need, and
6123 you don't need to check for any special properties of it, then you can
6124 use a general type-check macro.
6126 @menu
6127 * Particular Types::            Special handling to find certain types
6128 * Generic Types::               How to find other types
6129 @end menu
6131 @node Particular Types
6132 @subsection Particular Type Checks
6134 @hdrindex{sys/types.h}
6135 @hdrindex{stdlib.h}
6136 @hdrindex{stdint.h}
6137 @hdrindex{inttypes.h}
6138 These macros check for particular C types in @file{sys/types.h},
6139 @file{stdlib.h}, @file{stdint.h}, @file{inttypes.h} and others, if they
6140 exist.
6142 The Gnulib @code{stdint} module is an alternate way to define many of
6143 these symbols; it is useful if you prefer your code to assume a
6144 C99-or-better environment.  @xref{Gnulib}.
6146 @anchor{AC_TYPE_GETGROUPS}
6147 @defmac AC_TYPE_GETGROUPS
6148 @acindex{TYPE_GETGROUPS}
6149 @cvindex GETGROUPS_T
6150 Define @code{GETGROUPS_T} to be whichever of @code{gid_t} or @code{int}
6151 is the base type of the array argument to @code{getgroups}.
6152 @end defmac
6154 @defmac AC_TYPE_INT8_T
6155 @acindex{TYPE_INT8_T}
6156 @cvindex HAVE_INT8_T
6157 @cvindex int8_t
6158 If @file{stdint.h} or @file{inttypes.h} does not define the type
6159 @code{int8_t}, define @code{int8_t} to a signed
6160 integer type that is exactly 8 bits wide and that uses two's complement
6161 representation, if such a type exists.
6162 If you are worried about porting to hosts that lack such a type, you can
6163 use the results of this macro in C89-or-later code as follows:
6165 @example
6166 #if HAVE_STDINT_H
6167 # include <stdint.h>
6168 #endif
6169 #if defined INT8_MAX || defined int8_t
6170  @emph{code using int8_t}
6171 #else
6172  @emph{complicated alternative using >8-bit 'signed char'}
6173 #endif
6174 @end example
6175 @end defmac
6177 @defmac AC_TYPE_INT16_T
6178 @acindex{TYPE_INT16_T}
6179 @cvindex HAVE_INT16_T
6180 @cvindex int16_t
6181 This is like @code{AC_TYPE_INT8_T}, except for 16-bit integers.
6182 @end defmac
6184 @defmac AC_TYPE_INT32_T
6185 @acindex{TYPE_INT32_T}
6186 @cvindex HAVE_INT32_T
6187 @cvindex int32_t
6188 This is like @code{AC_TYPE_INT8_T}, except for 32-bit integers.
6189 @end defmac
6191 @defmac AC_TYPE_INT64_T
6192 @acindex{TYPE_INT64_T}
6193 @cvindex HAVE_INT64_T
6194 @cvindex int64_t
6195 This is like @code{AC_TYPE_INT8_T}, except for 64-bit integers.
6196 @end defmac
6198 @defmac AC_TYPE_INTMAX_T
6199 @acindex{TYPE_INTMAX_T}
6200 @cvindex HAVE_INTMAX_T
6201 @cvindex intmax_t
6202 If @file{stdint.h} or @file{inttypes.h} defines the type @code{intmax_t},
6203 define @code{HAVE_INTMAX_T}.  Otherwise, define @code{intmax_t} to the
6204 widest signed integer type.
6205 @end defmac
6207 @defmac AC_TYPE_INTPTR_T
6208 @acindex{TYPE_INTPTR_T}
6209 @cvindex HAVE_INTPTR_T
6210 @cvindex intptr_t
6211 If @file{stdint.h} or @file{inttypes.h} defines the type @code{intptr_t},
6212 define @code{HAVE_INTPTR_T}.  Otherwise, define @code{intptr_t} to a
6213 signed integer type wide enough to hold a pointer, if such a type
6214 exists.
6215 @end defmac
6217 @defmac AC_TYPE_LONG_DOUBLE
6218 @acindex{TYPE_LONG_DOUBLE}
6219 @cvindex HAVE_LONG_DOUBLE
6220 If the C compiler supports a working @code{long double} type, define
6221 @code{HAVE_LONG_DOUBLE}.  The @code{long double} type might have the
6222 same range and precision as @code{double}.
6224 This macro is obsolescent, as current C compilers support @code{long
6225 double}.  New programs need not use this macro.
6226 @end defmac
6228 @defmac AC_TYPE_LONG_DOUBLE_WIDER
6229 @acindex{TYPE_LONG_DOUBLE_WIDER}
6230 @cvindex HAVE_LONG_DOUBLE_WIDER
6231 If the C compiler supports a working @code{long double} type with more
6232 range or precision than the @code{double} type, define
6233 @code{HAVE_LONG_DOUBLE_WIDER}.
6234 @end defmac
6236 @defmac AC_TYPE_LONG_LONG_INT
6237 @acindex{TYPE_LONG_LONG_INT}
6238 @cvindex HAVE_LONG_LONG_INT
6239 If the C compiler supports a working @code{long long int} type, define
6240 @code{HAVE_LONG_LONG_INT}.  However, this test does not test
6241 @code{long long int} values in preprocessor @code{#if} expressions,
6242 because too many compilers mishandle such expressions.
6243 @xref{Preprocessor Arithmetic}.
6244 @end defmac
6246 @defmac AC_TYPE_MBSTATE_T
6247 @acindex{TYPE_MBSTATE_T}
6248 @cvindex mbstate_t
6249 @hdrindex{wchar.h}
6250 Define @code{HAVE_MBSTATE_T} if @code{<wchar.h>} declares the
6251 @code{mbstate_t} type.  Also, define @code{mbstate_t} to be a type if
6252 @code{<wchar.h>} does not declare it.
6253 @end defmac
6255 @anchor{AC_TYPE_MODE_T}
6256 @defmac AC_TYPE_MODE_T
6257 @acindex{TYPE_MODE_T}
6258 @cvindex mode_t
6259 Define @code{mode_t} to a suitable type, if standard headers do not
6260 define it.
6261 @end defmac
6263 @anchor{AC_TYPE_OFF_T}
6264 @defmac AC_TYPE_OFF_T
6265 @acindex{TYPE_OFF_T}
6266 @cvindex off_t
6267 Define @code{off_t} to a suitable type, if standard headers do not
6268 define it.
6269 @end defmac
6271 @anchor{AC_TYPE_PID_T}
6272 @defmac AC_TYPE_PID_T
6273 @acindex{TYPE_PID_T}
6274 @cvindex pid_t
6275 Define @code{pid_t} to a suitable type, if standard headers do not
6276 define it.
6277 @end defmac
6279 @anchor{AC_TYPE_SIZE_T}
6280 @defmac AC_TYPE_SIZE_T
6281 @acindex{TYPE_SIZE_T}
6282 @cvindex size_t
6283 Define @code{size_t} to a suitable type, if standard headers do not
6284 define it.
6285 @end defmac
6287 @defmac AC_TYPE_SSIZE_T
6288 @acindex{TYPE_SSIZE_T}
6289 @cvindex ssize_t
6290 Define @code{ssize_t} to a suitable type, if standard headers do not
6291 define it.
6292 @end defmac
6294 @anchor{AC_TYPE_UID_T}
6295 @defmac AC_TYPE_UID_T
6296 @acindex{TYPE_UID_T}
6297 @cvindex uid_t
6298 @cvindex gid_t
6299 Define @code{uid_t} and @code{gid_t} to suitable types, if standard
6300 headers do not define them.
6301 @end defmac
6303 @defmac AC_TYPE_UINT8_T
6304 @acindex{TYPE_UINT8_T}
6305 @cvindex HAVE_UINT8_T
6306 @cvindex uint8_t
6307 If @file{stdint.h} or @file{inttypes.h} does not define the type
6308 @code{uint8_t}, define @code{uint8_t} to an
6309 unsigned integer type that is exactly 8 bits wide, if such a type
6310 exists.
6311 This is like @code{AC_TYPE_INT8_T}, except for unsigned integers.
6312 @end defmac
6314 @defmac AC_TYPE_UINT16_T
6315 @acindex{TYPE_UINT16_T}
6316 @cvindex HAVE_UINT16_T
6317 @cvindex uint16_t
6318 This is like @code{AC_TYPE_UINT8_T}, except for 16-bit integers.
6319 @end defmac
6321 @defmac AC_TYPE_UINT32_T
6322 @acindex{TYPE_UINT32_T}
6323 @cvindex HAVE_UINT32_T
6324 @cvindex uint32_t
6325 This is like @code{AC_TYPE_UINT8_T}, except for 32-bit integers.
6326 @end defmac
6328 @defmac AC_TYPE_UINT64_T
6329 @acindex{TYPE_UINT64_T}
6330 @cvindex HAVE_UINT64_T
6331 @cvindex uint64_t
6332 This is like @code{AC_TYPE_UINT8_T}, except for 64-bit integers.
6333 @end defmac
6335 @defmac AC_TYPE_UINTMAX_T
6336 @acindex{TYPE_UINTMAX_T}
6337 @cvindex HAVE_UINTMAX_T
6338 @cvindex uintmax_t
6339 If @file{stdint.h} or @file{inttypes.h} defines the type @code{uintmax_t},
6340 define @code{HAVE_UINTMAX_T}.  Otherwise, define @code{uintmax_t} to the
6341 widest unsigned integer type.
6342 @end defmac
6344 @defmac AC_TYPE_UINTPTR_T
6345 @acindex{TYPE_UINTPTR_T}
6346 @cvindex HAVE_UINTPTR_T
6347 @cvindex uintptr_t
6348 If @file{stdint.h} or @file{inttypes.h} defines the type @code{uintptr_t},
6349 define @code{HAVE_UINTPTR_T}.  Otherwise, define @code{uintptr_t} to an
6350 unsigned integer type wide enough to hold a pointer, if such a type
6351 exists.
6352 @end defmac
6354 @defmac AC_TYPE_UNSIGNED_LONG_LONG_INT
6355 @acindex{TYPE_UNSIGNED_LONG_LONG_INT}
6356 @cvindex HAVE_UNSIGNED_LONG_LONG_INT
6357 If the C compiler supports a working @code{unsigned long long int} type,
6358 define @code{HAVE_UNSIGNED_LONG_LONG_INT}.  However, this test does not test
6359 @code{unsigned long long int} values in preprocessor @code{#if} expressions,
6360 because too many compilers mishandle such expressions.
6361 @xref{Preprocessor Arithmetic}.
6362 @end defmac
6364 @node Generic Types
6365 @subsection Generic Type Checks
6367 These macros are used to check for types not covered by the ``particular''
6368 test macros.
6370 @defmac AC_CHECK_TYPE (@var{type}, @ovar{action-if-found}, @
6371   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6372 @acindex{CHECK_TYPE}
6373 Check whether @var{type} is defined.  It may be a compiler builtin type
6374 or defined by the @var{includes}.  @var{includes} is a series of include
6375 directives, defaulting to @code{AC_INCLUDES_DEFAULT} (@pxref{Default
6376 Includes}), which are used prior to the type under test.
6378 In C, @var{type} must be a type-name, so that the expression @samp{sizeof
6379 (@var{type})} is valid (but @samp{sizeof ((@var{type}))} is not).  The
6380 same test is applied when compiling for C++, which means that in C++
6381 @var{type} should be a type-id and should not be an anonymous
6382 @samp{struct} or @samp{union}.
6383 @end defmac
6386 @defmac AC_CHECK_TYPES (@var{types}, @ovar{action-if-found}, @
6387   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6388 @acindex{CHECK_TYPES}
6389 @cvindex HAVE_@var{type}
6390 For each @var{type} of the @var{types} that is defined, define
6391 @code{HAVE_@var{type}} (in all capitals).  Each @var{type} must follow
6392 the rules of @code{AC_CHECK_TYPE}.  If no @var{includes} are
6393 specified, the default includes are used (@pxref{Default Includes}).  If
6394 @var{action-if-found} is given, it is additional shell code to execute
6395 when one of the types is found.  If @var{action-if-not-found} is given,
6396 it is executed when one of the types is not found.
6398 This macro uses M4 lists:
6399 @example
6400 AC_CHECK_TYPES([ptrdiff_t])
6401 AC_CHECK_TYPES([unsigned long long int, uintmax_t])
6402 AC_CHECK_TYPES([float_t], [], [], [[#include <math.h>]])
6403 @end example
6405 @end defmac
6407 Autoconf, up to 2.13, used to provide to another version of
6408 @code{AC_CHECK_TYPE}, broken by design.  In order to keep backward
6409 compatibility, a simple heuristic, quite safe but not totally, is
6410 implemented.  In case of doubt, read the documentation of the former
6411 @code{AC_CHECK_TYPE}, see @ref{Obsolete Macros}.
6414 @node Compilers and Preprocessors
6415 @section Compilers and Preprocessors
6416 @cindex Compilers
6417 @cindex Preprocessors
6419 @ovindex EXEEXT
6420 All the tests for compilers (@code{AC_PROG_CC}, @code{AC_PROG_CXX},
6421 @code{AC_PROG_F77}) define the output variable @code{EXEEXT} based on
6422 the output of the compiler, typically to the empty string if
6423 Posix and @samp{.exe} if a @acronym{DOS} variant.
6425 @ovindex OBJEXT
6426 They also define the output variable @code{OBJEXT} based on the
6427 output of the compiler, after @file{.c} files have been excluded, typically
6428 to @samp{o} if Posix, @samp{obj} if a @acronym{DOS} variant.
6430 If the compiler being used does not produce executables, the tests fail.  If
6431 the executables can't be run, and cross-compilation is not enabled, they
6432 fail too.  @xref{Manual Configuration}, for more on support for cross
6433 compiling.
6435 @menu
6436 * Specific Compiler Characteristics::  Some portability issues
6437 * Generic Compiler Characteristics::  Language independent tests and features
6438 * C Compiler::                  Checking its characteristics
6439 * C++ Compiler::                Likewise
6440 * Objective C Compiler::        Likewise
6441 * Erlang Compiler and Interpreter::  Likewise
6442 * Fortran Compiler::            Likewise
6443 @end menu
6445 @node Specific Compiler Characteristics
6446 @subsection Specific Compiler Characteristics
6448 Some compilers exhibit different behaviors.
6450 @table @asis
6451 @item Static/Dynamic Expressions
6452 Autoconf relies on a trick to extract one bit of information from the C
6453 compiler: using negative array sizes.  For instance the following
6454 excerpt of a C source demonstrates how to test whether @samp{int} objects are 4
6455 bytes wide:
6457 @example
6458 static int test_array[sizeof (int) == 4 ? 1 : -1];
6459 @end example
6461 @noindent
6462 To our knowledge, there is a single compiler that does not support this
6463 trick: the @acronym{HP} C compilers (the real ones, not only the
6464 ``bundled'') on @acronym{HP-UX} 11.00.
6465 They incorrectly reject the above program with the diagnostic
6466 ``Variable-length arrays cannot have static storage.''
6467 This bug comes from @acronym{HP} compilers' mishandling of @code{sizeof (int)},
6468 not from the @code{? 1 : -1}, and
6469 Autoconf works around this problem by casting @code{sizeof (int)} to
6470 @code{long int} before comparing it.
6471 @end table
6473 @node Generic Compiler Characteristics
6474 @subsection Generic Compiler Characteristics
6476 @anchor{AC_CHECK_SIZEOF}
6477 @defmac AC_CHECK_SIZEOF (@var{type-or-expr}, @ovar{unused}, @
6478   @dvar{includes, AC_INCLUDES_DEFAULT})
6479 @acindex{CHECK_SIZEOF}
6480 @cvindex SIZEOF_@var{type-or-expr}
6481 Define @code{SIZEOF_@var{type-or-expr}} (@pxref{Standard Symbols}) to be
6482 the size in bytes of @var{type-or-expr}, which may be either a type or
6483 an expression returning a value that has a size.  If the expression
6484 @samp{sizeof (@var{type-or-expr})} is invalid, the result is 0.
6485 @var{includes} is a series of include directives, defaulting to
6486 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
6487 prior to the expression under test.
6489 This macro now works even when cross-compiling.  The @var{unused}
6490 argument was used when cross-compiling.
6492 For example, the call
6494 @example
6495 AC_CHECK_SIZEOF([int *])
6496 @end example
6498 @noindent
6499 defines @code{SIZEOF_INT_P} to be 8 on DEC Alpha AXP systems.
6500 @end defmac
6502 @defmac AC_CHECK_ALIGNOF (@var{type}, @dvar{includes, AC_INCLUDES_DEFAULT})
6503 @acindex{CHECK_ALIGNOF}
6504 @cvindex ALIGNOF_@var{type}
6505 Define @code{ALIGNOF_@var{type}} (@pxref{Standard Symbols}) to be the
6506 alignment in bytes of @var{type}.  @samp{@var{type} y;} must be valid as
6507 a structure member declaration.  If @samp{type} is unknown, the result
6508 is 0.  If no @var{includes} are specified, the default includes are used
6509 (@pxref{Default Includes}).
6510 @end defmac
6512 @defmac AC_COMPUTE_INT (@var{var}, @var{expression}, @
6513   @dvar{includes, AC_INCLUDES_DEFAULT}, @ovar{action-if-fails})
6514 @acindex{COMPUTE_INT}
6515 Store into the shell variable @var{var} the value of the integer
6516 @var{expression}.  The
6517 value should fit in an initializer in a C variable of type @code{signed
6518 long}.  To support cross compilation (in which case, the macro only works on
6519 hosts that use twos-complement arithmetic), it should be possible to evaluate
6520 the expression at compile-time.  If no @var{includes} are specified, the
6521 default includes are used (@pxref{Default Includes}).
6523 Execute @var{action-if-fails} if the value cannot be determined correctly.
6524 @end defmac
6526 @defmac AC_LANG_WERROR
6527 @acindex{LANG_WERROR}
6528 Normally Autoconf ignores warnings generated by the compiler, linker, and
6529 preprocessor.  If this macro is used, warnings count as fatal
6530 errors for the current language.  This macro is useful when the
6531 results of configuration are used where warnings are unacceptable; for
6532 instance, if parts of a program are built with the @acronym{GCC}
6533 @option{-Werror}
6534 option.  If the whole program is built using @option{-Werror} it is
6535 often simpler to put @option{-Werror} in the compiler flags (@code{CFLAGS},
6536 etc.).
6537 @end defmac
6539 @defmac AC_OPENMP
6540 @acindex{OPENMP}
6541 @cvindex _OPENMP
6542 @ovindex OPENMP_CFLAGS
6543 @ovindex OPENMP_CXXFLAGS
6544 @ovindex OPENMP_FFLAGS
6545 @ovindex OPENMP_FCFLAGS
6546 OpenMP (@url{http://@/www.openmp.org/}) specifies extensions of C, C++,
6547 and Fortran that simplify optimization of shared memory parallelism,
6548 which is a common problem on multicore CPUs.
6550 If the current language is C, the macro @code{AC_OPENMP} sets the
6551 variable @code{OPENMP_CFLAGS} to the C compiler flags needed for
6552 supporting OpenMP@.  @code{OPENMP_CFLAGS} is set to empty if the
6553 compiler already supports OpenMP, if it has no way to activate OpenMP
6554 support, or if the user rejects OpenMP support by invoking
6555 @samp{configure} with the @samp{--disable-openmp} option.
6557 @code{OPENMP_CFLAGS} needs to be used when compiling programs, when
6558 preprocessing program source, and when linking programs.  Therefore you
6559 need to add @code{$(OPENMP_CFLAGS)} to the @code{CFLAGS} of C programs
6560 that use OpenMP@.  If you preprocess OpenMP-specific C code, you also
6561 need to add @code{$(OPENMP_CFLAGS)} to @code{CPPFLAGS}.  The presence of
6562 OpenMP support is revealed at compile time by the preprocessor macro
6563 @code{_OPENMP}.
6565 Linking a program with @code{OPENMP_CFLAGS} typically adds one more
6566 shared library to the program's dependencies, so its use is recommended
6567 only on programs that actually require OpenMP.
6569 If the current language is C++, @code{AC_OPENMP} sets the variable
6570 @code{OPENMP_CXXFLAGS}, suitably for the C++ compiler.  The same remarks
6571 hold as for C.
6573 If the current language is Fortran 77 or Fortran, @code{AC_OPENMP} sets
6574 the variable @code{OPENMP_FFLAGS} or @code{OPENMP_FCFLAGS},
6575 respectively.  Similar remarks as for C hold, except that
6576 @code{CPPFLAGS} is not used for Fortran, and no preprocessor macro
6577 signals OpenMP support.
6578 @end defmac
6580 @node C Compiler
6581 @subsection C Compiler Characteristics
6583 The following macros provide ways to find and exercise a C Compiler.
6584 There are a few constructs that ought to be avoided, but do not deserve
6585 being checked for, since they can easily be worked around.
6587 @table @asis
6588 @item Don't use lines containing solitary backslashes
6589 They tickle a bug in the @acronym{HP-UX} C compiler (checked on
6590 @acronym{HP-UX} 10.20,
6591 11.00, and 11i).  When given the following source:
6593 @example
6594 #ifdef __STDC__
6596 * A comment with backslash-newlines in it.  %@{ %@} *\
6599 char str[] = "\\
6600 " A string with backslash-newlines in it %@{ %@} \\
6602 char apostrophe = '\\
6606 #endif
6607 @end example
6609 @noindent
6610 the compiler incorrectly fails with the diagnostics ``Non-terminating
6611 comment at end of file'' and ``Missing @samp{#endif} at end of file.''
6612 Removing the lines with solitary backslashes solves the problem.
6614 @item Don't compile several files at once if output matters to you
6615 Some compilers, such as @acronym{HP}'s, report names of files being
6616 compiled when given more than one file operand.  For instance:
6618 @example
6619 $ @kbd{cc a.c b.c}
6620 a.c:
6621 b.c:
6622 @end example
6624 @noindent
6625 This can cause problems if you observe the output of the compiler to
6626 detect failures.  Invoking @samp{cc -c a.c && cc -c b.c && cc -o c a.o
6627 b.o} solves the issue.
6629 @item Don't rely on @code{#error} failing
6630 The @sc{irix} C compiler does not fail when #error is preprocessed; it
6631 simply emits a diagnostic and continues, exiting successfully.  So,
6632 instead of an error directive like @code{#error "Unsupported word size"}
6633 it is more portable to use an invalid directive like @code{#Unsupported
6634 word size} in Autoconf tests.  In ordinary source code, @code{#error} is
6635 OK, since installers with inadequate compilers like @sc{irix} can simply
6636 examine these compilers' diagnostic output.
6638 @item Don't rely on correct @code{#line} support
6639 On Solaris, @command{c89} (at least Sun C 5.3 through 5.8)
6640 diagnoses @code{#line} directives whose line
6641 numbers are greater than 32767.  Nothing in Posix
6642 makes this invalid.  That is why Autoconf stopped issuing
6643 @code{#line} directives.
6644 @end table
6646 @defmac AC_PROG_CC (@ovar{compiler-search-list})
6647 @acindex{PROG_CC}
6648 @ovindex CC
6649 @ovindex CFLAGS
6650 Determine a C compiler to use.  If @code{CC} is not already set in the
6651 environment, check for @code{gcc} and @code{cc}, then for other C
6652 compilers.  Set output variable @code{CC} to the name of the compiler
6653 found.
6655 This macro may, however, be invoked with an optional first argument
6656 which, if specified, must be a blank-separated list of C compilers to
6657 search for.  This just gives the user an opportunity to specify an
6658 alternative search list for the C compiler.  For example, if you didn't
6659 like the default order, then you could invoke @code{AC_PROG_CC} like
6660 this:
6662 @example
6663 AC_PROG_CC([gcc cl cc])
6664 @end example
6666 If the C compiler does not handle function prototypes correctly by
6667 default, try to add an option to output variable @code{CC} to make it
6668 so.  This macro tries various options that select standard-conformance
6669 modes on various systems.
6671 After calling this macro you can check whether the C compiler has been
6672 set to accept @acronym{ANSI} C89 (@acronym{ISO} C90); if not, the shell
6673 variable
6674 @code{ac_cv_prog_cc_c89} is set to @samp{no}.  See also
6675 @code{AC_C_PROTOTYPES} below.
6677 If using the @acronym{GNU} C compiler, set shell variable @code{GCC} to
6678 @samp{yes}.  If output variable @code{CFLAGS} was not already set, set
6679 it to @option{-g -O2} for the @acronym{GNU} C compiler (@option{-O2} on systems
6680 where @acronym{GCC} does not accept @option{-g}), or @option{-g} for
6681 other compilers.
6682 @end defmac
6684 @anchor{AC_PROG_CC_C_O}
6685 @defmac AC_PROG_CC_C_O
6686 @acindex{PROG_CC_C_O}
6687 @cvindex NO_MINUS_C_MINUS_O
6688 If the C compiler does not accept the @option{-c} and @option{-o} options
6689 simultaneously, define @code{NO_MINUS_C_MINUS_O}.  This macro actually
6690 tests both the compiler found by @code{AC_PROG_CC}, and, if different,
6691 the first @code{cc} in the path.  The test fails if one fails.  This
6692 macro was created for @acronym{GNU} Make to choose the default C compilation
6693 rule.
6694 @end defmac
6697 @defmac AC_PROG_CPP
6698 @acindex{PROG_CPP}
6699 @ovindex CPP
6700 Set output variable @code{CPP} to a command that runs the
6701 C preprocessor.  If @samp{$CC -E} doesn't work, @file{/lib/cpp} is used.
6702 It is only portable to run @code{CPP} on files with a @file{.c}
6703 extension.
6705 Some preprocessors don't indicate missing include files by the error
6706 status.  For such preprocessors an internal variable is set that causes
6707 other macros to check the standard error from the preprocessor and
6708 consider the test failed if any warnings have been reported.
6709 For most preprocessors, though, warnings do not cause include-file
6710 tests to fail unless @code{AC_PROG_CPP_WERROR} is also specified.
6711 @end defmac
6713 @defmac AC_PROG_CPP_WERROR
6714 @acindex{PROG_CPP_WERROR}
6715 @ovindex CPP
6716 This acts like @code{AC_PROG_CPP}, except it treats warnings from the
6717 preprocessor as errors even if the preprocessor exit status indicates
6718 success.  This is useful for avoiding headers that generate mandatory
6719 warnings, such as deprecation notices.
6720 @end defmac
6723 The following macros check for C compiler or machine architecture
6724 features.  To check for characteristics not listed here, use
6725 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}) or
6726 @code{AC_RUN_IFELSE} (@pxref{Runtime}).
6728 @defmac AC_PROG_CC_STDC
6729 @acindex{PROG_CC_STDC}
6730 If the C compiler cannot compile @acronym{ISO} Standard C (currently
6731 C99), try to add an option to output variable @code{CC} to make it work.
6732 If the compiler does not support C99, fall back to supporting
6733 @acronym{ANSI} C89 (@acronym{ISO} C90).
6735 After calling this macro you can check whether the C compiler has been
6736 set to accept Standard C; if not, the shell variable
6737 @code{ac_cv_prog_cc_stdc} is set to @samp{no}.
6738 @end defmac
6740 @defmac AC_PROG_CC_C89
6741 @acindex{PROG_CC_C89}
6742 If the C compiler is not in @acronym{ANSI} C89 (@acronym{ISO} C90) mode by
6743 default, try to add an option to output variable @code{CC} to make it
6744 so.  This macro tries various options that select @acronym{ANSI} C89 on
6745 some system or another.  It considers the compiler to be in
6746 @acronym{ANSI} C89 mode if it handles function prototypes correctly.
6748 After calling this macro you can check whether the C compiler has been
6749 set to accept @acronym{ANSI} C89; if not, the shell variable
6750 @code{ac_cv_prog_cc_c89} is set to @samp{no}.
6752 This macro is called automatically by @code{AC_PROG_CC}.
6753 @end defmac
6755 @defmac AC_PROG_CC_C99
6756 @acindex{PROG_CC_C99}
6757 If the C compiler is not in C99 mode by default, try to add an
6758 option to output variable @code{CC} to make it so.  This macro tries
6759 various options that select C99 on some system or another.  It
6760 considers the compiler to be in C99 mode if it handles @code{_Bool},
6761 @code{//} comments, flexible array members, @code{inline}, signed and
6762 unsigned @code{long long int}, mixed code and declarations, named
6763 initialization of structs,
6764 @code{restrict}, @code{va_copy}, varargs macros, variable declarations
6765 in @code{for} loops, and variable length arrays.
6767 After calling this macro you can check whether the C compiler has been
6768 set to accept C99; if not, the shell variable
6769 @code{ac_cv_prog_cc_c99} is set to @samp{no}.
6770 @end defmac
6772 @defmac AC_C_BACKSLASH_A
6773 @acindex{C_BACKSLASH_A}
6774 @cvindex HAVE_C_BACKSLASH_A
6775 Define @samp{HAVE_C_BACKSLASH_A} to 1 if the C compiler understands
6776 @samp{\a}.
6778 This macro is obsolescent, as current C compilers understand @samp{\a}.
6779 New programs need not use this macro.
6780 @end defmac
6782 @anchor{AC_C_BIGENDIAN}
6783 @defmac AC_C_BIGENDIAN (@ovar{action-if-true}, @ovar{action-if-false}, @
6784   @ovar{action-if-unknown}, @ovar{action-if-universal})
6785 @acindex{C_BIGENDIAN}
6786 @cvindex WORDS_BIGENDIAN
6787 @cindex Endianness
6788 If words are stored with the most significant byte first (like Motorola
6789 and SPARC CPUs), execute @var{action-if-true}.  If words are stored with
6790 the least significant byte first (like Intel and VAX CPUs), execute
6791 @var{action-if-false}.
6793 This macro runs a test-case if endianness cannot be determined from the
6794 system header files.  When cross-compiling, the test-case is not run but
6795 grep'ed for some magic values.  @var{action-if-unknown} is executed if
6796 the latter case fails to determine the byte sex of the host system.
6798 In some cases a single run of a compiler can generate code for multiple
6799 architectures.  This can happen, for example, when generating Mac OS X
6800 universal binary files, which work on both PowerPC and Intel
6801 architectures.  In this case, the different variants might be for
6802 different architectures whose endiannesses differ.  If
6803 @command{configure} detects this, it executes @var{action-if-universal}
6804 instead of @var{action-if-unknown}.
6806 The default for @var{action-if-true} is to define
6807 @samp{WORDS_BIGENDIAN}.  The default for @var{action-if-false} is to do
6808 nothing.  The default for @var{action-if-unknown} is to
6809 abort configure and tell the installer how to bypass this test.
6810 And finally, the default for @var{action-if-universal} is to ensure that
6811 @samp{WORDS_BIGENDIAN} is defined if and only if a universal build is
6812 detected and the current code is big-endian; this default works only if
6813 @command{autoheader} is used (@pxref{autoheader Invocation}).
6815 If you use this macro without specifying @var{action-if-universal}, you
6816 should also use @code{AC_CONFIG_HEADERS}; otherwise
6817 @samp{WORDS_BIGENDIAN} may be set incorrectly for Mac OS X universal
6818 binary files.
6819 @end defmac
6821 @anchor{AC_C_CONST}
6822 @defmac AC_C_CONST
6823 @acindex{C_CONST}
6824 @cvindex const
6825 If the C compiler does not fully support the @code{const} keyword,
6826 define @code{const} to be empty.  Some C compilers that do
6827 not define @code{__STDC__} do support @code{const}; some compilers that
6828 define @code{__STDC__} do not completely support @code{const}.  Programs
6829 can simply use @code{const} as if every C compiler supported it; for
6830 those that don't, the makefile or configuration header file
6831 defines it as empty.
6833 Occasionally installers use a C++ compiler to compile C code, typically
6834 because they lack a C compiler.  This causes problems with @code{const},
6835 because C and C++ treat @code{const} differently.  For example:
6837 @example
6838 const int foo;
6839 @end example
6841 @noindent
6842 is valid in C but not in C++.  These differences unfortunately cannot be
6843 papered over by defining @code{const} to be empty.
6845 If @command{autoconf} detects this situation, it leaves @code{const} alone,
6846 as this generally yields better results in practice.  However, using a
6847 C++ compiler to compile C code is not recommended or supported, and
6848 installers who run into trouble in this area should get a C compiler
6849 like @acronym{GCC} to compile their C code.
6851 This macro is obsolescent, as current C compilers support @code{const}.
6852 New programs need not use this macro.
6853 @end defmac
6855 @defmac AC_C_RESTRICT
6856 @acindex{C_RESTRICT}
6857 @cvindex restrict
6858 If the C compiler recognizes a variant spelling for the @code{restrict}
6859 keyword (@code{__restrict}, @code{__restrict__}, or @code{_Restrict}),
6860 then define @code{restrict} to that; this is more likely to do the right
6861 thing with compilers that support language variants where plain
6862 @code{restrict} is not a keyword.  Otherwise, if the C compiler
6863 recognizes the @code{restrict} keyword, don't do anything.
6864 Otherwise, define @code{restrict} to be empty.
6865 Thus, programs may simply use @code{restrict} as if every C compiler
6866 supported it; for those that do not, the makefile
6867 or configuration header defines it away.
6869 Although support in C++ for the @code{restrict} keyword is not
6870 required, several C++ compilers do accept the keyword.
6871 This macro works for them, too.
6872 @end defmac
6874 @defmac AC_C_VOLATILE
6875 @acindex{C_VOLATILE}
6876 @cvindex volatile
6877 If the C compiler does not understand the keyword @code{volatile},
6878 define @code{volatile} to be empty.  Programs can simply use
6879 @code{volatile} as if every C compiler supported it; for those that do
6880 not, the makefile or configuration header defines it as
6881 empty.
6883 If the correctness of your program depends on the semantics of
6884 @code{volatile}, simply defining it to be empty does, in a sense, break
6885 your code.  However, given that the compiler does not support
6886 @code{volatile}, you are at its mercy anyway.  At least your
6887 program compiles, when it wouldn't before.
6888 @xref{Volatile Objects}, for more about @code{volatile}.
6890 In general, the @code{volatile} keyword is a standard C feature, so
6891 you might expect that @code{volatile} is available only when
6892 @code{__STDC__} is defined.  However, Ultrix 4.3's native compiler does
6893 support volatile, but does not define @code{__STDC__}.
6895 This macro is obsolescent, as current C compilers support @code{volatile}.
6896 New programs need not use this macro.
6897 @end defmac
6899 @anchor{AC_C_INLINE}
6900 @defmac AC_C_INLINE
6901 @acindex{C_INLINE}
6902 @cvindex inline
6903 If the C compiler supports the keyword @code{inline}, do nothing.
6904 Otherwise define @code{inline} to @code{__inline__} or @code{__inline}
6905 if it accepts one of those, otherwise define @code{inline} to be empty.
6906 @end defmac
6908 @anchor{AC_C_CHAR_UNSIGNED}
6909 @defmac AC_C_CHAR_UNSIGNED
6910 @acindex{C_CHAR_UNSIGNED}
6911 @cvindex __CHAR_UNSIGNED__
6912 If the C type @code{char} is unsigned, define @code{__CHAR_UNSIGNED__},
6913 unless the C compiler predefines it.
6915 These days, using this macro is not necessary.  The same information can
6916 be determined by this portable alternative, thus avoiding the use of
6917 preprocessor macros in the namespace reserved for the implementation.
6919 @example
6920 #include <limits.h>
6921 #if CHAR_MIN == 0
6922 # define CHAR_UNSIGNED 1
6923 #endif
6924 @end example
6925 @end defmac
6927 @defmac AC_C_STRINGIZE
6928 @acindex{C_STRINGIZE}
6929 @cvindex HAVE_STRINGIZE
6930 If the C preprocessor supports the stringizing operator, define
6931 @code{HAVE_STRINGIZE}.  The stringizing operator is @samp{#} and is
6932 found in macros such as this:
6934 @example
6935 #define x(y) #y
6936 @end example
6938 This macro is obsolescent, as current C compilers support the
6939 stringizing operator.  New programs need not use this macro.
6940 @end defmac
6942 @defmac AC_C_FLEXIBLE_ARRAY_MEMBER
6943 @acindex{C_FLEXIBLE_ARRAY_MEMBER}
6944 @cvindex FLEXIBLE_ARRAY_MEMBER
6945 If the C compiler supports flexible array members, define
6946 @code{FLEXIBLE_ARRAY_MEMBER} to nothing; otherwise define it to 1.
6947 That way, a declaration like this:
6949 @example
6950 struct s
6951   @{
6952     size_t n_vals;
6953     double val[FLEXIBLE_ARRAY_MEMBER];
6954   @};
6955 @end example
6957 @noindent
6958 will let applications use the ``struct hack'' even with compilers that
6959 do not support flexible array members.  To allocate and use such an
6960 object, you can use code like this:
6962 @example
6963 size_t i;
6964 size_t n = compute_value_count ();
6965 struct s *p =
6966    malloc (offsetof (struct s, val)
6967            + n * sizeof (double));
6968 p->n_vals = n;
6969 for (i = 0; i < n; i++)
6970   p->val[i] = compute_value (i);
6971 @end example
6972 @end defmac
6974 @defmac AC_C_VARARRAYS
6975 @acindex{C_VARARRAYS}
6976 @cvindex HAVE_C_VARARRAYS
6977 If the C compiler supports variable-length arrays, define
6978 @code{HAVE_C_VARARRAYS}.  A variable-length array is an array of automatic
6979 storage duration whose length is determined at run time, when the array
6980 is declared.
6981 @end defmac
6983 @defmac AC_C_TYPEOF
6984 @acindex{C_TYPEOF}
6985 @cvindex HAVE_TYPEOF
6986 @cvindex typeof
6987 If the C compiler supports @acronym{GCC}'s @code{typeof} syntax either
6988 directly or
6989 through a different spelling of the keyword (e.g., @code{__typeof__}),
6990 define @code{HAVE_TYPEOF}.  If the support is available only through a
6991 different spelling, define @code{typeof} to that spelling.
6992 @end defmac
6994 @defmac AC_C_PROTOTYPES
6995 @acindex{C_PROTOTYPES}
6996 @cvindex PROTOTYPES
6997 @cvindex __PROTOTYPES
6998 @cvindex PARAMS
6999 If function prototypes are understood by the compiler (as determined by
7000 @code{AC_PROG_CC}), define @code{PROTOTYPES} and @code{__PROTOTYPES}.
7001 Defining @code{__PROTOTYPES} is for the benefit of
7002 header files that cannot use macros that infringe on user name space.
7004 This macro is obsolescent, as current C compilers support prototypes.
7005 New programs need not use this macro.
7006 @end defmac
7008 @anchor{AC_PROG_GCC_TRADITIONAL}
7009 @defmac AC_PROG_GCC_TRADITIONAL
7010 @acindex{PROG_GCC_TRADITIONAL}
7011 @ovindex CC
7012 Add @option{-traditional} to output variable @code{CC} if using the
7013 @acronym{GNU} C compiler and @code{ioctl} does not work properly without
7014 @option{-traditional}.  That usually happens when the fixed header files
7015 have not been installed on an old system.
7017 This macro is obsolescent, since current versions of the @acronym{GNU} C
7018 compiler fix the header files automatically when installed.
7019 @end defmac
7022 @node C++ Compiler
7023 @subsection C++ Compiler Characteristics
7026 @defmac AC_PROG_CXX (@ovar{compiler-search-list})
7027 @acindex{PROG_CXX}
7028 @ovindex CXX
7029 @ovindex CXXFLAGS
7030 Determine a C++ compiler to use.  Check whether the environment variable
7031 @code{CXX} or @code{CCC} (in that order) is set; if so, then set output
7032 variable @code{CXX} to its value.
7034 Otherwise, if the macro is invoked without an argument, then search for
7035 a C++ compiler under the likely names (first @code{g++} and @code{c++}
7036 then other names).  If none of those checks succeed, then as a last
7037 resort set @code{CXX} to @code{g++}.
7039 This macro may, however, be invoked with an optional first argument
7040 which, if specified, must be a blank-separated list of C++ compilers to
7041 search for.  This just gives the user an opportunity to specify an
7042 alternative search list for the C++ compiler.  For example, if you
7043 didn't like the default order, then you could invoke @code{AC_PROG_CXX}
7044 like this:
7046 @example
7047 AC_PROG_CXX([gcc cl KCC CC cxx cc++ xlC aCC c++ g++])
7048 @end example
7050 If using the @acronym{GNU} C++ compiler, set shell variable @code{GXX} to
7051 @samp{yes}.  If output variable @code{CXXFLAGS} was not already set, set
7052 it to @option{-g -O2} for the @acronym{GNU} C++ compiler (@option{-O2} on
7053 systems where G++ does not accept @option{-g}), or @option{-g} for other
7054 compilers.
7055 @end defmac
7057 @defmac AC_PROG_CXXCPP
7058 @acindex{PROG_CXXCPP}
7059 @ovindex CXXCPP
7060 Set output variable @code{CXXCPP} to a command that runs the C++
7061 preprocessor.  If @samp{$CXX -E} doesn't work, @file{/lib/cpp} is used.
7062 It is portable to run @code{CXXCPP} only on files with a @file{.c},
7063 @file{.C}, @file{.cc}, or @file{.cpp} extension.
7065 Some preprocessors don't indicate missing include files by the error
7066 status.  For such preprocessors an internal variable is set that causes
7067 other macros to check the standard error from the preprocessor and
7068 consider the test failed if any warnings have been reported.  However,
7069 it is not known whether such broken preprocessors exist for C++.
7070 @end defmac
7072 @defmac AC_PROG_CXX_C_O
7073 @acindex{PROG_CXX_C_O}
7074 @cvindex CXX_NO_MINUS_C_MINUS_O
7075 Test whether the C++ compiler accepts the options @option{-c} and
7076 @option{-o} simultaneously, and define @code{CXX_NO_MINUS_C_MINUS_O},
7077 if it does not.
7078 @end defmac
7081 @node Objective C Compiler
7082 @subsection Objective C Compiler Characteristics
7085 @defmac AC_PROG_OBJC (@ovar{compiler-search-list})
7086 @acindex{PROG_OBJC}
7087 @ovindex OBJC
7088 @ovindex OBJCFLAGS
7089 Determine an Objective C compiler to use.  If @code{OBJC} is not already
7090 set in the environment, check for Objective C compilers.  Set output
7091 variable @code{OBJC} to the name of the compiler found.
7093 This macro may, however, be invoked with an optional first argument
7094 which, if specified, must be a blank-separated list of Objective C compilers to
7095 search for.  This just gives the user an opportunity to specify an
7096 alternative search list for the Objective C compiler.  For example, if you
7097 didn't like the default order, then you could invoke @code{AC_PROG_OBJC}
7098 like this:
7100 @example
7101 AC_PROG_OBJC([gcc objcc objc])
7102 @end example
7104 If using the @acronym{GNU} Objective C compiler, set shell variable
7105 @code{GOBJC} to @samp{yes}.  If output variable @code{OBJCFLAGS} was not
7106 already set, set it to @option{-g -O2} for the @acronym{GNU} Objective C
7107 compiler (@option{-O2} on systems where @command{gcc} does not accept
7108 @option{-g}), or @option{-g} for other compilers.
7109 @end defmac
7111 @defmac AC_PROG_OBJCPP
7112 @acindex{PROG_OBJCPP}
7113 @ovindex OBJCPP
7114 Set output variable @code{OBJCPP} to a command that runs the Objective C
7115 preprocessor.  If @samp{$OBJC -E} doesn't work, @file{/lib/cpp} is used.
7116 @end defmac
7119 @node Erlang Compiler and Interpreter
7120 @subsection Erlang Compiler and Interpreter Characteristics
7121 @cindex Erlang
7123 Autoconf defines the following macros for determining paths to the essential
7124 Erlang/OTP programs:
7126 @defmac AC_ERLANG_PATH_ERLC (@ovar{value-if-not-found}, @dvar{path, $PATH})
7127 @acindex{ERLANG_PATH_ERLC}
7128 @ovindex ERLC
7129 @ovindex ERLCFLAGS
7130 Determine an Erlang compiler to use.  If @code{ERLC} is not already set in the
7131 environment, check for @command{erlc}.  Set output variable @code{ERLC} to the
7132 complete path of the compiler command found.  In addition, if @code{ERLCFLAGS}
7133 is not set in the environment, set it to an empty value.
7135 The two optional arguments have the same meaning as the two last arguments of
7136 macro @code{AC_PROG_PATH} for looking for the @command{erlc} program.  For
7137 example, to look for @command{erlc} only in the @file{/usr/lib/erlang/bin}
7138 directory:
7140 @example
7141 AC_ERLANG_PATH_ERLC([not found], [/usr/lib/erlang/bin])
7142 @end example
7143 @end defmac
7145 @defmac AC_ERLANG_NEED_ERLC (@dvar{path, $PATH})
7146 @acindex{ERLANG_NEED_ERLC}
7147 A simplified variant of the @code{AC_ERLANG_PATH_ERLC} macro, that prints an
7148 error message and exits the @command{configure} script if the @command{erlc}
7149 program is not found.
7150 @end defmac
7152 @defmac AC_ERLANG_PATH_ERL (@ovar{value-if-not-found}, @dvar{path, $PATH})
7153 @acindex{ERLANG_PATH_ERL}
7154 @ovindex ERL
7155 Determine an Erlang interpreter to use.  If @code{ERL} is not already
7156 set in the
7157 environment, check for @command{erl}.  Set output variable @code{ERL} to the
7158 complete path of the interpreter command found.
7160 The two optional arguments have the same meaning as the two last arguments of
7161 macro @code{AC_PROG_PATH} for looking for the @command{erl} program.  For
7162 example, to look for @command{erl} only in the @file{/usr/lib/erlang/bin}
7163 directory:
7165 @example
7166 AC_ERLANG_PATH_ERL([not found], [/usr/lib/erlang/bin])
7167 @end example
7168 @end defmac
7170 @defmac AC_ERLANG_NEED_ERL (@dvar{path, $PATH})
7171 @acindex{ERLANG_NEED_ERL}
7172 A simplified variant of the @code{AC_ERLANG_PATH_ERL} macro, that prints an
7173 error message and exits the @command{configure} script if the @command{erl}
7174 program is not found.
7175 @end defmac
7178 @node Fortran Compiler
7179 @subsection Fortran Compiler Characteristics
7180 @cindex Fortran
7181 @cindex F77
7183 The Autoconf Fortran support is divided into two categories: legacy
7184 Fortran 77 macros (@code{F77}), and modern Fortran macros (@code{FC}).
7185 The former are intended for traditional Fortran 77 code, and have output
7186 variables like @code{F77}, @code{FFLAGS}, and @code{FLIBS}.  The latter
7187 are for newer programs that can (or must) compile under the newer
7188 Fortran standards, and have output variables like @code{FC},
7189 @code{FCFLAGS}, and @code{FCLIBS}.
7191 Except for two new macros @code{AC_FC_SRCEXT} and
7192 @code{AC_FC_FREEFORM} (see below), the @code{FC} and @code{F77} macros
7193 behave almost identically, and so they are documented together in this
7194 section.
7197 @defmac AC_PROG_F77 (@ovar{compiler-search-list})
7198 @acindex{PROG_F77}
7199 @ovindex F77
7200 @ovindex FFLAGS
7201 Determine a Fortran 77 compiler to use.  If @code{F77} is not already
7202 set in the environment, then check for @code{g77} and @code{f77}, and
7203 then some other names.  Set the output variable @code{F77} to the name
7204 of the compiler found.
7206 This macro may, however, be invoked with an optional first argument
7207 which, if specified, must be a blank-separated list of Fortran 77
7208 compilers to search for.  This just gives the user an opportunity to
7209 specify an alternative search list for the Fortran 77 compiler.  For
7210 example, if you didn't like the default order, then you could invoke
7211 @code{AC_PROG_F77} like this:
7213 @example
7214 AC_PROG_F77([fl32 f77 fort77 xlf g77 f90 xlf90])
7215 @end example
7217 If using @code{g77} (the @acronym{GNU} Fortran 77 compiler), then
7218 set the shell variable @code{G77} to @samp{yes}.
7219 If the output variable @code{FFLAGS} was not already set in the
7220 environment, then set it to @option{-g -02} for @code{g77} (or @option{-O2}
7221 where @code{g77} does not accept @option{-g}).  Otherwise, set
7222 @code{FFLAGS} to @option{-g} for all other Fortran 77 compilers.
7223 @end defmac
7225 @defmac AC_PROG_FC (@ovar{compiler-search-list}, @ovar{dialect})
7226 @acindex{PROG_FC}
7227 @ovindex FC
7228 @ovindex FCFLAGS
7229 Determine a Fortran compiler to use.  If @code{FC} is not already set in
7230 the environment, then @code{dialect} is a hint to indicate what Fortran
7231 dialect to search for; the default is to search for the newest available
7232 dialect.  Set the output variable @code{FC} to the name of the compiler
7233 found.
7235 By default, newer dialects are preferred over older dialects, but if
7236 @code{dialect} is specified then older dialects are preferred starting
7237 with the specified dialect.  @code{dialect} can currently be one of
7238 Fortran 77, Fortran 90, or Fortran 95.  However, this is only a hint of
7239 which compiler @emph{name} to prefer (e.g., @code{f90} or @code{f95}),
7240 and no attempt is made to guarantee that a particular language standard
7241 is actually supported.  Thus, it is preferable that you avoid the
7242 @code{dialect} option, and use AC_PROG_FC only for code compatible with
7243 the latest Fortran standard.
7245 This macro may, alternatively, be invoked with an optional first argument
7246 which, if specified, must be a blank-separated list of Fortran
7247 compilers to search for, just as in @code{AC_PROG_F77}.
7249 If the output variable @code{FCFLAGS} was not already set in the
7250 environment, then set it to @option{-g -02} for @acronym{GNU} @code{g77} (or
7251 @option{-O2} where @code{g77} does not accept @option{-g}).  Otherwise,
7252 set @code{FCFLAGS} to @option{-g} for all other Fortran compilers.
7253 @end defmac
7255 @defmac AC_PROG_F77_C_O
7256 @defmacx AC_PROG_FC_C_O
7257 @acindex{PROG_F77_C_O}
7258 @acindex{PROG_FC_C_O}
7259 @cvindex F77_NO_MINUS_C_MINUS_O
7260 @cvindex FC_NO_MINUS_C_MINUS_O
7261 Test whether the Fortran compiler accepts the options @option{-c} and
7262 @option{-o} simultaneously, and define @code{F77_NO_MINUS_C_MINUS_O} or
7263 @code{FC_NO_MINUS_C_MINUS_O}, respectively, if it does not.
7264 @end defmac
7266 The following macros check for Fortran compiler characteristics.
7267 To check for characteristics not listed here, use
7268 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}) or
7269 @code{AC_RUN_IFELSE} (@pxref{Runtime}), making sure to first set the
7270 current language to Fortran 77 or Fortran via @code{AC_LANG([Fortran 77])}
7271 or @code{AC_LANG(Fortran)} (@pxref{Language Choice}).
7274 @defmac AC_F77_LIBRARY_LDFLAGS
7275 @defmacx AC_FC_LIBRARY_LDFLAGS
7276 @acindex{F77_LIBRARY_LDFLAGS}
7277 @ovindex FLIBS
7278 @acindex{FC_LIBRARY_LDFLAGS}
7279 @ovindex FCLIBS
7280 Determine the linker flags (e.g., @option{-L} and @option{-l}) for the
7281 @dfn{Fortran intrinsic and runtime libraries} that are required to
7282 successfully link a Fortran program or shared library.  The output
7283 variable @code{FLIBS} or @code{FCLIBS} is set to these flags (which
7284 should be included after @code{LIBS} when linking).
7286 This macro is intended to be used in those situations when it is
7287 necessary to mix, e.g., C++ and Fortran source code in a single
7288 program or shared library (@pxref{Mixing Fortran 77 With C and C++, , ,
7289 automake, @acronym{GNU} Automake}).
7291 For example, if object files from a C++ and Fortran compiler must be
7292 linked together, then the C++ compiler/linker must be used for linking
7293 (since special C++-ish things need to happen at link time like calling
7294 global constructors, instantiating templates, enabling exception
7295 support, etc.).
7297 However, the Fortran intrinsic and runtime libraries must be linked in
7298 as well, but the C++ compiler/linker doesn't know by default how to add
7299 these Fortran 77 libraries.  Hence, this macro was created to determine
7300 these Fortran libraries.
7302 The macros @code{AC_F77_DUMMY_MAIN} and @code{AC_FC_DUMMY_MAIN} or
7303 @code{AC_F77_MAIN} and @code{AC_FC_MAIN} are probably also necessary to
7304 link C/C++ with Fortran; see below.
7305 @end defmac
7307 @defmac AC_F77_DUMMY_MAIN (@ovar{action-if-found}, @ovar{action-if-not-found})
7308 @defmacx AC_FC_DUMMY_MAIN (@ovar{action-if-found}, @ovar{action-if-not-found})
7309 @acindex{F77_DUMMY_MAIN}
7310 @cvindex F77_DUMMY_MAIN
7311 With many compilers, the Fortran libraries detected by
7312 @code{AC_F77_LIBRARY_LDFLAGS} or @code{AC_FC_LIBRARY_LDFLAGS} provide
7313 their own @code{main} entry function that initializes things like
7314 Fortran I/O, and which then calls a user-provided entry function named
7315 (say) @code{MAIN__} to run the user's program.  The
7316 @code{AC_F77_DUMMY_MAIN} and @code{AC_FC_DUMMY_MAIN} or
7317 @code{AC_F77_MAIN} and @code{AC_FC_MAIN} macros figure out how to deal with
7318 this interaction.
7320 When using Fortran for purely numerical functions (no I/O, etc.)@: often
7321 one prefers to provide one's own @code{main} and skip the Fortran
7322 library initializations.  In this case, however, one may still need to
7323 provide a dummy @code{MAIN__} routine in order to prevent linking errors
7324 on some systems.  @code{AC_F77_DUMMY_MAIN} or @code{AC_FC_DUMMY_MAIN}
7325 detects whether any such routine is @emph{required} for linking, and
7326 what its name is; the shell variable @code{F77_DUMMY_MAIN} or
7327 @code{FC_DUMMY_MAIN} holds this name, @code{unknown} when no solution
7328 was found, and @code{none} when no such dummy main is needed.
7330 By default, @var{action-if-found} defines @code{F77_DUMMY_MAIN} or
7331 @code{FC_DUMMY_MAIN} to the name of this routine (e.g., @code{MAIN__})
7332 @emph{if} it is required.  @var{action-if-not-found} defaults to
7333 exiting with an error.
7335 In order to link with Fortran routines, the user's C/C++ program should
7336 then include the following code to define the dummy main if it is
7337 needed:
7339 @example
7340 #ifdef F77_DUMMY_MAIN
7341 #  ifdef __cplusplus
7342      extern "C"
7343 #  endif
7344    int F77_DUMMY_MAIN() @{ return 1; @}
7345 #endif
7346 @end example
7348 (Replace @code{F77} with @code{FC} for Fortran instead of Fortran 77.)
7350 Note that this macro is called automatically from @code{AC_F77_WRAPPERS}
7351 or @code{AC_FC_WRAPPERS}; there is generally no need to call it
7352 explicitly unless one wants to change the default actions.
7353 @end defmac
7355 @defmac AC_F77_MAIN
7356 @defmacx AC_FC_MAIN
7357 @acindex{F77_MAIN}
7358 @cvindex F77_MAIN
7359 @acindex{FC_MAIN}
7360 @cvindex FC_MAIN
7361 As discussed above, many Fortran libraries allow you to provide an entry
7362 point called (say) @code{MAIN__} instead of the usual @code{main}, which
7363 is then called by a @code{main} function in the Fortran libraries that
7364 initializes things like Fortran I/O@.  The
7365 @code{AC_F77_MAIN} and @code{AC_FC_MAIN} macros detect whether it is
7366 @emph{possible} to utilize such an alternate main function, and defines
7367 @code{F77_MAIN} and @code{FC_MAIN} to the name of the function.  (If no
7368 alternate main function name is found, @code{F77_MAIN} and @code{FC_MAIN} are
7369 simply defined to @code{main}.)
7371 Thus, when calling Fortran routines from C that perform things like I/O,
7372 one should use this macro and declare the "main" function like so:
7374 @example
7375 #ifdef __cplusplus
7376   extern "C"
7377 #endif
7378 int F77_MAIN(int argc, char *argv[]);
7379 @end example
7381 (Again, replace @code{F77} with @code{FC} for Fortran instead of Fortran 77.)
7382 @end defmac
7384 @defmac AC_F77_WRAPPERS
7385 @defmacx AC_FC_WRAPPERS
7386 @acindex{F77_WRAPPERS}
7387 @cvindex F77_FUNC
7388 @cvindex F77_FUNC_
7389 @acindex{FC_WRAPPERS}
7390 @cvindex FC_FUNC
7391 @cvindex FC_FUNC_
7392 Defines C macros @code{F77_FUNC (name, NAME)}, @code{FC_FUNC (name, NAME)},
7393 @code{F77_FUNC_(name, NAME)}, and @code{FC_FUNC_(name, NAME)} to properly
7394 mangle the names of C/C++ identifiers, and identifiers with underscores,
7395 respectively, so that they match the name-mangling scheme used by the
7396 Fortran compiler.
7398 Fortran is case-insensitive, and in order to achieve this the Fortran
7399 compiler converts all identifiers into a canonical case and format.  To
7400 call a Fortran subroutine from C or to write a C function that is
7401 callable from Fortran, the C program must explicitly use identifiers in
7402 the format expected by the Fortran compiler.  In order to do this, one
7403 simply wraps all C identifiers in one of the macros provided by
7404 @code{AC_F77_WRAPPERS} or @code{AC_FC_WRAPPERS}.  For example, suppose
7405 you have the following Fortran 77 subroutine:
7407 @example
7408       subroutine foobar (x, y)
7409       double precision x, y
7410       y = 3.14159 * x
7411       return
7412       end
7413 @end example
7415 You would then declare its prototype in C or C++ as:
7417 @example
7418 #define FOOBAR_F77 F77_FUNC (foobar, FOOBAR)
7419 #ifdef __cplusplus
7420 extern "C"  /* prevent C++ name mangling */
7421 #endif
7422 void FOOBAR_F77(double *x, double *y);
7423 @end example
7425 Note that we pass both the lowercase and uppercase versions of the
7426 function name to @code{F77_FUNC} so that it can select the right one.
7427 Note also that all parameters to Fortran 77 routines are passed as
7428 pointers (@pxref{Mixing Fortran 77 With C and C++, , , automake, @acronym{GNU}
7429 Automake}).
7431 (Replace @code{F77} with @code{FC} for Fortran instead of Fortran 77.)
7433 Although Autoconf tries to be intelligent about detecting the
7434 name-mangling scheme of the Fortran compiler, there may be Fortran
7435 compilers that it doesn't support yet.  In this case, the above code
7436 generates a compile-time error, but some other behavior
7437 (e.g., disabling Fortran-related features) can be induced by checking
7438 whether @code{F77_FUNC} or @code{FC_FUNC} is defined.
7440 Now, to call that routine from a C program, we would do something like:
7442 @example
7444     double x = 2.7183, y;
7445     FOOBAR_F77 (&x, &y);
7447 @end example
7449 If the Fortran identifier contains an underscore (e.g., @code{foo_bar}),
7450 you should use @code{F77_FUNC_} or @code{FC_FUNC_} instead of
7451 @code{F77_FUNC} or @code{FC_FUNC} (with the same arguments).  This is
7452 because some Fortran compilers mangle names differently if they contain
7453 an underscore.
7454 @end defmac
7456 @defmac AC_F77_FUNC (@var{name}, @ovar{shellvar})
7457 @defmacx AC_FC_FUNC (@var{name}, @ovar{shellvar})
7458 @acindex{F77_FUNC}
7459 @acindex{FC_FUNC}
7460 Given an identifier @var{name}, set the shell variable @var{shellvar} to
7461 hold the mangled version @var{name} according to the rules of the
7462 Fortran linker (see also @code{AC_F77_WRAPPERS} or
7463 @code{AC_FC_WRAPPERS}).  @var{shellvar} is optional; if it is not
7464 supplied, the shell variable is simply @var{name}.  The purpose of
7465 this macro is to give the caller a way to access the name-mangling
7466 information other than through the C preprocessor as above, for example,
7467 to call Fortran routines from some language other than C/C++.
7468 @end defmac
7470 @defmac AC_FC_SRCEXT (@var{ext}, @ovar{action-if-success}, @
7471   @ovar{action-if-failure})
7472 @acindex{FC_SRCEXT}
7473 By default, the @code{FC} macros perform their tests using a @file{.f}
7474 extension for source-code files.  Some compilers, however, only enable
7475 newer language features for appropriately named files, e.g., Fortran 90
7476 features only for @file{.f90} files.  On the other hand, some other
7477 compilers expect all source files to end in @file{.f} and require
7478 special flags to support other file name extensions.  The
7479 @code{AC_FC_SRCEXT} macro deals with both of these issues.
7481 The @code{AC_FC_SRCEXT} tries to get the @code{FC} compiler to accept files
7482 ending with the extension .@var{ext} (i.e., @var{ext} does @emph{not}
7483 contain the dot).  If any special compiler flags are needed for this, it
7484 stores them in the output variable @code{FCFLAGS_}@var{ext}.  This
7485 extension and these flags are then used for all subsequent @code{FC} tests
7486 (until @code{AC_FC_SRCEXT} is called again).
7488 For example, you would use @code{AC_FC_SRCEXT(f90)} to employ the
7489 @file{.f90} extension in future tests, and it would set a
7490 @code{FCFLAGS_f90} output variable with any extra flags that are needed
7491 to compile such files.
7493 The @code{FCFLAGS_}@var{ext} can @emph{not} be simply absorbed into
7494 @code{FCFLAGS}, for two reasons based on the limitations of some
7495 compilers.  First, only one @code{FCFLAGS_}@var{ext} can be used at a
7496 time, so files with different extensions must be compiled separately.
7497 Second, @code{FCFLAGS_}@var{ext} must appear @emph{immediately} before
7498 the source-code file name when compiling.  So, continuing the example
7499 above, you might compile a @file{foo.f90} file in your makefile with the
7500 command:
7502 @example
7503 foo.o: foo.f90
7504      $(FC) -c $(FCFLAGS) $(FCFLAGS_f90) '$(srcdir)/foo.f90'
7505 @end example
7507 If @code{AC_FC_SRCEXT} succeeds in compiling files with the @var{ext}
7508 extension, it calls @var{action-if-success} (defaults to nothing).  If
7509 it fails, and cannot find a way to make the @code{FC} compiler accept such
7510 files, it calls @var{action-if-failure} (defaults to exiting with an
7511 error message).
7513 @end defmac
7515 @defmac AC_FC_FREEFORM (@ovar{action-if-success}, @ovar{action-if-failure})
7516 @acindex{FC_FREEFORM}
7518 The @code{AC_FC_FREEFORM} tries to ensure that the Fortran compiler
7519 (@code{$FC}) allows free-format source code (as opposed to the older
7520 fixed-format style from Fortran 77).  If necessary, it may add some
7521 additional flags to @code{FCFLAGS}.
7523 This macro is most important if you are using the default @file{.f}
7524 extension, since many compilers interpret this extension as indicating
7525 fixed-format source unless an additional flag is supplied.  If you
7526 specify a different extension with @code{AC_FC_SRCEXT}, such as
7527 @file{.f90} or @file{.f95}, then @code{AC_FC_FREEFORM} ordinarily
7528 succeeds without modifying @code{FCFLAGS}.
7530 If @code{AC_FC_FREEFORM} succeeds in compiling free-form source, it
7531 calls @var{action-if-success} (defaults to nothing).  If it fails, it
7532 calls @var{action-if-failure} (defaults to exiting with an error
7533 message).
7534 @end defmac
7536 @node System Services
7537 @section System Services
7539 The following macros check for operating system services or capabilities.
7541 @anchor{AC_PATH_X}
7542 @defmac AC_PATH_X
7543 @acindex{PATH_X}
7544 @evindex XMKMF
7545 @cindex X Window System
7546 Try to locate the X Window System include files and libraries.  If the
7547 user gave the command line options @option{--x-includes=@var{dir}} and
7548 @option{--x-libraries=@var{dir}}, use those directories.
7550 If either or both were not given, get the missing values by running
7551 @code{xmkmf} (or an executable pointed to by the @code{XMKMF}
7552 environment variable) on a trivial @file{Imakefile} and examining the
7553 makefile that it produces.  Setting @code{XMKMF} to @samp{false}
7554 disables this method.
7556 If this method fails to find the X Window System, @command{configure}
7557 looks for the files in several directories where they often reside.
7558 If either method is successful, set the shell variables
7559 @code{x_includes} and @code{x_libraries} to their locations, unless they
7560 are in directories the compiler searches by default.
7562 If both methods fail, or the user gave the command line option
7563 @option{--without-x}, set the shell variable @code{no_x} to @samp{yes};
7564 otherwise set it to the empty string.
7565 @end defmac
7567 @anchor{AC_PATH_XTRA}
7568 @defmac AC_PATH_XTRA
7569 @acindex{PATH_XTRA}
7570 @ovindex X_CFLAGS
7571 @ovindex X_LIBS
7572 @ovindex X_EXTRA_LIBS
7573 @ovindex X_PRE_LIBS
7574 @cvindex X_DISPLAY_MISSING
7575 An enhanced version of @code{AC_PATH_X}.  It adds the C compiler flags
7576 that X needs to output variable @code{X_CFLAGS}, and the X linker flags
7577 to @code{X_LIBS}.  Define @code{X_DISPLAY_MISSING} if X is not
7578 available.
7580 This macro also checks for special libraries that some systems need in
7581 order to compile X programs.  It adds any that the system needs to
7582 output variable @code{X_EXTRA_LIBS}.  And it checks for special X11R6
7583 libraries that need to be linked with before @option{-lX11}, and adds
7584 any found to the output variable @code{X_PRE_LIBS}.
7586 @c This is an incomplete kludge.  Make a real way to do it.
7587 @c If you need to check for other X functions or libraries yourself, then
7588 @c after calling this macro, add the contents of @code{X_EXTRA_LIBS} to
7589 @c @code{LIBS} temporarily, like this: (FIXME - add example)
7590 @end defmac
7592 @anchor{AC_SYS_INTERPRETER}
7593 @defmac AC_SYS_INTERPRETER
7594 @acindex{SYS_INTERPRETER}
7595 Check whether the system supports starting scripts with a line of the
7596 form @samp{#!/bin/sh} to select the interpreter to use for the script.
7597 After running this macro, shell code in @file{configure.ac} can check
7598 the shell variable @code{interpval}; it is set to @samp{yes}
7599 if the system supports @samp{#!}, @samp{no} if not.
7600 @end defmac
7602 @defmac AC_SYS_LARGEFILE
7603 @acindex{SYS_LARGEFILE}
7604 @cvindex _FILE_OFFSET_BITS
7605 @cvindex _LARGE_FILES
7606 @ovindex CC
7607 @cindex Large file support
7608 @cindex LFS
7609 Arrange for 64-bit file offsets, known as
7610 @uref{http://@/www.unix-systems@/.org/@/version2/@/whatsnew/@/lfs20mar.html,
7611 large-file support}.  On some hosts, one must use special compiler
7612 options to build programs that can access large files.  Append any such
7613 options to the output variable @code{CC}.  Define
7614 @code{_FILE_OFFSET_BITS} and @code{_LARGE_FILES} if necessary.
7616 Large-file support can be disabled by configuring with the
7617 @option{--disable-largefile} option.
7619 If you use this macro, check that your program works even when
7620 @code{off_t} is wider than @code{long int}, since this is common when
7621 large-file support is enabled.  For example, it is not correct to print
7622 an arbitrary @code{off_t} value @code{X} with @code{printf ("%ld",
7623 (long int) X)}.
7625 The LFS introduced the @code{fseeko} and @code{ftello} functions to
7626 replace their C counterparts @code{fseek} and @code{ftell} that do not
7627 use @code{off_t}.  Take care to use @code{AC_FUNC_FSEEKO} to make their
7628 prototypes available when using them and large-file support is
7629 enabled.
7630 @end defmac
7632 @anchor{AC_SYS_LONG_FILE_NAMES}
7633 @defmac AC_SYS_LONG_FILE_NAMES
7634 @acindex{SYS_LONG_FILE_NAMES}
7635 @cvindex HAVE_LONG_FILE_NAMES
7636 If the system supports file names longer than 14 characters, define
7637 @code{HAVE_LONG_FILE_NAMES}.
7638 @end defmac
7640 @defmac AC_SYS_POSIX_TERMIOS
7641 @acindex{SYS_POSIX_TERMIOS}
7642 @cindex Posix termios headers
7643 @cindex termios Posix headers
7644 Check to see if the Posix termios headers and functions are available on the
7645 system.  If so, set the shell variable @code{ac_cv_sys_posix_termios} to
7646 @samp{yes}.  If not, set the variable to @samp{no}.
7647 @end defmac
7649 @node Posix Variants
7650 @section Posix Variants
7652 The following macro makes it possible to use features of Posix that are
7653 extensions to C, as well as platform extensions not defined by Posix.
7655 @anchor{AC_USE_SYSTEM_EXTENSIONS}
7656 @defmac AC_USE_SYSTEM_EXTENSIONS
7657 @acindex{USE_SYSTEM_EXTENSIONS}
7658 @cvindex _ALL_SOURCE
7659 @cvindex _GNU_SOURCE
7660 @cvindex _MINIX
7661 @cvindex _POSIX_1_SOURCE
7662 @cvindex _POSIX_PTHREAD_SEMANTICS
7663 @cvindex _POSIX_SOURCE
7664 @cvindex _TANDEM_SOURCE
7665 @cvindex __EXTENSIONS__
7666 This macro was introduced in Autoconf 2.60.  If possible, enable
7667 extensions to C or Posix on hosts that normally disable the extensions,
7668 typically due to standards-conformance namespace issues.  This should be
7669 called before any macros that run the C compiler.  The following
7670 preprocessor macros are defined where appropriate:
7672 @table @code
7673 @item _GNU_SOURCE
7674 Enable extensions on @acronym{GNU}/Linux.
7675 @item __EXTENSIONS__
7676 Enable general extensions on Solaris.
7677 @item _POSIX_PTHREAD_SEMANTICS
7678 Enable threading extensions on Solaris.
7679 @item _TANDEM_SOURCE
7680 Enable extensions for the @acronym{HP} NonStop platform.
7681 @item _ALL_SOURCE
7682 Enable extensions for @acronym{AIX} 3, and for Interix.
7683 @item _POSIX_SOURCE
7684 Enable Posix functions for Minix.
7685 @item _POSIX_1_SOURCE
7686 Enable additional Posix functions for Minix.
7687 @item _MINIX
7688 Identify Minix platform.  This particular preprocessor macro is
7689 obsolescent, and may be removed in a future release of Autoconf.
7690 @end table
7691 @end defmac
7694 @node Erlang Libraries
7695 @section Erlang Libraries
7696 @cindex Erlang, Library, checking
7698 The following macros check for an installation of Erlang/OTP, and for the
7699 presence of certain Erlang libraries.  All those macros require the
7700 configuration of an Erlang interpreter and an Erlang compiler
7701 (@pxref{Erlang Compiler and Interpreter}).
7703 @defmac AC_ERLANG_SUBST_ROOT_DIR
7704 @acindex{ERLANG_SUBST_ROOT_DIR}
7705 @ovindex ERLANG_ROOT_DIR
7707 Set the output variable @code{ERLANG_ROOT_DIR} to the path to the base
7708 directory in which Erlang/OTP is installed (as returned by Erlang's
7709 @code{code:root_dir/0} function).  The result of this test is cached if
7710 caching is enabled when running @command{configure}.
7711 @end defmac
7713 @defmac AC_ERLANG_SUBST_LIB_DIR
7714 @acindex{ERLANG_SUBST_LIB_DIR}
7715 @ovindex ERLANG_LIB_DIR
7717 Set the output variable @code{ERLANG_LIB_DIR} to the path of the library
7718 directory of Erlang/OTP (as returned by Erlang's
7719 @code{code:lib_dir/0} function), which subdirectories each contain an installed
7720 Erlang/OTP library.  The result of this test is cached if caching is enabled
7721 when running @command{configure}.
7722 @end defmac
7724 @defmac AC_ERLANG_CHECK_LIB (@var{library}, @ovar{action-if-found}, @
7725   @ovar{action-if-not-found})
7726 @acindex{ERLANG_CHECK_LIB}
7727 @ovindex ERLANG_LIB_DIR_@var{library}
7728 @ovindex ERLANG_LIB_VER_@var{library}
7730 Test whether the Erlang/OTP library @var{library} is installed by
7731 calling Erlang's @code{code:lib_dir/1} function.  The result of this
7732 test is cached if caching is enabled when running @command{configure}.
7733 @var{action-if-found} is a list of shell commands to run if the library
7734 is installed; @var{action-if-not-found} is a list of shell commands to
7735 run if it is not.  Additionally, if the library is installed, the output
7736 variable @samp{ERLANG_LIB_DIR_@var{library}} is set to the path to the
7737 library installation directory, and the output variable
7738 @samp{ERLANG_LIB_VER_@var{library}} is set to the version number that is
7739 part of the subdirectory name, if it is in the standard form
7740 (@code{@var{library}-@var{version}}).  If the directory name does not
7741 have a version part, @samp{ERLANG_LIB_VER_@var{library}} is set to the
7742 empty string.  If the library is not installed,
7743 @samp{ERLANG_LIB_DIR_@var{library}} and
7744 @samp{ERLANG_LIB_VER_@var{library}} are set to @code{"not found"}.  For
7745 example, to check if library @code{stdlib} is installed:
7747 @example
7748 AC_ERLANG_CHECK_LIB([stdlib],
7749   [echo "stdlib version \"$ERLANG_LIB_VER_stdlib\""
7750    echo "is installed in \"$ERLANG_LIB_DIR_stdlib\""],
7751   [AC_MSG_ERROR([stdlib was not found!])])
7752 @end example
7753 @end defmac
7755 In addition to the above macros, which test installed Erlang libraries, the
7756 following macros determine the paths to the directories into which newly built
7757 Erlang libraries are to be installed:
7759 @defmac AC_ERLANG_SUBST_INSTALL_LIB_DIR
7760 @acindex{ERLANG_SUBST_INSTALL_LIB_DIR}
7761 @ovindex ERLANG_INSTALL_LIB_DIR
7763 Set the @code{ERLANG_INSTALL_LIB_DIR} output variable to the directory into
7764 which every built Erlang library should be installed in a separate
7765 subdirectory.
7766 If this variable is not set in the environment when @command{configure} runs,
7767 its default value is @code{$ERLANG_LIB_DIR}, which value is set by the
7768 @code{AC_ERLANG_SUBST_LIB_DIR} macro.
7769 @end defmac
7771 @defmac AC_ERLANG_SUBST_INSTALL_LIB_SUBDIR (@var{library}, @var{version})
7772 @acindex{ERLANG_SUBST_INSTALL_LIB_SUBDIR}
7773 @ovindex ERLANG_INSTALL_LIB_DIR_@var{library}
7775 Set the @samp{ERLANG_INSTALL_LIB_DIR_@var{library}} output variable to the
7776 directory into which the built Erlang library @var{library} version
7777 @var{version} should be installed.  If this variable is not set in the
7778 environment when @command{configure} runs, its default value is
7779 @samp{$ERLANG_INSTALL_LIB_DIR/@var{library}-@var{version}}, the value of the
7780 @code{ERLANG_INSTALL_LIB_DIR} variable being set by the
7781 @code{AC_ERLANG_SUBST_INSTALL_LIB_DIR} macro.
7782 @end defmac
7788 @c ========================================================= Writing Tests
7790 @node Writing Tests
7791 @chapter Writing Tests
7793 If the existing feature tests don't do something you need, you have to
7794 write new ones.  These macros are the building blocks.  They provide
7795 ways for other macros to check whether various kinds of features are
7796 available and report the results.
7798 This chapter contains some suggestions and some of the reasons why the
7799 existing tests are written the way they are.  You can also learn a lot
7800 about how to write Autoconf tests by looking at the existing ones.  If
7801 something goes wrong in one or more of the Autoconf tests, this
7802 information can help you understand the assumptions behind them, which
7803 might help you figure out how to best solve the problem.
7805 These macros check the output of the compiler system of the current
7806 language (@pxref{Language Choice}).  They do not cache the results of
7807 their tests for future use (@pxref{Caching Results}), because they don't
7808 know enough about the information they are checking for to generate a
7809 cache variable name.  They also do not print any messages, for the same
7810 reason.  The checks for particular kinds of features call these macros
7811 and do cache their results and print messages about what they're
7812 checking for.
7814 When you write a feature test that could be applicable to more than one
7815 software package, the best thing to do is encapsulate it in a new macro.
7816 @xref{Writing Autoconf Macros}, for how to do that.
7818 @menu
7819 * Language Choice::             Selecting which language to use for testing
7820 * Writing Test Programs::       Forging source files for compilers
7821 * Running the Preprocessor::    Detecting preprocessor symbols
7822 * Running the Compiler::        Detecting language or header features
7823 * Running the Linker::          Detecting library features
7824 * Runtime::                     Testing for runtime features
7825 * Systemology::                 A zoology of operating systems
7826 * Multiple Cases::              Tests for several possible values
7827 @end menu
7829 @node Language Choice
7830 @section Language Choice
7831 @cindex Language
7833 Autoconf-generated @command{configure} scripts check for the C compiler and
7834 its features by default.  Packages that use other programming languages
7835 (maybe more than one, e.g., C and C++) need to test features of the
7836 compilers for the respective languages.  The following macros determine
7837 which programming language is used in the subsequent tests in
7838 @file{configure.ac}.
7840 @anchor{AC_LANG}
7841 @defmac AC_LANG (@var{language})
7842 Do compilation tests using the compiler, preprocessor, and file
7843 extensions for the specified @var{language}.
7845 Supported languages are:
7847 @table @samp
7848 @item C
7849 Do compilation tests using @code{CC} and @code{CPP} and use extension
7850 @file{.c} for test programs.  Use compilation flags: @code{CPPFLAGS} with
7851 @code{CPP}, and both @code{CPPFLAGS} and @code{CFLAGS} with @code{CC}.
7853 @item C++
7854 Do compilation tests using @code{CXX} and @code{CXXCPP} and use
7855 extension @file{.C} for test programs.  Use compilation flags:
7856 @code{CPPFLAGS} with @code{CXXCPP}, and both @code{CPPFLAGS} and
7857 @code{CXXFLAGS} with @code{CXX}.
7859 @item Fortran 77
7860 Do compilation tests using @code{F77} and use extension @file{.f} for
7861 test programs.  Use compilation flags: @code{FFLAGS}.
7863 @item Fortran
7864 Do compilation tests using @code{FC} and use extension @file{.f} (or
7865 whatever has been set by @code{AC_FC_SRCEXT}) for test programs.  Use
7866 compilation flags: @code{FCFLAGS}.
7868 @item Erlang
7869 @ovindex ERLC
7870 @ovindex ERL
7871 @ovindex ERLCFLAGS
7872 Compile and execute tests using @code{ERLC} and @code{ERL} and use extension
7873 @file{.erl} for test Erlang modules.  Use compilation flags: @code{ERLCFLAGS}.
7875 @item Objective C
7876 Do compilation tests using @code{OBJC} and @code{OBJCPP} and use
7877 extension @file{.m} for test programs.  Use compilation flags:
7878 @code{CPPFLAGS} with @code{OBJCPP}, and both @code{CPPFLAGS} and
7879 @code{OBJCFLAGS} with @code{OBJC}.
7880 @end table
7881 @end defmac
7883 @anchor{AC_LANG_PUSH}
7884 @defmac AC_LANG_PUSH (@var{language})
7885 @acindex{LANG_PUSH}
7886 Remember the current language (as set by @code{AC_LANG}) on a stack, and
7887 then select the @var{language}.  Use this macro and @code{AC_LANG_POP}
7888 in macros that need to temporarily switch to a particular language.
7889 @end defmac
7891 @defmac AC_LANG_POP (@ovar{language})
7892 @acindex{LANG_POP}
7893 Select the language that is saved on the top of the stack, as set by
7894 @code{AC_LANG_PUSH}, and remove it from the stack.
7896 If given, @var{language} specifies the language we just @emph{quit}.  It
7897 is a good idea to specify it when it's known (which should be the
7898 case@dots{}), since Autoconf detects inconsistencies.
7900 @example
7901 AC_LANG_PUSH([Fortran 77])
7902 # Perform some tests on Fortran 77.
7903 # @dots{}
7904 AC_LANG_POP([Fortran 77])
7905 @end example
7906 @end defmac
7908 @defmac AC_LANG_ASSERT (@var{language})
7909 @acindex{LANG_ASSERT} Check statically that the current language is
7910 @var{language}.  You should use this in your language specific macros
7911 to avoid that they be called with an inappropriate language.
7913 This macro runs only at @command{autoconf} time, and incurs no cost at
7914 @command{configure} time.  Sadly enough and because Autoconf is a two
7915 layer language @footnote{Because M4 is not aware of Sh code,
7916 especially conditionals, some optimizations that look nice statically
7917 may produce incorrect results at runtime.}, the macros
7918 @code{AC_LANG_PUSH} and @code{AC_LANG_POP} cannot be ``optimizing'',
7919 therefore as much as possible you ought to avoid using them to wrap
7920 your code, rather, require from the user to run the macro with a
7921 correct current language, and check it with @code{AC_LANG_ASSERT}.
7922 And anyway, that may help the user understand she is running a Fortran
7923 macro while expecting a result about her Fortran 77 compiler@enddots{}
7924 @end defmac
7927 @defmac AC_REQUIRE_CPP
7928 @acindex{REQUIRE_CPP}
7929 Ensure that whichever preprocessor would currently be used for tests has
7930 been found.  Calls @code{AC_REQUIRE} (@pxref{Prerequisite Macros}) with an
7931 argument of either @code{AC_PROG_CPP} or @code{AC_PROG_CXXCPP},
7932 depending on which language is current.
7933 @end defmac
7936 @node Writing Test Programs
7937 @section Writing Test Programs
7939 Autoconf tests follow a common scheme: feed some program with some
7940 input, and most of the time, feed a compiler with some source file.
7941 This section is dedicated to these source samples.
7943 @menu
7944 * Guidelines::                  General rules for writing test programs
7945 * Test Functions::              Avoiding pitfalls in test programs
7946 * Generating Sources::          Source program boilerplate
7947 @end menu
7949 @node Guidelines
7950 @subsection Guidelines for Test Programs
7952 The most important rule to follow when writing testing samples is:
7954 @center @emph{Look for realism.}
7956 This motto means that testing samples must be written with the same
7957 strictness as real programs are written.  In particular, you should
7958 avoid ``shortcuts'' and simplifications.
7960 Don't just play with the preprocessor if you want to prepare a
7961 compilation.  For instance, using @command{cpp} to check whether a header is
7962 functional might let your @command{configure} accept a header which
7963 causes some @emph{compiler} error.  Do not hesitate to check a header with
7964 other headers included before, especially required headers.
7966 Make sure the symbols you use are properly defined, i.e., refrain for
7967 simply declaring a function yourself instead of including the proper
7968 header.
7970 Test programs should not write to standard output.  They
7971 should exit with status 0 if the test succeeds, and with status 1
7972 otherwise, so that success
7973 can be distinguished easily from a core dump or other failure;
7974 segmentation violations and other failures produce a nonzero exit
7975 status.  Unless you arrange for @code{exit} to be declared, test
7976 programs should @code{return}, not @code{exit}, from @code{main},
7977 because on many systems @code{exit} is not declared by default.
7979 Test programs can use @code{#if} or @code{#ifdef} to check the values of
7980 preprocessor macros defined by tests that have already run.  For
7981 example, if you call @code{AC_HEADER_STDBOOL}, then later on in
7982 @file{configure.ac} you can have a test program that includes
7983 @file{stdbool.h} conditionally:
7985 @example
7986 @group
7987 #ifdef HAVE_STDBOOL_H
7988 # include <stdbool.h>
7989 #endif
7990 @end group
7991 @end example
7993 Both @code{#if HAVE_STDBOOL_H} and @code{#ifdef HAVE_STDBOOL_H} will
7994 work with any standard C compiler.  Some developers prefer @code{#if}
7995 because it is easier to read, while others prefer @code{#ifdef} because
7996 it avoids diagnostics with picky compilers like @acronym{GCC} with the
7997 @option{-Wundef} option.
7999 If a test program needs to use or create a data file, give it a name
8000 that starts with @file{conftest}, such as @file{conftest.data}.  The
8001 @command{configure} script cleans up by running @samp{rm -f -r conftest*}
8002 after running test programs and if the script is interrupted.
8004 @node Test Functions
8005 @subsection Test Functions
8007 These days it's safe to assume support for function prototypes
8008 (introduced in C89).
8010 Functions that test programs declare should also be conditionalized for
8011 C++, which requires @samp{extern "C"} prototypes.  Make sure to not
8012 include any header files containing clashing prototypes.
8014 @example
8015 #ifdef __cplusplus
8016 extern "C"
8017 #endif
8018 void *valloc (size_t);
8019 @end example
8021 If a test program calls a function with invalid parameters (just to see
8022 whether it exists), organize the program to ensure that it never invokes
8023 that function.  You can do this by calling it in another function that is
8024 never invoked.  You can't do it by putting it after a call to
8025 @code{exit}, because @acronym{GCC} version 2 knows that @code{exit}
8026 never returns
8027 and optimizes out any code that follows it in the same block.
8029 If you include any header files, be sure to call the functions
8030 relevant to them with the correct number of arguments, even if they are
8031 just 0, to avoid compilation errors due to prototypes.  @acronym{GCC}
8032 version 2
8033 has internal prototypes for several functions that it automatically
8034 inlines; for example, @code{memcpy}.  To avoid errors when checking for
8035 them, either pass them the correct number of arguments or redeclare them
8036 with a different return type (such as @code{char}).
8039 @node Generating Sources
8040 @subsection Generating Sources
8042 Autoconf provides a set of macros that can be used to generate test
8043 source files.  They are written to be language generic, i.e., they
8044 actually depend on the current language (@pxref{Language Choice}) to
8045 ``format'' the output properly.
8048 @defmac AC_LANG_CONFTEST (@var{source})
8049 @acindex{LANG_CONFTEST}
8050 Save the @var{source} text in the current test source file:
8051 @file{conftest.@var{extension}} where the @var{extension} depends on the
8052 current language.
8054 Note that the @var{source} is evaluated exactly once, like regular
8055 Autoconf macro arguments, and therefore (i) you may pass a macro
8056 invocation, (ii) if not, be sure to double quote if needed.
8057 @end defmac
8059 @defmac AC_LANG_SOURCE (@var{source})
8060 @acindex{LANG_SOURCE}
8061 Expands into the @var{source}, with the definition of
8062 all the @code{AC_DEFINE} performed so far.
8063 @end defmac
8065 For instance executing (observe the double quotation!):
8067 @example
8068 AC_INIT([Hello], [1.0], [bug-hello@@example.org])
8069 AC_DEFINE([HELLO_WORLD], ["Hello, World\n"],
8070   [Greetings string.])
8071 AC_LANG(C)
8072 AC_LANG_CONFTEST(
8073    [AC_LANG_SOURCE([[const char hw[] = "Hello, World\n";]])])
8074 gcc -E -dD -o - conftest.c
8075 @end example
8077 @noindent
8078 results in:
8080 @example
8081 @dots{}
8082 # 1 "conftest.c"
8084 #define PACKAGE_NAME "Hello"
8085 #define PACKAGE_TARNAME "hello"
8086 #define PACKAGE_VERSION "1.0"
8087 #define PACKAGE_STRING "Hello 1.0"
8088 #define PACKAGE_BUGREPORT "bug-hello@@example.org"
8089 #define HELLO_WORLD "Hello, World\n"
8091 const char hw[] = "Hello, World\n";
8092 @end example
8094 When the test language is Fortran or Erlang, the @code{AC_DEFINE} definitions
8095 are not automatically translated into constants in the source code by this
8096 macro.
8098 @defmac AC_LANG_PROGRAM (@var{prologue}, @var{body})
8099 @acindex{LANG_PROGRAM}
8100 Expands into a source file which consists of the @var{prologue}, and
8101 then @var{body} as body of the main function (e.g., @code{main} in
8102 C).  Since it uses @code{AC_LANG_SOURCE}, the features of the latter are
8103 available.
8104 @end defmac
8106 For instance:
8108 @example
8109 AC_INIT([Hello], [1.0], [bug-hello@@example.org])
8110 AC_DEFINE([HELLO_WORLD], ["Hello, World\n"],
8111   [Greetings string.])
8112 AC_LANG_CONFTEST(
8113 [AC_LANG_PROGRAM([[const char hw[] = "Hello, World\n";]],
8114                  [[fputs (hw, stdout);]])])
8115 gcc -E -dD -o - conftest.c
8116 @end example
8118 @noindent
8119 results in:
8121 @example
8122 @dots{}
8123 # 1 "conftest.c"
8125 #define PACKAGE_NAME "Hello"
8126 #define PACKAGE_TARNAME "hello"
8127 #define PACKAGE_VERSION "1.0"
8128 #define PACKAGE_STRING "Hello 1.0"
8129 #define PACKAGE_BUGREPORT "bug-hello@@example.org"
8130 #define HELLO_WORLD "Hello, World\n"
8132 const char hw[] = "Hello, World\n";
8134 main ()
8136 fputs (hw, stdout);
8137   ;
8138   return 0;
8140 @end example
8142 In Erlang tests, the created source file is that of an Erlang module called
8143 @code{conftest} (@file{conftest.erl}).  This module defines and exports
8144 at least
8145 one @code{start/0} function, which is called to perform the test.  The
8146 @var{prologue} is optional code that is inserted between the module header and
8147 the @code{start/0} function definition.  @var{body} is the body of the
8148 @code{start/0} function without the final period (@pxref{Runtime}, about
8149 constraints on this function's behavior).
8151 For instance:
8153 @example
8154 AC_INIT([Hello], [1.0], [bug-hello@@example.org])
8155 AC_LANG(Erlang)
8156 AC_LANG_CONFTEST(
8157 [AC_LANG_PROGRAM([[-define(HELLO_WORLD, "Hello, world!").]],
8158                  [[io:format("~s~n", [?HELLO_WORLD])]])])
8159 cat conftest.erl
8160 @end example
8162 @noindent
8163 results in:
8165 @example
8166 -module(conftest).
8167 -export([start/0]).
8168 -define(HELLO_WORLD, "Hello, world!").
8169 start() ->
8170 io:format("~s~n", [?HELLO_WORLD])
8172 @end example
8174 @defmac AC_LANG_CALL (@var{prologue}, @var{function})
8175 @acindex{LANG_CALL}
8176 Expands into a source file which consists of the @var{prologue}, and
8177 then a call to the @var{function} as body of the main function (e.g.,
8178 @code{main} in C).  Since it uses @code{AC_LANG_PROGRAM}, the feature
8179 of the latter are available.
8181 This function will probably be replaced in the future by a version
8182 which would enable specifying the arguments.  The use of this macro is
8183 not encouraged, as it violates strongly the typing system.
8185 This macro cannot be used for Erlang tests.
8186 @end defmac
8188 @defmac AC_LANG_FUNC_LINK_TRY (@var{function})
8189 @acindex{LANG_FUNC_LINK_TRY}
8190 Expands into a source file which uses the @var{function} in the body of
8191 the main function (e.g., @code{main} in C).  Since it uses
8192 @code{AC_LANG_PROGRAM}, the features of the latter are available.
8194 As @code{AC_LANG_CALL}, this macro is documented only for completeness.
8195 It is considered to be severely broken, and in the future will be
8196 removed in favor of actual function calls (with properly typed
8197 arguments).
8199 This macro cannot be used for Erlang tests.
8200 @end defmac
8202 @node Running the Preprocessor
8203 @section Running the Preprocessor
8205 Sometimes one might need to run the preprocessor on some source file.
8206 @emph{Usually it is a bad idea}, as you typically need to @emph{compile}
8207 your project, not merely run the preprocessor on it; therefore you
8208 certainly want to run the compiler, not the preprocessor.  Resist the
8209 temptation of following the easiest path.
8211 Nevertheless, if you need to run the preprocessor, then use
8212 @code{AC_PREPROC_IFELSE}.
8214 The macros described in this section cannot be used for tests in Erlang or
8215 Fortran, since those languages require no preprocessor.
8217 @anchor{AC_PREPROC_IFELSE}
8218 @defmac AC_PREPROC_IFELSE (@var{input}, @ovar{action-if-true}, @
8219   @ovar{action-if-false})
8220 @acindex{PREPROC_IFELSE}
8221 Run the preprocessor of the current language (@pxref{Language Choice})
8222 on the @var{input}, run the shell commands @var{action-if-true} on
8223 success, @var{action-if-false} otherwise.  The @var{input} can be made
8224 by @code{AC_LANG_PROGRAM} and friends.
8226 This macro uses @code{CPPFLAGS}, but not @code{CFLAGS}, because
8227 @option{-g}, @option{-O}, etc.@: are not valid options to many C
8228 preprocessors.
8230 It is customary to report unexpected failures with
8231 @code{AC_MSG_FAILURE}.
8232 @end defmac
8234 For instance:
8236 @example
8237 AC_INIT([Hello], [1.0], [bug-hello@@example.org])
8238 AC_DEFINE([HELLO_WORLD], ["Hello, World\n"],
8239   [Greetings string.])
8240 AC_PREPROC_IFELSE(
8241    [AC_LANG_PROGRAM([[const char hw[] = "Hello, World\n";]],
8242                     [[fputs (hw, stdout);]])],
8243    [AC_MSG_RESULT([OK])],
8244    [AC_MSG_FAILURE([unexpected preprocessor failure])])
8245 @end example
8247 @noindent
8248 results in:
8250 @example
8251 checking for gcc... gcc
8252 checking for C compiler default output file name... a.out
8253 checking whether the C compiler works... yes
8254 checking whether we are cross compiling... no
8255 checking for suffix of executables...
8256 checking for suffix of object files... o
8257 checking whether we are using the GNU C compiler... yes
8258 checking whether gcc accepts -g... yes
8259 checking for gcc option to accept ISO C89... none needed
8260 checking how to run the C preprocessor... gcc -E
8262 @end example
8264 @sp 1
8266 The macro @code{AC_TRY_CPP} (@pxref{Obsolete Macros}) used to play the
8267 role of @code{AC_PREPROC_IFELSE}, but double quotes its argument, making
8268 it impossible to use it to elaborate sources.  You are encouraged to
8269 get rid of your old use of the macro @code{AC_TRY_CPP} in favor of
8270 @code{AC_PREPROC_IFELSE}, but, in the first place, are you sure you need
8271 to run the @emph{preprocessor} and not the compiler?
8273 @anchor{AC_EGREP_HEADER}
8274 @defmac AC_EGREP_HEADER (@var{pattern}, @var{header-file}, @
8275   @var{action-if-found}, @ovar{action-if-not-found})
8276 @acindex{EGREP_HEADER}
8277 If the output of running the preprocessor on the system header file
8278 @var{header-file} matches the extended regular expression
8279 @var{pattern}, execute shell commands @var{action-if-found}, otherwise
8280 execute @var{action-if-not-found}.
8281 @end defmac
8283 @anchor{AC_EGREP_CPP}
8284 @defmac AC_EGREP_CPP (@var{pattern}, @var{program}, @
8285   @ovar{action-if-found}, @ovar{action-if-not-found})
8286 @acindex{EGREP_CPP}
8287 @var{program} is the text of a C or C++ program, on which shell
8288 variable, back quote, and backslash substitutions are performed.  If the
8289 output of running the preprocessor on @var{program} matches the
8290 extended regular expression @var{pattern}, execute shell commands
8291 @var{action-if-found}, otherwise execute @var{action-if-not-found}.
8292 @end defmac
8296 @node Running the Compiler
8297 @section Running the Compiler
8299 To check for a syntax feature of the current language's (@pxref{Language
8300 Choice}) compiler, such as whether it recognizes a certain keyword, or
8301 simply to try some library feature, use @code{AC_COMPILE_IFELSE} to try
8302 to compile a small program that uses that feature.
8304 @defmac AC_COMPILE_IFELSE (@var{input}, @ovar{action-if-true}, @
8305   @ovar{action-if-false})
8306 @acindex{COMPILE_IFELSE}
8307 Run the compiler and compilation flags of the current language
8308 (@pxref{Language Choice}) on the @var{input}, run the shell commands
8309 @var{action-if-true} on success, @var{action-if-false} otherwise.  The
8310 @var{input} can be made by @code{AC_LANG_PROGRAM} and friends.
8312 It is customary to report unexpected failures with
8313 @code{AC_MSG_FAILURE}.  This macro does not try to link; use
8314 @code{AC_LINK_IFELSE} if you need to do that (@pxref{Running the
8315 Linker}).
8316 @end defmac
8318 @ovindex ERL
8319 For tests in Erlang, the @var{input} must be the source code of a module named
8320 @code{conftest}.  @code{AC_COMPILE_IFELSE} generates a @file{conftest.beam}
8321 file that can be interpreted by the Erlang virtual machine (@code{ERL}).  It is
8322 recommended to use @code{AC_LANG_PROGRAM} to specify the test program,
8323 to ensure that the Erlang module has the right name.
8325 @node Running the Linker
8326 @section Running the Linker
8328 To check for a library, a function, or a global variable, Autoconf
8329 @command{configure} scripts try to compile and link a small program that
8330 uses it.  This is unlike Metaconfig, which by default uses @code{nm} or
8331 @code{ar} on the C library to try to figure out which functions are
8332 available.  Trying to link with the function is usually a more reliable
8333 approach because it avoids dealing with the variations in the options
8334 and output formats of @code{nm} and @code{ar} and in the location of the
8335 standard libraries.  It also allows configuring for cross-compilation or
8336 checking a function's runtime behavior if needed.  On the other hand,
8337 it can be slower than scanning the libraries once, but accuracy is more
8338 important than speed.
8340 @code{AC_LINK_IFELSE} is used to compile test programs to test for
8341 functions and global variables.  It is also used by @code{AC_CHECK_LIB}
8342 to check for libraries (@pxref{Libraries}), by adding the library being
8343 checked for to @code{LIBS} temporarily and trying to link a small
8344 program.
8346 @anchor{AC_LINK_IFELSE}
8347 @defmac AC_LINK_IFELSE (@var{input}, @ovar{action-if-true}, @
8348   @ovar{action-if-false})
8349 @acindex{LINK_IFELSE}
8350 Run the compiler (and compilation flags) and the linker of the current
8351 language (@pxref{Language Choice}) on the @var{input}, run the shell
8352 commands @var{action-if-true} on success, @var{action-if-false}
8353 otherwise.  The @var{input} can be made by @code{AC_LANG_PROGRAM} and
8354 friends.
8356 @code{LDFLAGS} and @code{LIBS} are used for linking, in addition to the
8357 current compilation flags.
8359 It is customary to report unexpected failures with
8360 @code{AC_MSG_FAILURE}.  This macro does not try to execute the program;
8361 use @code{AC_RUN_IFELSE} if you need to do that (@pxref{Runtime}).
8362 @end defmac
8364 The @code{AC_LINK_IFELSE} macro cannot be used for Erlang tests, since Erlang
8365 programs are interpreted and do not require linking.
8369 @node Runtime
8370 @section Checking Runtime Behavior
8372 Sometimes you need to find out how a system performs at runtime, such
8373 as whether a given function has a certain capability or bug.  If you
8374 can, make such checks when your program runs instead of when it is
8375 configured.  You can check for things like the machine's endianness when
8376 your program initializes itself.
8378 If you really need to test for a runtime behavior while configuring,
8379 you can write a test program to determine the result, and compile and
8380 run it using @code{AC_RUN_IFELSE}.  Avoid running test programs if
8381 possible, because this prevents people from configuring your package for
8382 cross-compiling.
8384 @anchor{AC_RUN_IFELSE}
8385 @defmac AC_RUN_IFELSE (@var{input}, @ovar{action-if-true}, @
8386   @ovar{action-if-false}, @ovar{action-if-cross-compiling})
8387 @acindex{RUN_IFELSE}
8388 If @var{program} compiles and links successfully and returns an exit
8389 status of 0 when executed, run shell commands @var{action-if-true}.
8390 Otherwise, run shell commands @var{action-if-false}.
8392 The @var{input} can be made by @code{AC_LANG_PROGRAM} and friends.
8393 @code{LDFLAGS} and @code{LIBS} are used for linking, in addition to the
8394 compilation flags of the current language (@pxref{Language Choice}).
8396 If the compiler being used does not produce executables that run on the
8397 system where @command{configure} is being run, then the test program is
8398 not run.  If the optional shell commands @var{action-if-cross-compiling}
8399 are given, they are run instead.  Otherwise, @command{configure} prints
8400 an error message and exits.
8402 In the @var{action-if-false} section, the failing exit status is
8403 available in the shell variable @samp{$?}.  This exit status might be
8404 that of a failed compilation, or it might be that of a failed program
8405 execution.
8407 It is customary to report unexpected failures with
8408 @code{AC_MSG_FAILURE}.
8409 @end defmac
8411 Try to provide a pessimistic default value to use when cross-compiling
8412 makes runtime tests impossible.  You do this by passing the optional
8413 last argument to @code{AC_RUN_IFELSE}.  @command{autoconf} prints a
8414 warning message when creating @command{configure} each time it
8415 encounters a call to @code{AC_RUN_IFELSE} with no
8416 @var{action-if-cross-compiling} argument given.  You may ignore the
8417 warning, though users cannot configure your package for
8418 cross-compiling.  A few of the macros distributed with Autoconf produce
8419 this warning message.
8421 To configure for cross-compiling you can also choose a value for those
8422 parameters based on the canonical system name (@pxref{Manual
8423 Configuration}).  Alternatively, set up a test results cache file with
8424 the correct values for the host system (@pxref{Caching Results}).
8426 @ovindex cross_compiling
8427 To provide a default for calls of @code{AC_RUN_IFELSE} that are embedded
8428 in other macros, including a few of the ones that come with Autoconf,
8429 you can test whether the shell variable @code{cross_compiling} is set to
8430 @samp{yes}, and then use an alternate method to get the results instead
8431 of calling the macros.
8433 It is also permissible to temporarily assign to @code{cross_compiling}
8434 in order to force tests to behave as though they are in a
8435 cross-compilation environment, particularly since this provides a way to
8436 test your @var{action-if-cross-compiling} even when you are not using a
8437 cross-compiler.
8439 @example
8440 # We temporarily set cross-compile mode to force AC_COMPUTE_INT
8441 # to use the slow link-only method
8442 save_cross_compiling=$cross_compiling
8443 cross_compiling=yes
8444 AC_COMPUTE_INT([@dots{}])
8445 cross_compiling=$save_cross_compiling
8446 @end example
8448 A C or C++ runtime test should be portable.
8449 @xref{Portable C and C++}.
8451 Erlang tests must exit themselves the Erlang VM by calling the @code{halt/1}
8452 function: the given status code is used to determine the success of the test
8453 (status is @code{0}) or its failure (status is different than @code{0}), as
8454 explained above.  It must be noted that data output through the standard output
8455 (e.g., using @code{io:format/2}) may be truncated when halting the VM.
8456 Therefore, if a test must output configuration information, it is recommended
8457 to create and to output data into the temporary file named @file{conftest.out},
8458 using the functions of module @code{file}.  The @code{conftest.out} file is
8459 automatically deleted by the @code{AC_RUN_IFELSE} macro.  For instance, a
8460 simplified implementation of Autoconf's @code{AC_ERLANG_SUBST_LIB_DIR}
8461 macro is:
8463 @example
8464 AC_INIT([LibdirTest], [1.0], [bug-libdirtest@@example.org])
8465 AC_ERLANG_NEED_ERL
8466 AC_LANG(Erlang)
8467 AC_RUN_IFELSE(
8468   [AC_LANG_PROGRAM([], [dnl
8469     file:write_file("conftest.out", code:lib_dir()),
8470     halt(0)])],
8471   [echo "code:lib_dir() returned: `cat conftest.out`"],
8472   [AC_MSG_FAILURE([test Erlang program execution failed])])
8473 @end example
8476 @node Systemology
8477 @section Systemology
8478 @cindex Systemology
8480 This section aims at presenting some systems and pointers to
8481 documentation.  It may help you addressing particular problems reported
8482 by users.
8484 @uref{http://@/www.opengroup.org/@/susv3, Posix-conforming systems} are
8485 derived from the @uref{http://@/www.bell-labs.com/@/history/@/unix/, Unix
8486 operating system}.
8488 The @uref{http://@/bhami.com/@/rosetta.html, Rosetta Stone for Unix}
8489 contains a table correlating the features of various Posix-conforming
8490 systems.  @uref{http://@/www.levenez.com/@/unix/, Unix History} is a
8491 simplified diagram of how many Unix systems were derived from each
8492 other.
8494 @uref{http://@/heirloom.sourceforge.net/, The Heirloom Project}
8495 provides some variants of traditional implementations of Unix utilities.
8497 @table @asis
8498 @item Darwin
8499 @cindex Darwin
8500 Darwin is also known as Mac OS X@.  Beware that the file system @emph{can} be
8501 case-preserving, but case insensitive.  This can cause nasty problems,
8502 since for instance the installation attempt for a package having an
8503 @file{INSTALL} file can result in @samp{make install} report that
8504 nothing was to be done!
8506 That's all dependent on whether the file system is a UFS (case
8507 sensitive) or HFS+ (case preserving).  By default Apple wants you to
8508 install the OS on HFS+.  Unfortunately, there are some pieces of
8509 software which really need to be built on UFS@.  We may want to rebuild
8510 Darwin to have both UFS and HFS+ available (and put the /local/build
8511 tree on the UFS).
8513 @item @acronym{QNX} 4.25
8514 @cindex @acronym{QNX} 4.25
8515 @c FIXME: Please, if you feel like writing something more precise,
8516 @c it'd be great.  In particular, I can't understand the difference with
8517 @c QNX Neutrino.
8518 @acronym{QNX} is a realtime operating system running on Intel architecture
8519 meant to be scalable from the small embedded systems to the hundred
8520 processor super-computer.  It claims to be Posix certified.  More
8521 information is available on the
8522 @uref{http://@/www.qnx.com/, @acronym{QNX} home page}.
8524 @item Tru64
8525 @cindex Tru64
8526 @uref{http://@/h30097.www3.hp.com/@/docs/,
8527 Documentation of several versions of Tru64} is available in different
8528 formats.
8530 @item Unix version 7
8531 @cindex Unix version 7
8532 @cindex V7
8533 Officially this was called the ``Seventh Edition'' of ``the @sc{unix}
8534 time-sharing system'' but we use the more-common name ``Unix version 7''.
8535 Documentation is available in the
8536 @uref{http://@/plan9.bell-labs.com/@/7thEdMan/, Unix Seventh Edition Manual}.
8537 Previous versions of Unix are called ``Unix version 6'', etc., but
8538 they were not as widely used.
8539 @end table
8542 @node Multiple Cases
8543 @section Multiple Cases
8545 Some operations are accomplished in several possible ways, depending on
8546 the OS variant.  Checking for them essentially requires a ``case
8547 statement''.  Autoconf does not directly provide one; however, it is
8548 easy to simulate by using a shell variable to keep track of whether a
8549 way to perform the operation has been found yet.
8551 Here is an example that uses the shell variable @code{fstype} to keep
8552 track of whether the remaining cases need to be checked.
8554 @example
8555 @group
8556 AC_MSG_CHECKING([how to get file system type])
8557 fstype=no
8558 # The order of these tests is important.
8559 AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <sys/statvfs.h>
8560 #include <sys/fstyp.h>]])],
8561                   [AC_DEFINE([FSTYPE_STATVFS], [1],
8562                      [Define if statvfs exists.])
8563                    fstype=SVR4])
8564 if test $fstype = no; then
8565   AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <sys/statfs.h>
8566 #include <sys/fstyp.h>]])],
8567                   [AC_DEFINE([FSTYPE_USG_STATFS], [1],
8568                      [Define if USG statfs.])
8569                    fstype=SVR3])
8571 if test $fstype = no; then
8572   AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <sys/statfs.h>
8573 #include <sys/vmount.h>]])]),
8574                   [AC_DEFINE([FSTYPE_AIX_STATFS], [1],
8575                      [Define if AIX statfs.])
8576                    fstype=AIX])
8578 # (more cases omitted here)
8579 AC_MSG_RESULT([$fstype])
8580 @end group
8581 @end example
8583 @c ====================================================== Results of Tests.
8585 @node Results
8586 @chapter Results of Tests
8588 Once @command{configure} has determined whether a feature exists, what can
8589 it do to record that information?  There are four sorts of things it can
8590 do: define a C preprocessor symbol, set a variable in the output files,
8591 save the result in a cache file for future @command{configure} runs, and
8592 print a message letting the user know the result of the test.
8594 @menu
8595 * Defining Symbols::            Defining C preprocessor symbols
8596 * Setting Output Variables::    Replacing variables in output files
8597 * Special Chars in Variables::  Characters to beware of in variables
8598 * Caching Results::             Speeding up subsequent @command{configure} runs
8599 * Printing Messages::           Notifying @command{configure} users
8600 @end menu
8602 @node Defining Symbols
8603 @section Defining C Preprocessor Symbols
8605 A common action to take in response to a feature test is to define a C
8606 preprocessor symbol indicating the results of the test.  That is done by
8607 calling @code{AC_DEFINE} or @code{AC_DEFINE_UNQUOTED}.
8609 By default, @code{AC_OUTPUT} places the symbols defined by these macros
8610 into the output variable @code{DEFS}, which contains an option
8611 @option{-D@var{symbol}=@var{value}} for each symbol defined.  Unlike in
8612 Autoconf version 1, there is no variable @code{DEFS} defined while
8613 @command{configure} is running.  To check whether Autoconf macros have
8614 already defined a certain C preprocessor symbol, test the value of the
8615 appropriate cache variable, as in this example:
8617 @example
8618 AC_CHECK_FUNC([vprintf], [AC_DEFINE([HAVE_VPRINTF], [1],
8619                           [Define if vprintf exists.])])
8620 if test "$ac_cv_func_vprintf" != yes; then
8621   AC_CHECK_FUNC([_doprnt], [AC_DEFINE([HAVE_DOPRNT], [1],
8622                             [Define if _doprnt exists.])])
8624 @end example
8626 If @code{AC_CONFIG_HEADERS} has been called, then instead of creating
8627 @code{DEFS}, @code{AC_OUTPUT} creates a header file by substituting the
8628 correct values into @code{#define} statements in a template file.
8629 @xref{Configuration Headers}, for more information about this kind of
8630 output.
8632 @defmac AC_DEFINE (@var{variable}, @var{value}, @ovar{description})
8633 @defmacx AC_DEFINE (@var{variable})
8634 @cvindex @var{variable}
8635 @acindex{DEFINE}
8636 Define @var{variable} to @var{value} (verbatim), by defining a C
8637 preprocessor macro for @var{variable}.  @var{variable} should be a C
8638 identifier, optionally suffixed by a parenthesized argument list to
8639 define a C preprocessor macro with arguments.  The macro argument list,
8640 if present, should be a comma-separated list of C identifiers, possibly
8641 terminated by an ellipsis @samp{...} if C99 syntax is employed.
8642 @var{variable} should not contain comments, white space, trigraphs,
8643 backslash-newlines, universal character names, or non-@acronym{ASCII}
8644 characters.
8646 @var{value} may contain backslash-escaped newlines, which will be
8647 preserved if you use @code{AC_CONFIG_HEADERS} but flattened if passed
8648 via @code{@@DEFS@@} (with no effect on the compilation, since the
8649 preprocessor sees only one line in the first place).  @var{value} should
8650 not contain raw newlines.  If you are not using
8651 @code{AC_CONFIG_HEADERS}, @var{value} should not contain any @samp{#}
8652 characters, as @command{make} tends to eat them.  To use a shell
8653 variable, use @code{AC_DEFINE_UNQUOTED} instead.
8655 @var{description} is only useful if you are using
8656 @code{AC_CONFIG_HEADERS}.  In this case, @var{description} is put into
8657 the generated @file{config.h.in} as the comment before the macro define.
8658 The following example defines the C preprocessor variable
8659 @code{EQUATION} to be the string constant @samp{"$a > $b"}:
8661 @example
8662 AC_DEFINE([EQUATION], ["$a > $b"],
8663   [Equation string.])
8664 @end example
8666 If neither @var{value} nor @var{description} are given, then
8667 @var{value} defaults to 1 instead of to the empty string.  This is for
8668 backwards compatibility with older versions of Autoconf, but this usage
8669 is obsolescent and may be withdrawn in future versions of Autoconf.
8671 If the @var{variable} is a literal string, it is passed to
8672 @code{m4_pattern_allow} (@pxref{Forbidden Patterns}).
8674 If multiple @code{AC_DEFINE} statements are executed for the same
8675 @var{variable} name (not counting any parenthesized argument list),
8676 the last one wins.
8677 @end defmac
8679 @defmac AC_DEFINE_UNQUOTED (@var{variable}, @var{value}, @ovar{description})
8680 @defmacx AC_DEFINE_UNQUOTED (@var{variable})
8681 @acindex{DEFINE_UNQUOTED}
8682 @cvindex @var{variable}
8683 Like @code{AC_DEFINE}, but three shell expansions are
8684 performed---once---on @var{variable} and @var{value}: variable expansion
8685 (@samp{$}), command substitution (@samp{`}), and backslash escaping
8686 (@samp{\}).  Single and double quote characters in the value have no
8687 special meaning.  Use this macro instead of @code{AC_DEFINE} when
8688 @var{variable} or @var{value} is a shell variable.  Examples:
8690 @example
8691 AC_DEFINE_UNQUOTED([config_machfile], ["$machfile"],
8692   [Configuration machine file.])
8693 AC_DEFINE_UNQUOTED([GETGROUPS_T], [$ac_cv_type_getgroups],
8694   [getgroups return type.])
8695 AC_DEFINE_UNQUOTED([$ac_tr_hdr], [1],
8696   [Translated header name.])
8697 @end example
8698 @end defmac
8700 Due to a syntactical bizarreness of the Bourne shell, do not use
8701 semicolons to separate @code{AC_DEFINE} or @code{AC_DEFINE_UNQUOTED}
8702 calls from other macro calls or shell code; that can cause syntax errors
8703 in the resulting @command{configure} script.  Use either blanks or
8704 newlines.  That is, do this:
8706 @example
8707 AC_CHECK_HEADER([elf.h],
8708   [AC_DEFINE([SVR4], [1], [System V Release 4]) LIBS="-lelf $LIBS"])
8709 @end example
8711 @noindent
8712 or this:
8714 @example
8715 AC_CHECK_HEADER([elf.h],
8716   [AC_DEFINE([SVR4], [1], [System V Release 4])
8717    LIBS="-lelf $LIBS"])
8718 @end example
8720 @noindent
8721 instead of this:
8723 @example
8724 AC_CHECK_HEADER([elf.h],
8725   [AC_DEFINE([SVR4], [1], [System V Release 4]); LIBS="-lelf $LIBS"])
8726 @end example
8728 @node Setting Output Variables
8729 @section Setting Output Variables
8730 @cindex Output variables
8732 Another way to record the results of tests is to set @dfn{output
8733 variables}, which are shell variables whose values are substituted into
8734 files that @command{configure} outputs.  The two macros below create new
8735 output variables.  @xref{Preset Output Variables}, for a list of output
8736 variables that are always available.
8738 @defmac AC_SUBST (@var{variable}, @ovar{value})
8739 @acindex{SUBST}
8740 Create an output variable from a shell variable.  Make @code{AC_OUTPUT}
8741 substitute the variable @var{variable} into output files (typically one
8742 or more makefiles).  This means that @code{AC_OUTPUT}
8743 replaces instances of @samp{@@@var{variable}@@} in input files with the
8744 value that the shell variable @var{variable} has when @code{AC_OUTPUT}
8745 is called.  The value can contain any non-@code{NUL} character, including
8746 newline.
8747 Variable occurrences should not overlap: e.g., an input file should
8748 not contain @samp{@@@var{var1}@@@var{var2}@@} if @var{var1} and @var{var2}
8749 are variable names.
8750 The substituted value is not rescanned for more output variables;
8751 occurrences of @samp{@@@var{variable}@@} in the value are inserted
8752 literally into the output file.  (The algorithm uses the special marker
8753 @code{|#_!!_#|} internally, so neither the substituted value nor the
8754 output file may contain @code{|#_!!_#|}.)
8756 If @var{value} is given, in addition assign it to @var{variable}.
8758 The string @var{variable} is passed to @code{m4_pattern_allow}
8759 (@pxref{Forbidden Patterns}).
8760 @end defmac
8762 @defmac AC_SUBST_FILE (@var{variable})
8763 @acindex{SUBST_FILE}
8764 Another way to create an output variable from a shell variable.  Make
8765 @code{AC_OUTPUT} insert (without substitutions) the contents of the file
8766 named by shell variable @var{variable} into output files.  This means
8767 that @code{AC_OUTPUT} replaces instances of
8768 @samp{@@@var{variable}@@} in output files (such as @file{Makefile.in})
8769 with the contents of the file that the shell variable @var{variable}
8770 names when @code{AC_OUTPUT} is called.  Set the variable to
8771 @file{/dev/null} for cases that do not have a file to insert.
8772 This substitution occurs only when the @samp{@@@var{variable}@@} is on a
8773 line by itself, optionally surrounded by spaces and tabs.  The
8774 substitution replaces the whole line, including the spaces, tabs, and
8775 the terminating newline.
8777 This macro is useful for inserting makefile fragments containing
8778 special dependencies or other @command{make} directives for particular host
8779 or target types into makefiles.  For example, @file{configure.ac}
8780 could contain:
8782 @example
8783 AC_SUBST_FILE([host_frag])
8784 host_frag=$srcdir/conf/sun4.mh
8785 @end example
8787 @noindent
8788 and then a @file{Makefile.in} could contain:
8790 @example
8791 @@host_frag@@
8792 @end example
8794 The string @var{variable} is passed to @code{m4_pattern_allow}
8795 (@pxref{Forbidden Patterns}).
8796 @end defmac
8798 @cindex Precious Variable
8799 @cindex Variable, Precious
8800 Running @command{configure} in varying environments can be extremely
8801 dangerous.  If for instance the user runs @samp{CC=bizarre-cc
8802 ./configure}, then the cache, @file{config.h}, and many other output
8803 files depend upon @command{bizarre-cc} being the C compiler.  If
8804 for some reason the user runs @command{./configure} again, or if it is
8805 run via @samp{./config.status --recheck}, (@xref{Automatic Remaking},
8806 and @pxref{config.status Invocation}), then the configuration can be
8807 inconsistent, composed of results depending upon two different
8808 compilers.
8810 Environment variables that affect this situation, such as @samp{CC}
8811 above, are called @dfn{precious variables}, and can be declared as such
8812 by @code{AC_ARG_VAR}.
8814 @defmac AC_ARG_VAR (@var{variable}, @var{description})
8815 @acindex{ARG_VAR}
8816 Declare @var{variable} is a precious variable, and include its
8817 @var{description} in the variable section of @samp{./configure --help}.
8819 Being precious means that
8820 @itemize @minus
8821 @item
8822 @var{variable} is substituted via @code{AC_SUBST}.
8824 @item
8825 The value of @var{variable} when @command{configure} was launched is
8826 saved in the cache, including if it was not specified on the command
8827 line but via the environment.  Indeed, while @command{configure} can
8828 notice the definition of @code{CC} in @samp{./configure CC=bizarre-cc},
8829 it is impossible to notice it in @samp{CC=bizarre-cc ./configure},
8830 which, unfortunately, is what most users do.
8832 We emphasize that it is the @emph{initial} value of @var{variable} which
8833 is saved, not that found during the execution of @command{configure}.
8834 Indeed, specifying @samp{./configure FOO=foo} and letting
8835 @samp{./configure} guess that @code{FOO} is @code{foo} can be two
8836 different things.
8838 @item
8839 @var{variable} is checked for consistency between two
8840 @command{configure} runs.  For instance:
8842 @example
8843 $ @kbd{./configure --silent --config-cache}
8844 $ @kbd{CC=cc ./configure --silent --config-cache}
8845 configure: error: `CC' was not set in the previous run
8846 configure: error: changes in the environment can compromise \
8847 the build
8848 configure: error: run `make distclean' and/or \
8849 `rm config.cache' and start over
8850 @end example
8852 @noindent
8853 and similarly if the variable is unset, or if its content is changed.
8854 If the content has white space changes only, then the error is degraded
8855 to a warning only, but the old value is reused.
8857 @item
8858 @var{variable} is kept during automatic reconfiguration
8859 (@pxref{config.status Invocation}) as if it had been passed as a command
8860 line argument, including when no cache is used:
8862 @example
8863 $ @kbd{CC=/usr/bin/cc ./configure var=raboof --silent}
8864 $ @kbd{./config.status --recheck}
8865 running CONFIG_SHELL=/bin/sh /bin/sh ./configure var=raboof \
8866   CC=/usr/bin/cc  --no-create --no-recursion
8867 @end example
8868 @end itemize
8869 @end defmac
8871 @node Special Chars in Variables
8872 @section Special Characters in Output Variables
8873 @cindex Output variables, special characters in
8875 Many output variables are intended to be evaluated both by
8876 @command{make} and by the shell.  Some characters are expanded
8877 differently in these two contexts, so to avoid confusion these
8878 variables' values should not contain any of the following characters:
8880 @example
8881 " # $ & ' ( ) * ; < > ? [ \ ^ ` |
8882 @end example
8884 Also, these variables' values should neither contain newlines, nor start
8885 with @samp{~}, nor contain white space or @samp{:} immediately followed
8886 by @samp{~}.  The values can contain nonempty sequences of white space
8887 characters like tabs and spaces, but each such sequence might
8888 arbitrarily be replaced by a single space during substitution.
8890 These restrictions apply both to the values that @command{configure}
8891 computes, and to the values set directly by the user.  For example, the
8892 following invocations of @command{configure} are problematic, since they
8893 attempt to use special characters within @code{CPPFLAGS} and white space
8894 within @code{$(srcdir)}:
8896 @example
8897 CPPFLAGS='-DOUCH="&\"#$*?"' '../My Source/ouch-1.0/configure'
8899 '../My Source/ouch-1.0/configure' CPPFLAGS='-DOUCH="&\"#$*?"'
8900 @end example
8902 @node Caching Results
8903 @section Caching Results
8904 @cindex Cache
8906 To avoid checking for the same features repeatedly in various
8907 @command{configure} scripts (or in repeated runs of one script),
8908 @command{configure} can optionally save the results of many checks in a
8909 @dfn{cache file} (@pxref{Cache Files}).  If a @command{configure} script
8910 runs with caching enabled and finds a cache file, it reads the results
8911 of previous runs from the cache and avoids rerunning those checks.  As a
8912 result, @command{configure} can then run much faster than if it had to
8913 perform all of the checks every time.
8915 @defmac AC_CACHE_VAL (@var{cache-id}, @var{commands-to-set-it})
8916 @acindex{CACHE_VAL}
8917 Ensure that the results of the check identified by @var{cache-id} are
8918 available.  If the results of the check were in the cache file that was
8919 read, and @command{configure} was not given the @option{--quiet} or
8920 @option{--silent} option, print a message saying that the result was
8921 cached; otherwise, run the shell commands @var{commands-to-set-it}.  If
8922 the shell commands are run to determine the value, the value is
8923 saved in the cache file just before @command{configure} creates its output
8924 files.  @xref{Cache Variable Names}, for how to choose the name of the
8925 @var{cache-id} variable.
8927 The @var{commands-to-set-it} @emph{must have no side effects} except for
8928 setting the variable @var{cache-id}, see below.
8929 @end defmac
8931 @defmac AC_CACHE_CHECK (@var{message}, @var{cache-id}, @
8932   @var{commands-to-set-it})
8933 @acindex{CACHE_CHECK}
8934 A wrapper for @code{AC_CACHE_VAL} that takes care of printing the
8935 messages.  This macro provides a convenient shorthand for the most
8936 common way to use these macros.  It calls @code{AC_MSG_CHECKING} for
8937 @var{message}, then @code{AC_CACHE_VAL} with the @var{cache-id} and
8938 @var{commands} arguments, and @code{AC_MSG_RESULT} with @var{cache-id}.
8940 The @var{commands-to-set-it} @emph{must have no side effects} except for
8941 setting the variable @var{cache-id}, see below.
8942 @end defmac
8944 It is common to find buggy macros using @code{AC_CACHE_VAL} or
8945 @code{AC_CACHE_CHECK}, because people are tempted to call
8946 @code{AC_DEFINE} in the @var{commands-to-set-it}.  Instead, the code that
8947 @emph{follows} the call to @code{AC_CACHE_VAL} should call
8948 @code{AC_DEFINE}, by examining the value of the cache variable.  For
8949 instance, the following macro is broken:
8951 @example
8952 @group
8953 AC_DEFUN([AC_SHELL_TRUE],
8954 [AC_CACHE_CHECK([whether true(1) works], [my_cv_shell_true_works],
8955                 [my_cv_shell_true_works=no
8956                  (true) 2>/dev/null && my_cv_shell_true_works=yes
8957                  if test "$my_cv_shell_true_works" = yes; then
8958                    AC_DEFINE([TRUE_WORKS], [1],
8959                              [Define if `true(1)' works properly.])
8960                  fi])
8962 @end group
8963 @end example
8965 @noindent
8966 This fails if the cache is enabled: the second time this macro is run,
8967 @code{TRUE_WORKS} @emph{will not be defined}.  The proper implementation
8970 @example
8971 @group
8972 AC_DEFUN([AC_SHELL_TRUE],
8973 [AC_CACHE_CHECK([whether true(1) works], [my_cv_shell_true_works],
8974                 [my_cv_shell_true_works=no
8975                  (true) 2>/dev/null && my_cv_shell_true_works=yes])
8976  if test "$my_cv_shell_true_works" = yes; then
8977    AC_DEFINE([TRUE_WORKS], [1],
8978              [Define if `true(1)' works properly.])
8979  fi
8981 @end group
8982 @end example
8984 Also, @var{commands-to-set-it} should not print any messages, for
8985 example with @code{AC_MSG_CHECKING}; do that before calling
8986 @code{AC_CACHE_VAL}, so the messages are printed regardless of whether
8987 the results of the check are retrieved from the cache or determined by
8988 running the shell commands.
8990 @menu
8991 * Cache Variable Names::        Shell variables used in caches
8992 * Cache Files::                 Files @command{configure} uses for caching
8993 * Cache Checkpointing::         Loading and saving the cache file
8994 @end menu
8996 @node Cache Variable Names
8997 @subsection Cache Variable Names
8998 @cindex Cache variable
9000 The names of cache variables should have the following format:
9002 @example
9003 @var{package-prefix}_cv_@var{value-type}_@var{specific-value}_@ovar{additional-options}
9004 @end example
9006 @noindent
9007 for example, @samp{ac_cv_header_stat_broken} or
9008 @samp{ac_cv_prog_gcc_traditional}.  The parts of the variable name are:
9010 @table @asis
9011 @item @var{package-prefix}
9012 An abbreviation for your package or organization; the same prefix you
9013 begin local Autoconf macros with, except lowercase by convention.
9014 For cache values used by the distributed Autoconf macros, this value is
9015 @samp{ac}.
9017 @item @code{_cv_}
9018 Indicates that this shell variable is a cache value.  This string
9019 @emph{must} be present in the variable name, including the leading
9020 underscore.
9022 @item @var{value-type}
9023 A convention for classifying cache values, to produce a rational naming
9024 system.  The values used in Autoconf are listed in @ref{Macro Names}.
9026 @item @var{specific-value}
9027 Which member of the class of cache values this test applies to.
9028 For example, which function (@samp{alloca}), program (@samp{gcc}), or
9029 output variable (@samp{INSTALL}).
9031 @item @var{additional-options}
9032 Any particular behavior of the specific member that this test applies to.
9033 For example, @samp{broken} or @samp{set}.  This part of the name may
9034 be omitted if it does not apply.
9035 @end table
9037 The values assigned to cache variables may not contain newlines.
9038 Usually, their values are Boolean (@samp{yes} or @samp{no}) or the
9039 names of files or functions; so this is not an important restriction.
9041 @node Cache Files
9042 @subsection Cache Files
9044 A cache file is a shell script that caches the results of configure
9045 tests run on one system so they can be shared between configure scripts
9046 and configure runs.  It is not useful on other systems.  If its contents
9047 are invalid for some reason, the user may delete or edit it.
9049 By default, @command{configure} uses no cache file,
9050 to avoid problems caused by accidental
9051 use of stale cache files.
9053 To enable caching, @command{configure} accepts @option{--config-cache} (or
9054 @option{-C}) to cache results in the file @file{config.cache}.
9055 Alternatively, @option{--cache-file=@var{file}} specifies that
9056 @var{file} be the cache file.  The cache file is created if it does not
9057 exist already.  When @command{configure} calls @command{configure} scripts in
9058 subdirectories, it uses the @option{--cache-file} argument so that they
9059 share the same cache.  @xref{Subdirectories}, for information on
9060 configuring subdirectories with the @code{AC_CONFIG_SUBDIRS} macro.
9062 @file{config.status} only pays attention to the cache file if it is
9063 given the @option{--recheck} option, which makes it rerun
9064 @command{configure}.
9066 It is wrong to try to distribute cache files for particular system types.
9067 There is too much room for error in doing that, and too much
9068 administrative overhead in maintaining them.  For any features that
9069 can't be guessed automatically, use the standard method of the canonical
9070 system type and linking files (@pxref{Manual Configuration}).
9072 The site initialization script can specify a site-wide cache file to
9073 use, instead of the usual per-program cache.  In this case, the cache
9074 file gradually accumulates information whenever someone runs a new
9075 @command{configure} script.  (Running @command{configure} merges the new cache
9076 results with the existing cache file.)  This may cause problems,
9077 however, if the system configuration (e.g., the installed libraries or
9078 compilers) changes and the stale cache file is not deleted.
9080 @node Cache Checkpointing
9081 @subsection Cache Checkpointing
9083 If your configure script, or a macro called from @file{configure.ac}, happens
9084 to abort the configure process, it may be useful to checkpoint the cache
9085 a few times at key points using @code{AC_CACHE_SAVE}.  Doing so
9086 reduces the amount of time it takes to rerun the configure script with
9087 (hopefully) the error that caused the previous abort corrected.
9089 @c FIXME: Do we really want to document this guy?
9090 @defmac AC_CACHE_LOAD
9091 @acindex{CACHE_LOAD}
9092 Loads values from existing cache file, or creates a new cache file if a
9093 cache file is not found.  Called automatically from @code{AC_INIT}.
9094 @end defmac
9096 @defmac AC_CACHE_SAVE
9097 @acindex{CACHE_SAVE}
9098 Flushes all cached values to the cache file.  Called automatically from
9099 @code{AC_OUTPUT}, but it can be quite useful to call
9100 @code{AC_CACHE_SAVE} at key points in @file{configure.ac}.
9101 @end defmac
9103 For instance:
9105 @example
9106 @r{ @dots{} AC_INIT, etc. @dots{}}
9107 @group
9108 # Checks for programs.
9109 AC_PROG_CC
9110 AC_PROG_AWK
9111 @r{ @dots{} more program checks @dots{}}
9112 AC_CACHE_SAVE
9113 @end group
9115 @group
9116 # Checks for libraries.
9117 AC_CHECK_LIB([nsl], [gethostbyname])
9118 AC_CHECK_LIB([socket], [connect])
9119 @r{ @dots{} more lib checks @dots{}}
9120 AC_CACHE_SAVE
9121 @end group
9123 @group
9124 # Might abort@dots{}
9125 AM_PATH_GTK([1.0.2], [], [AC_MSG_ERROR([GTK not in path])])
9126 AM_PATH_GTKMM([0.9.5], [], [AC_MSG_ERROR([GTK not in path])])
9127 @end group
9128 @r{ @dots{} AC_OUTPUT, etc. @dots{}}
9129 @end example
9131 @node Printing Messages
9132 @section Printing Messages
9133 @cindex Messages, from @command{configure}
9135 @command{configure} scripts need to give users running them several kinds
9136 of information.  The following macros print messages in ways appropriate
9137 for each kind.  The arguments to all of them get enclosed in shell
9138 double quotes, so the shell performs variable and back-quote
9139 substitution on them.
9141 These macros are all wrappers around the @command{echo} shell command.
9142 They direct output to the appropriate file descriptor (@pxref{File
9143 Descriptor Macros}).
9144 @command{configure} scripts should rarely need to run @command{echo} directly
9145 to print messages for the user.  Using these macros makes it easy to
9146 change how and when each kind of message is printed; such changes need
9147 only be made to the macro definitions and all the callers change
9148 automatically.
9150 To diagnose static issues, i.e., when @command{autoconf} is run, see
9151 @ref{Diagnostic Macros}.
9153 @defmac AC_MSG_CHECKING (@var{feature-description})
9154 @acindex{MSG_CHECKING}
9155 Notify the user that @command{configure} is checking for a particular
9156 feature.  This macro prints a message that starts with @samp{checking }
9157 and ends with @samp{...} and no newline.  It must be followed by a call
9158 to @code{AC_MSG_RESULT} to print the result of the check and the
9159 newline.  The @var{feature-description} should be something like
9160 @samp{whether the Fortran compiler accepts C++ comments} or @samp{for
9161 c89}.
9163 This macro prints nothing if @command{configure} is run with the
9164 @option{--quiet} or @option{--silent} option.
9165 @end defmac
9167 @anchor{AC_MSG_RESULT}
9168 @defmac AC_MSG_RESULT (@var{result-description})
9169 @acindex{MSG_RESULT}
9170 Notify the user of the results of a check.  @var{result-description} is
9171 almost always the value of the cache variable for the check, typically
9172 @samp{yes}, @samp{no}, or a file name.  This macro should follow a call
9173 to @code{AC_MSG_CHECKING}, and the @var{result-description} should be
9174 the completion of the message printed by the call to
9175 @code{AC_MSG_CHECKING}.
9177 This macro prints nothing if @command{configure} is run with the
9178 @option{--quiet} or @option{--silent} option.
9179 @end defmac
9181 @anchor{AC_MSG_NOTICE}
9182 @defmac AC_MSG_NOTICE (@var{message})
9183 @acindex{MSG_NOTICE}
9184 Deliver the @var{message} to the user.  It is useful mainly to print a
9185 general description of the overall purpose of a group of feature checks,
9186 e.g.,
9188 @example
9189 AC_MSG_NOTICE([checking if stack overflow is detectable])
9190 @end example
9192 This macro prints nothing if @command{configure} is run with the
9193 @option{--quiet} or @option{--silent} option.
9194 @end defmac
9196 @anchor{AC_MSG_ERROR}
9197 @defmac AC_MSG_ERROR (@var{error-description}, @ovar{exit-status})
9198 @acindex{MSG_ERROR}
9199 Notify the user of an error that prevents @command{configure} from
9200 completing.  This macro prints an error message to the standard error
9201 output and exits @command{configure} with @var{exit-status} (1 by default).
9202 @var{error-description} should be something like @samp{invalid value
9203 $HOME for \$HOME}.
9205 The @var{error-description} should start with a lower-case letter, and
9206 ``cannot'' is preferred to ``can't''.
9207 @end defmac
9209 @defmac AC_MSG_FAILURE (@var{error-description}, @ovar{exit-status})
9210 @acindex{MSG_FAILURE}
9211 This @code{AC_MSG_ERROR} wrapper notifies the user of an error that
9212 prevents @command{configure} from completing @emph{and} that additional
9213 details are provided in @file{config.log}.  This is typically used when
9214 abnormal results are found during a compilation.
9215 @end defmac
9217 @anchor{AC_MSG_WARN}
9218 @defmac AC_MSG_WARN (@var{problem-description})
9219 @acindex{MSG_WARN}
9220 Notify the @command{configure} user of a possible problem.  This macro
9221 prints the message to the standard error output; @command{configure}
9222 continues running afterward, so macros that call @code{AC_MSG_WARN} should
9223 provide a default (back-up) behavior for the situations they warn about.
9224 @var{problem-description} should be something like @samp{ln -s seems to
9225 make hard links}.
9226 @end defmac
9230 @c ====================================================== Programming in M4.
9232 @node Programming in M4
9233 @chapter Programming in M4
9234 @cindex M4
9236 Autoconf is written on top of two layers: @dfn{M4sugar}, which provides
9237 convenient macros for pure M4 programming, and @dfn{M4sh}, which
9238 provides macros dedicated to shell script generation.
9240 As of this version of Autoconf, these two layers still contain
9241 experimental macros, whose interface might change in the future.  As a
9242 matter of fact, @emph{anything that is not documented must not be used}.
9244 @menu
9245 * M4 Quotation::                Protecting macros from unwanted expansion
9246 * Using autom4te::              The Autoconf executables backbone
9247 * Programming in M4sugar::      Convenient pure M4 macros
9248 @end menu
9250 @node M4 Quotation
9251 @section M4 Quotation
9252 @cindex M4 quotation
9253 @cindex quotation
9255 The most common problem with existing macros is an improper quotation.
9256 This section, which users of Autoconf can skip, but which macro writers
9257 @emph{must} read, first justifies the quotation scheme that was chosen
9258 for Autoconf and then ends with a rule of thumb.  Understanding the
9259 former helps one to follow the latter.
9261 @menu
9262 * Active Characters::           Characters that change the behavior of M4
9263 * One Macro Call::              Quotation and one macro call
9264 * Quoting and Parameters::      M4 vs. shell parameters
9265 * Quotation and Nested Macros::  Macros calling macros
9266 * Changequote is Evil::         Worse than INTERCAL: M4 + changequote
9267 * Quadrigraphs::                Another way to escape special characters
9268 * Quotation Rule Of Thumb::     One parenthesis, one quote
9269 @end menu
9271 @node Active Characters
9272 @subsection Active Characters
9274 To fully understand where proper quotation is important, you first need
9275 to know what the special characters are in Autoconf: @samp{#} introduces
9276 a comment inside which no macro expansion is performed, @samp{,}
9277 separates arguments, @samp{[} and @samp{]} are the quotes themselves,
9278 @samp{(} and @samp{)} (which M4 tries to match by pairs), and finally
9279 @samp{$} inside a macro definition.
9281 In order to understand the delicate case of macro calls, we first have
9282 to present some obvious failures.  Below they are ``obvious-ified'',
9283 but when you find them in real life, they are usually in disguise.
9285 Comments, introduced by a hash and running up to the newline, are opaque
9286 tokens to the top level: active characters are turned off, and there is
9287 no macro expansion:
9289 @example
9290 # define([def], ine)
9291 @result{}# define([def], ine)
9292 @end example
9294 Each time there can be a macro expansion, there is a quotation
9295 expansion, i.e., one level of quotes is stripped:
9297 @example
9298 int tab[10];
9299 @result{}int tab10;
9300 [int tab[10];]
9301 @result{}int tab[10];
9302 @end example
9304 Without this in mind, the reader might try hopelessly to use her macro
9305 @code{array}:
9307 @example
9308 define([array], [int tab[10];])
9309 array
9310 @result{}int tab10;
9311 [array]
9312 @result{}array
9313 @end example
9315 @noindent
9316 How can you correctly output the intended results@footnote{Using
9317 @code{defn}.}?
9320 @node One Macro Call
9321 @subsection One Macro Call
9323 Let's proceed on the interaction between active characters and macros
9324 with this small macro, which just returns its first argument:
9326 @example
9327 define([car], [$1])
9328 @end example
9330 @noindent
9331 The two pairs of quotes above are not part of the arguments of
9332 @code{define}; rather, they are understood by the top level when it
9333 tries to find the arguments of @code{define}.  Therefore, assuming
9334 @code{car} is not already defined, it is equivalent to write:
9336 @example
9337 define(car, $1)
9338 @end example
9340 @noindent
9341 But, while it is acceptable for a @file{configure.ac} to avoid unnecessary
9342 quotes, it is bad practice for Autoconf macros which must both be more
9343 robust and also advocate perfect style.
9345 At the top level, there are only two possibilities: either you
9346 quote or you don't:
9348 @example
9349 car(foo, bar, baz)
9350 @result{}foo
9351 [car(foo, bar, baz)]
9352 @result{}car(foo, bar, baz)
9353 @end example
9355 Let's pay attention to the special characters:
9357 @example
9358 car(#)
9359 @error{}EOF in argument list
9360 @end example
9362 The closing parenthesis is hidden in the comment; with a hypothetical
9363 quoting, the top level understood it this way:
9365 @example
9366 car([#)]
9367 @end example
9369 @noindent
9370 Proper quotation, of course, fixes the problem:
9372 @example
9373 car([#])
9374 @result{}#
9375 @end example
9377 Here are more examples:
9379 @example
9380 car(foo, bar)
9381 @result{}foo
9382 car([foo, bar])
9383 @result{}foo, bar
9384 car((foo, bar))
9385 @result{}(foo, bar)
9386 car([(foo], [bar)])
9387 @result{}(foo
9388 define([a], [b])
9389 @result{}
9390 car(a)
9391 @result{}b
9392 car([a])
9393 @result{}b
9394 car([[a]])
9395 @result{}a
9396 car([[[a]]])
9397 @result{}[a]
9398 @end example
9400 @node Quoting and Parameters
9401 @subsection Quoting and Parameters
9403 When M4 encounters @samp{$} within a macro definition, followed
9404 immediately by a character it recognizes (@samp{0}@dots{}@samp{9},
9405 @samp{#}, @samp{@@}, or @samp{*}), it will perform M4 parameter
9406 expansion.  This happens regardless of how many layers of quotes the
9407 parameter expansion is nested within, or even if it occurs in text that
9408 will be rescanned as a comment.
9410 @example
9411 define([none], [$1])
9412 @result{}
9413 define([one], [[$1]])
9414 @result{}
9415 define([two], [[[$1]]])
9416 @result{}
9417 define([comment], [# $1])
9418 @result{}
9419 define([active], [ACTIVE])
9420 @result{}
9421 none([active])
9422 @result{}ACTIVE
9423 one([active])
9424 @result{}active
9425 two([active])
9426 @result{}[active]
9427 comment([active])
9428 @result{}# active
9429 @end example
9431 On the other hand, since autoconf generates shell code, you often want
9432 to output shell variable expansion, rather than performing M4 parameter
9433 expansion.  To do this, you must use M4 quoting to separate the @samp{$}
9434 from the next character in the definition of your macro.  If the macro
9435 definition occurs in single-quoted text, then insert another level of
9436 quoting; if the usage is already inside a double-quoted string, then
9437 split it into concatenated strings.
9439 @example
9440 define([single], [a single-quoted $[]1 definition])
9441 @result{}
9442 define([double], [[a double-quoted $][1 definition]])
9443 @result{}
9444 single
9445 @result{}a single-quoted $1 definition
9446 double
9447 @result{}a double-quoted $1 definition
9448 @end example
9450 Posix states that M4 implementations are free to provide implementation
9451 extensions when @samp{$@{} is encountered in a macro definition.
9452 Autoconf reserves the longer sequence @samp{$@{@{} for use with planned
9453 extensions that will be available in the future @acronym{GNU} M4 2.0,
9454 but guarantees that all other instances of @samp{$@{} will be output
9455 literally.  Therefore, this idiom can also be used to output shell code
9456 parameter references:
9458 @example
9459 define([first], [$@{1@}])first
9460 @result{}$@{1@}
9461 @end example
9463 Posix also states that @samp{$11} should expand to the first parameter
9464 concatenated with a literal @samp{1}, although some versions of
9465 @acronym{GNU} M4 expand the eleventh parameter instead.  For
9466 portability, you should only use single-digit M4 parameter expansion.
9468 With this in mind, we can explore the cases where macros invoke
9469 macros@enddots{}
9471 @node Quotation and Nested Macros
9472 @subsection Quotation and Nested Macros
9474 The examples below use the following macros:
9476 @example
9477 define([car], [$1])
9478 define([active], [ACT, IVE])
9479 define([array], [int tab[10]])
9480 @end example
9482 Each additional embedded macro call introduces other possible
9483 interesting quotations:
9485 @example
9486 car(active)
9487 @result{}ACT
9488 car([active])
9489 @result{}ACT, IVE
9490 car([[active]])
9491 @result{}active
9492 @end example
9494 In the first case, the top level looks for the arguments of @code{car},
9495 and finds @samp{active}.  Because M4 evaluates its arguments
9496 before applying the macro, @samp{active} is expanded, which results in:
9498 @example
9499 car(ACT, IVE)
9500 @result{}ACT
9501 @end example
9503 @noindent
9504 In the second case, the top level gives @samp{active} as first and only
9505 argument of @code{car}, which results in:
9507 @example
9508 active
9509 @result{}ACT, IVE
9510 @end example
9512 @noindent
9513 i.e., the argument is evaluated @emph{after} the macro that invokes it.
9514 In the third case, @code{car} receives @samp{[active]}, which results in:
9516 @example
9517 [active]
9518 @result{}active
9519 @end example
9521 @noindent
9522 exactly as we already saw above.
9524 The example above, applied to a more realistic example, gives:
9526 @example
9527 car(int tab[10];)
9528 @result{}int tab10;
9529 car([int tab[10];])
9530 @result{}int tab10;
9531 car([[int tab[10];]])
9532 @result{}int tab[10];
9533 @end example
9535 @noindent
9536 Huh?  The first case is easily understood, but why is the second wrong,
9537 and the third right?  To understand that, you must know that after
9538 M4 expands a macro, the resulting text is immediately subjected
9539 to macro expansion and quote removal.  This means that the quote removal
9540 occurs twice---first before the argument is passed to the @code{car}
9541 macro, and second after the @code{car} macro expands to the first
9542 argument.
9544 As the author of the Autoconf macro @code{car}, you then consider it to
9545 be incorrect that your users have to double-quote the arguments of
9546 @code{car}, so you ``fix'' your macro.  Let's call it @code{qar} for
9547 quoted car:
9549 @example
9550 define([qar], [[$1]])
9551 @end example
9553 @noindent
9554 and check that @code{qar} is properly fixed:
9556 @example
9557 qar([int tab[10];])
9558 @result{}int tab[10];
9559 @end example
9561 @noindent
9562 Ahhh!  That's much better.
9564 But note what you've done: now that the result of @code{qar} is always
9565 a literal string, the only time a user can use nested macros is if she
9566 relies on an @emph{unquoted} macro call:
9568 @example
9569 qar(active)
9570 @result{}ACT
9571 qar([active])
9572 @result{}active
9573 @end example
9575 @noindent
9576 leaving no way for her to reproduce what she used to do with @code{car}:
9578 @example
9579 car([active])
9580 @result{}ACT, IVE
9581 @end example
9583 @noindent
9584 Worse yet: she wants to use a macro that produces a set of @code{cpp}
9585 macros:
9587 @example
9588 define([my_includes], [#include <stdio.h>])
9589 car([my_includes])
9590 @result{}#include <stdio.h>
9591 qar(my_includes)
9592 @error{}EOF in argument list
9593 @end example
9595 This macro, @code{qar}, because it double quotes its arguments, forces
9596 its users to leave their macro calls unquoted, which is dangerous.
9597 Commas and other active symbols are interpreted by M4 before
9598 they are given to the macro, often not in the way the users expect.
9599 Also, because @code{qar} behaves differently from the other macros,
9600 it's an exception that should be avoided in Autoconf.
9602 @node Changequote is Evil
9603 @subsection @code{changequote} is Evil
9604 @cindex @code{changequote}
9606 The temptation is often high to bypass proper quotation, in particular
9607 when it's late at night.  Then, many experienced Autoconf hackers
9608 finally surrender to the dark side of the force and use the ultimate
9609 weapon: @code{changequote}.
9611 The M4 builtin @code{changequote} belongs to a set of primitives that
9612 allow one to adjust the syntax of the language to adjust it to one's
9613 needs.  For instance, by default M4 uses @samp{`} and @samp{'} as
9614 quotes, but in the context of shell programming (and actually of most
9615 programming languages), that's about the worst choice one can make:
9616 because of strings and back-quoted expressions in shell code (such as
9617 @samp{'this'} and @samp{`that`}), and because of literal characters in usual
9618 programming languages (as in @samp{'0'}), there are many unbalanced
9619 @samp{`} and @samp{'}.  Proper M4 quotation then becomes a nightmare, if
9620 not impossible.  In order to make M4 useful in such a context, its
9621 designers have equipped it with @code{changequote}, which makes it
9622 possible to choose another pair of quotes.  M4sugar, M4sh, Autoconf, and
9623 Autotest all have chosen to use @samp{[} and @samp{]}.  Not especially
9624 because they are unlikely characters, but @emph{because they are
9625 characters unlikely to be unbalanced}.
9627 There are other magic primitives, such as @code{changecom} to specify
9628 what syntactic forms are comments (it is common to see
9629 @samp{changecom(<!--, -->)} when M4 is used to produce HTML pages),
9630 @code{changeword} and @code{changesyntax} to change other syntactic
9631 details (such as the character to denote the @var{n}th argument, @samp{$} by
9632 default, the parentheses around arguments, etc.).
9634 These primitives are really meant to make M4 more useful for specific
9635 domains: they should be considered like command line options:
9636 @option{--quotes}, @option{--comments}, @option{--words}, and
9637 @option{--syntax}.  Nevertheless, they are implemented as M4 builtins, as
9638 it makes M4 libraries self contained (no need for additional options).
9640 There lies the problem@enddots{}
9642 @sp 1
9644 The problem is that it is then tempting to use them in the middle of an
9645 M4 script, as opposed to its initialization.  This, if not carefully
9646 thought out, can lead to disastrous effects: @emph{you are changing the
9647 language in the middle of the execution}.  Changing and restoring the
9648 syntax is often not enough: if you happened to invoke macros in between,
9649 these macros are lost, as the current syntax is probably not
9650 the one they were implemented with.
9652 @c FIXME: I've been looking for a short, real case example, but I
9653 @c lost them all :(
9656 @node Quadrigraphs
9657 @subsection Quadrigraphs
9658 @cindex quadrigraphs
9659 @cindex @samp{@@S|@@}
9660 @cindex @samp{@@&t@@}
9661 @c Info cannot handle `:' in index entries.
9662 @c @cindex @samp{@@<:@@}
9663 @c @cindex @samp{@@:>@@}
9664 @c @cindex @samp{@@%:@@}
9665 @c @cindex @samp{@@@{:@@}
9666 @c @cindex @samp{@@:@}@@}
9668 When writing an Autoconf macro you may occasionally need to generate
9669 special characters that are difficult to express with the standard
9670 Autoconf quoting rules.  For example, you may need to output the regular
9671 expression @samp{[^[]}, which matches any character other than @samp{[}.
9672 This expression contains unbalanced brackets so it cannot be put easily
9673 into an M4 macro.
9675 Additionally, there are a few m4sugar macros (such as @code{m4_split}
9676 and @code{m4_expand}) which internally use special markers in addition
9677 to the regular quoting characters.  If the arguments to these macros
9678 contain the literal strings @samp{-=<@{(} or @samp{)@}>=-}, the macros
9679 might behave incorrectly.
9681 You can work around these problems by using one of the following
9682 @dfn{quadrigraphs}:
9684 @table @samp
9685 @item @@<:@@
9686 @samp{[}
9687 @item @@:>@@
9688 @samp{]}
9689 @item @@S|@@
9690 @samp{$}
9691 @item @@%:@@
9692 @samp{#}
9693 @item @@@{:@@
9694 @samp{(}
9695 @item @@:@}@@
9696 @samp{)}
9697 @item @@&t@@
9698 Expands to nothing.
9699 @end table
9701 Quadrigraphs are replaced at a late stage of the translation process,
9702 after @command{m4} is run, so they do not get in the way of M4 quoting.
9703 For example, the string @samp{^@@<:@@}, independently of its quotation,
9704 appears as @samp{^[} in the output.
9706 The empty quadrigraph can be used:
9708 @itemize @minus
9709 @item to mark trailing spaces explicitly
9711 Trailing spaces are smashed by @command{autom4te}.  This is a feature.
9713 @item to produce quadrigraphs and other strings reserved by m4sugar
9715 For instance @samp{@@<@@&t@@:@@} produces @samp{@@<:@@}.  For a more
9716 contrived example:
9718 @example
9719 m4_define([a], [A])m4_define([b], [B])m4_define([c], [C])dnl
9720 m4_split([a )@}>=- b -=<@{( c])
9721 @result{}[a], [], [B], [], [c]
9722 m4_split([a )@}@@&t@@>=- b -=<@@&t@@@{( c])
9723 @result{}[a], [)@}>=-], [b], [-=<@{(], [c]
9724 @end example
9726 @item to escape @emph{occurrences} of forbidden patterns
9728 For instance you might want to mention @code{AC_FOO} in a comment, while
9729 still being sure that @command{autom4te} still catches unexpanded
9730 @samp{AC_*}.  Then write @samp{AC@@&t@@_FOO}.
9731 @end itemize
9733 The name @samp{@@&t@@} was suggested by Paul Eggert:
9735 @quotation
9736 I should give some credit to the @samp{@@&t@@} pun.  The @samp{&} is my
9737 own invention, but the @samp{t} came from the source code of the
9738 @sc{algol68c} compiler, written by Steve Bourne (of Bourne shell fame),
9739 and which used @samp{mt} to denote the empty string.  In C, it would
9740 have looked like something like:
9742 @example
9743 char const mt[] = "";
9744 @end example
9746 @noindent
9747 but of course the source code was written in Algol 68.
9749 I don't know where he got @samp{mt} from: it could have been his own
9750 invention, and I suppose it could have been a common pun around the
9751 Cambridge University computer lab at the time.
9752 @end quotation
9754 @node Quotation Rule Of Thumb
9755 @subsection Quotation Rule Of Thumb
9757 To conclude, the quotation rule of thumb is:
9759 @center @emph{One pair of quotes per pair of parentheses.}
9761 Never over-quote, never under-quote, in particular in the definition of
9762 macros.  In the few places where the macros need to use brackets
9763 (usually in C program text or regular expressions), properly quote
9764 @emph{the arguments}!
9766 It is common to read Autoconf programs with snippets like:
9768 @example
9769 AC_TRY_LINK(
9770 changequote(<<, >>)dnl
9771 <<#include <time.h>
9772 #ifndef tzname /* For SGI.  */
9773 extern char *tzname[]; /* RS6000 and others reject char **tzname.  */
9774 #endif>>,
9775 changequote([, ])dnl
9776 [atoi (*tzname);], ac_cv_var_tzname=yes, ac_cv_var_tzname=no)
9777 @end example
9779 @noindent
9780 which is incredibly useless since @code{AC_TRY_LINK} is @emph{already}
9781 double quoting, so you just need:
9783 @example
9784 AC_TRY_LINK(
9785 [#include <time.h>
9786 #ifndef tzname /* For SGI.  */
9787 extern char *tzname[]; /* RS6000 and others reject char **tzname.  */
9788 #endif],
9789             [atoi (*tzname);],
9790             [ac_cv_var_tzname=yes],
9791             [ac_cv_var_tzname=no])
9792 @end example
9794 @noindent
9795 The M4-fluent reader might note that these two examples are rigorously
9796 equivalent, since M4 swallows both the @samp{changequote(<<, >>)}
9797 and @samp{<<} @samp{>>} when it @dfn{collects} the arguments: these
9798 quotes are not part of the arguments!
9800 Simplified, the example above is just doing this:
9802 @example
9803 changequote(<<, >>)dnl
9804 <<[]>>
9805 changequote([, ])dnl
9806 @end example
9808 @noindent
9809 instead of simply:
9811 @example
9812 [[]]
9813 @end example
9815 With macros that do not double quote their arguments (which is the
9816 rule), double-quote the (risky) literals:
9818 @example
9819 AC_LINK_IFELSE([AC_LANG_PROGRAM(
9820 [[#include <time.h>
9821 #ifndef tzname /* For SGI.  */
9822 extern char *tzname[]; /* RS6000 and others reject char **tzname.  */
9823 #endif]],
9824                                 [atoi (*tzname);])],
9825                [ac_cv_var_tzname=yes],
9826                [ac_cv_var_tzname=no])
9827 @end example
9829 Please note that the macro @code{AC_TRY_LINK} is obsolete, so you really
9830 should be using @code{AC_LINK_IFELSE} instead.
9832 @xref{Quadrigraphs}, for what to do if you run into a hopeless case
9833 where quoting does not suffice.
9835 When you create a @command{configure} script using newly written macros,
9836 examine it carefully to check whether you need to add more quotes in
9837 your macros.  If one or more words have disappeared in the M4
9838 output, you need more quotes.  When in doubt, quote.
9840 However, it's also possible to put on too many layers of quotes.  If
9841 this happens, the resulting @command{configure} script may contain
9842 unexpanded macros.  The @command{autoconf} program checks for this problem
9843 by looking for the string @samp{AC_} in @file{configure}.  However, this
9844 heuristic does not work in general: for example, it does not catch
9845 overquoting in @code{AC_DEFINE} descriptions.
9848 @c ---------------------------------------- Using autom4te
9850 @node Using autom4te
9851 @section Using @command{autom4te}
9853 The Autoconf suite, including M4sugar, M4sh, and Autotest, in addition
9854 to Autoconf per se, heavily rely on M4.  All these different uses
9855 revealed common needs factored into a layer over M4:
9856 @command{autom4te}@footnote{
9858 Yet another great name from Lars J. Aas.
9862 @command{autom4te} is a preprocessor that is like @command{m4}.
9863 It supports M4 extensions designed for use in tools like Autoconf.
9865 @menu
9866 * autom4te Invocation::         A @acronym{GNU} M4 wrapper
9867 * Customizing autom4te::        Customizing the Autoconf package
9868 @end menu
9870 @node autom4te Invocation
9871 @subsection Invoking @command{autom4te}
9873 The command line arguments are modeled after M4's:
9875 @example
9876 autom4te @var{options} @var{files}
9877 @end example
9879 @noindent
9880 @evindex M4
9881 where the @var{files} are directly passed to @command{m4}.  By default,
9882 @acronym{GNU} M4 is found during configuration, but the environment
9883 variable
9884 @env{M4} can be set to tell @command{autom4te} where to look.  In addition
9885 to the regular expansion, it handles the replacement of the quadrigraphs
9886 (@pxref{Quadrigraphs}), and of @samp{__oline__}, the current line in the
9887 output.  It supports an extended syntax for the @var{files}:
9889 @table @file
9890 @item @var{file}.m4f
9891 This file is an M4 frozen file.  Note that @emph{all the previous files
9892 are ignored}.  See the option @option{--melt} for the rationale.
9894 @item @var{file}?
9895 If found in the library path, the @var{file} is included for expansion,
9896 otherwise it is ignored instead of triggering a failure.
9897 @end table
9899 @sp 1
9901 Of course, it supports the Autoconf common subset of options:
9903 @table @option
9904 @item --help
9905 @itemx -h
9906 Print a summary of the command line options and exit.
9908 @item --version
9909 @itemx -V
9910 Print the version number of Autoconf and exit.
9912 @item --verbose
9913 @itemx -v
9914 Report processing steps.
9916 @item --debug
9917 @itemx -d
9918 Don't remove the temporary files and be even more verbose.
9920 @item --include=@var{dir}
9921 @itemx -I @var{dir}
9922 Also look for input files in @var{dir}.  Multiple invocations
9923 accumulate.
9925 @item --output=@var{file}
9926 @itemx -o @var{file}
9927 Save output (script or trace) to @var{file}.  The file @option{-} stands
9928 for the standard output.
9929 @end table
9931 @sp 1
9933 As an extension of @command{m4}, it includes the following options:
9935 @table @option
9936 @item --warnings=@var{category}
9937 @itemx -W @var{category}
9938 @evindex WARNINGS
9939 @c FIXME: Point to the M4sugar macros, not Autoconf's.
9940 Report the warnings related to @var{category} (which can actually be a
9941 comma separated list).  @xref{Reporting Messages}, macro
9942 @code{AC_DIAGNOSE}, for a comprehensive list of categories.  Special
9943 values include:
9945 @table @samp
9946 @item all
9947 report all the warnings
9949 @item none
9950 report none
9952 @item error
9953 treats warnings as errors
9955 @item no-@var{category}
9956 disable warnings falling into @var{category}
9957 @end table
9959 Warnings about @samp{syntax} are enabled by default, and the environment
9960 variable @env{WARNINGS}, a comma separated list of categories, is
9961 honored.  @samp{autom4te -W @var{category}} actually
9962 behaves as if you had run:
9964 @example
9965 autom4te --warnings=syntax,$WARNINGS,@var{category}
9966 @end example
9968 @noindent
9969 For example, if you want to disable defaults and @env{WARNINGS}
9970 of @command{autom4te}, but enable the warnings about obsolete
9971 constructs, you would use @option{-W none,obsolete}.
9973 @cindex Back trace
9974 @cindex Macro invocation stack
9975 @command{autom4te} displays a back trace for errors, but not for
9976 warnings; if you want them, just pass @option{-W error}.
9978 @item --melt
9979 @itemx -M
9980 Do not use frozen files.  Any argument @code{@var{file}.m4f} is
9981 replaced by @code{@var{file}.m4}.  This helps tracing the macros which
9982 are executed only when the files are frozen, typically
9983 @code{m4_define}.  For instance, running:
9985 @example
9986 autom4te --melt 1.m4 2.m4f 3.m4 4.m4f input.m4
9987 @end example
9989 @noindent
9990 is roughly equivalent to running:
9992 @example
9993 m4 1.m4 2.m4 3.m4 4.m4 input.m4
9994 @end example
9996 @noindent
9997 while
9999 @example
10000 autom4te 1.m4 2.m4f 3.m4 4.m4f input.m4
10001 @end example
10003 @noindent
10004 is equivalent to:
10006 @example
10007 m4 --reload-state=4.m4f input.m4
10008 @end example
10010 @item --freeze
10011 @itemx -F
10012 Produce a frozen state file.  @command{autom4te} freezing is stricter
10013 than M4's: it must produce no warnings, and no output other than empty
10014 lines (a line with white space is @emph{not} empty) and comments
10015 (starting with @samp{#}).  Unlike @command{m4}'s similarly-named option,
10016 this option takes no argument:
10018 @example
10019 autom4te 1.m4 2.m4 3.m4 --freeze --output=3.m4f
10020 @end example
10022 @noindent
10023 corresponds to
10025 @example
10026 m4 1.m4 2.m4 3.m4 --freeze-state=3.m4f
10027 @end example
10029 @item --mode=@var{octal-mode}
10030 @itemx -m @var{octal-mode}
10031 Set the mode of the non-traces output to @var{octal-mode}; by default
10032 @samp{0666}.
10033 @end table
10035 @sp 1
10037 @cindex @file{autom4te.cache}
10038 As another additional feature over @command{m4}, @command{autom4te}
10039 caches its results.  @acronym{GNU} M4 is able to produce a regular
10040 output and traces at the same time.  Traces are heavily used in the
10041 @acronym{GNU} Build System: @command{autoheader} uses them to build
10042 @file{config.h.in}, @command{autoreconf} to determine what
10043 @acronym{GNU} Build System components are used, @command{automake} to
10044 ``parse'' @file{configure.ac} etc.  To avoid recomputation,
10045 traces are cached while performing regular expansion,
10046 and conversely.  This cache is (actually, the caches are) stored in
10047 the directory @file{autom4te.cache}.  @emph{It can safely be removed}
10048 at any moment (especially if for some reason @command{autom4te}
10049 considers it trashed).
10051 @table @option
10052 @item --cache=@var{directory}
10053 @itemx -C @var{directory}
10054 Specify the name of the directory where the result should be cached.
10055 Passing an empty value disables caching.  Be sure to pass a relative
10056 file name, as for the time being, global caches are not supported.
10058 @item --no-cache
10059 Don't cache the results.
10061 @item --force
10062 @itemx -f
10063 If a cache is used, consider it obsolete (but update it anyway).
10064 @end table
10066 @sp 1
10068 Because traces are so important to the @acronym{GNU} Build System,
10069 @command{autom4te} provides high level tracing features as compared to
10070 M4, and helps exploiting the cache:
10072 @table @option
10073 @item --trace=@var{macro}[:@var{format}]
10074 @itemx -t @var{macro}[:@var{format}]
10075 Trace the invocations of @var{macro} according to the @var{format}.
10076 Multiple @option{--trace} arguments can be used to list several macros.
10077 Multiple @option{--trace} arguments for a single macro are not
10078 cumulative; instead, you should just make @var{format} as long as
10079 needed.
10081 The @var{format} is a regular string, with newlines if desired, and
10082 several special escape codes.  It defaults to @samp{$f:$l:$n:$%}.  It can
10083 use the following special escapes:
10085 @table @samp
10086 @item $$
10087 The character @samp{$}.
10089 @item $f
10090 The file name from which @var{macro} is called.
10092 @item $l
10093 The line number from which @var{macro} is called.
10095 @item $d
10096 The depth of the @var{macro} call.  This is an M4 technical detail that
10097 you probably don't want to know about.
10099 @item $n
10100 The name of the @var{macro}.
10102 @item $@var{num}
10103 The @var{num}th argument of the call to @var{macro}.
10105 @item $@@
10106 @itemx $@var{sep}@@
10107 @itemx $@{@var{separator}@}@@
10108 All the arguments passed to @var{macro}, separated by the character
10109 @var{sep} or the string @var{separator} (@samp{,} by default).  Each
10110 argument is quoted, i.e., enclosed in a pair of square brackets.
10112 @item $*
10113 @itemx $@var{sep}*
10114 @itemx $@{@var{separator}@}*
10115 As above, but the arguments are not quoted.
10117 @item $%
10118 @itemx $@var{sep}%
10119 @itemx $@{@var{separator}@}%
10120 As above, but the arguments are not quoted, all new line characters in
10121 the arguments are smashed, and the default separator is @samp{:}.
10123 The escape @samp{$%} produces single-line trace outputs (unless you put
10124 newlines in the @samp{separator}), while @samp{$@@} and @samp{$*} do
10125 not.
10126 @end table
10128 @xref{autoconf Invocation}, for examples of trace uses.
10130 @item --preselect=@var{macro}
10131 @itemx -p @var{macro}
10132 Cache the traces of @var{macro}, but do not enable traces.  This is
10133 especially important to save CPU cycles in the future.  For instance,
10134 when invoked, @command{autoconf} preselects all the macros that
10135 @command{autoheader}, @command{automake}, @command{autoreconf}, etc.,
10136 trace, so that running @command{m4} is not needed to trace them: the
10137 cache suffices.  This results in a huge speed-up.
10138 @end table
10140 @sp 1
10142 @cindex Autom4te Library
10143 Finally, @command{autom4te} introduces the concept of @dfn{Autom4te
10144 libraries}.  They consists in a powerful yet extremely simple feature:
10145 sets of combined command line arguments:
10147 @table @option
10148 @item --language=@var{language}
10149 @itemx -l @var{language}
10150 Use the @var{language} Autom4te library.  Current languages include:
10152 @table @code
10153 @item M4sugar
10154 create M4sugar output.
10156 @item M4sh
10157 create M4sh executable shell scripts.
10159 @item Autotest
10160 create Autotest executable test suites.
10162 @item Autoconf-without-aclocal-m4
10163 create Autoconf executable configure scripts without
10164 reading @file{aclocal.m4}.
10166 @item Autoconf
10167 create Autoconf executable configure scripts.  This language inherits
10168 all the characteristics of @code{Autoconf-without-aclocal-m4} and
10169 additionally reads @file{aclocal.m4}.
10170 @end table
10172 @item --prepend-include=@var{dir}
10173 @itemx -B @var{dir}
10174 Prepend directory @var{dir} to the search path.  This is used to include
10175 the language-specific files before any third-party macros.
10177 @end table
10179 @cindex @file{autom4te.cfg}
10180 As an example, if Autoconf is installed in its default location,
10181 @file{/usr/local}, the command @samp{autom4te -l m4sugar foo.m4} is
10182 strictly equivalent to the command:
10184 @example
10185 autom4te --prepend-include /usr/local/share/autoconf \
10186   m4sugar/m4sugar.m4f --warnings syntax foo.m4
10187 @end example
10189 @noindent
10190 Recursive expansion applies here: the command @samp{autom4te -l m4sh foo.m4}
10191 is the same as @samp{autom4te --language M4sugar m4sugar/m4sh.m4f
10192 foo.m4}, i.e.:
10194 @example
10195 autom4te --prepend-include /usr/local/share/autoconf \
10196   m4sugar/m4sugar.m4f m4sugar/m4sh.m4f --mode 777 foo.m4
10197 @end example
10199 @noindent
10200 The definition of the languages is stored in @file{autom4te.cfg}.
10202 @node Customizing autom4te
10203 @subsection Customizing @command{autom4te}
10205 One can customize @command{autom4te} via @file{~/.autom4te.cfg} (i.e.,
10206 as found in the user home directory), and @file{./.autom4te.cfg} (i.e.,
10207 as found in the directory from which @command{autom4te} is run).  The
10208 order is first reading @file{autom4te.cfg}, then @file{~/.autom4te.cfg},
10209 then @file{./.autom4te.cfg}, and finally the command line arguments.
10211 In these text files, comments are introduced with @code{#}, and empty
10212 lines are ignored.  Customization is performed on a per-language basis,
10213 wrapped in between a @samp{begin-language: "@var{language}"},
10214 @samp{end-language: "@var{language}"} pair.
10216 Customizing a language stands for appending options (@pxref{autom4te
10217 Invocation}) to the current definition of the language.  Options, and
10218 more generally arguments, are introduced by @samp{args:
10219 @var{arguments}}.  You may use the traditional shell syntax to quote the
10220 @var{arguments}.
10222 As an example, to disable Autoconf caches (@file{autom4te.cache})
10223 globally, include the following lines in @file{~/.autom4te.cfg}:
10225 @verbatim
10226 ## ------------------ ##
10227 ## User Preferences.  ##
10228 ## ------------------ ##
10230 begin-language: "Autoconf-without-aclocal-m4"
10231 args: --no-cache
10232 end-language: "Autoconf-without-aclocal-m4"
10233 @end verbatim
10236 @node Programming in M4sugar
10237 @section Programming in M4sugar
10239 @cindex M4sugar
10240 M4 by itself provides only a small, but sufficient, set of all-purpose
10241 macros.  M4sugar introduces additional generic macros.  Its name was
10242 coined by Lars J. Aas: ``Readability And Greater Understanding Stands 4
10243 M4sugar''.
10245 M4sugar reserves the macro namespace @samp{^_m4_} for internal use, and
10246 the macro namespace @samp{^m4_} for M4sugar macros.  You should not
10247 define your own macros into these namespaces.
10249 @menu
10250 * Redefined M4 Macros::         M4 builtins changed in M4sugar
10251 * Diagnostic Macros::           Diagnostic messages from M4sugar
10252 * Diversion support::           Diversions in M4sugar
10253 * Conditional constructs::      Conditions in M4
10254 * Looping constructs::          Iteration in M4
10255 * Evaluation Macros::           More quotation and evaluation control
10256 * Text processing Macros::      String manipulation in M4
10257 * Number processing Macros::    Arithmetic computation in M4
10258 * Set manipulation Macros::     Set manipulation in M4
10259 * Forbidden Patterns::          Catching unexpanded macros
10260 @end menu
10262 @node Redefined M4 Macros
10263 @subsection Redefined M4 Macros
10265 @msindex{builtin}
10266 @msindex{changecom}
10267 @msindex{changequote}
10268 @msindex{debugfile}
10269 @msindex{debugmode}
10270 @msindex{decr}
10271 @msindex{define}
10272 @msindex{divnum}
10273 @msindex{dumpdef}
10274 @msindex{errprint}
10275 @msindex{esyscmd}
10276 @msindex{eval}
10277 @msindex{format}
10278 @msindex{ifdef}
10279 @msindex{incr}
10280 @msindex{index}
10281 @msindex{indir}
10282 @msindex{len}
10283 @msindex{pushdef}
10284 @msindex{shift}
10285 @msindex{substr}
10286 @msindex{syscmd}
10287 @msindex{sysval}
10288 @msindex{traceoff}
10289 @msindex{traceon}
10290 @msindex{translit}
10291 With a few exceptions, all the M4 native macros are moved in the
10292 @samp{m4_} pseudo-namespace, e.g., M4sugar renames @code{define} as
10293 @code{m4_define} etc.
10295 The list of macros unchanged from M4, except for their name, is:
10296 @itemize @minus
10297 @item m4_builtin
10298 @item m4_changecom
10299 @item m4_changequote
10300 @item m4_debugfile
10301 @item m4_debugmode
10302 @item m4_decr
10303 @item m4_define
10304 @item m4_divnum
10305 @item m4_dumpdef
10306 @item m4_errprint
10307 @item m4_esyscmd
10308 @item m4_eval
10309 @item m4_format
10310 @item m4_ifdef
10311 @item m4_incr
10312 @item m4_index
10313 @item m4_indir
10314 @item m4_len
10315 @item m4_pushdef
10316 @item m4_shift
10317 @item m4_substr
10318 @item m4_syscmd
10319 @item m4_sysval
10320 @item m4_traceoff
10321 @item m4_traceon
10322 @item m4_translit
10323 @end itemize
10325 Some M4 macros are redefined, and are slightly incompatible with their
10326 native equivalent.
10328 @defmac __file__
10329 @defmacx __line__
10330 @MSindex __file__
10331 @MSindex __line__
10332 All M4 macros starting with @samp{__} retain their original name: for
10333 example, no @code{m4__file__} is defined.
10334 @end defmac
10336 @defmac __oline__
10337 @MSindex __oline__
10338 This is not technically a macro, but a feature of Autom4te.  The
10339 sequence @code{__oline__} can be used similarly to the other m4sugar
10340 location macros, but rather than expanding to the location of the input
10341 file, it is translated to the line number where it appears in the output
10342 file after all other M4 expansions.
10343 @end defmac
10345 @defmac dnl
10346 @MSindex dnl
10347 This macro kept its original name: no @code{m4_dnl} is defined.
10348 @end defmac
10350 @defmac m4_bpatsubst (@var{string}, @var{regexp}, @ovar{replacement})
10351 @msindex{bpatsubst}
10352 This macro corresponds to @code{patsubst}.  The name @code{m4_patsubst}
10353 is kept for future versions of M4sugar, once @acronym{GNU} M4 2.0 is
10354 released and supports extended regular expression syntax.
10355 @end defmac
10357 @defmac m4_bregexp (@var{string}, @var{regexp}, @ovar{replacement})
10358 @msindex{bregexp}
10359 This macro corresponds to @code{regexp}.  The name @code{m4_regexp}
10360 is kept for future versions of M4sugar, once @acronym{GNU} M4 2.0 is
10361 released and supports extended regular expression syntax.
10362 @end defmac
10364 @defmac m4_defn (@var{macro}@dots{})
10365 @msindex{defn}
10366 This macro fails if @var{macro} is not defined, even when using older
10367 versions of M4 that did not warn.  See @code{m4_undefine}.
10368 Unfortunately, in order to support these older versions of M4, there are
10369 some situations involving unbalanced quotes where concatenating multiple
10370 macros together will work in newer M4 but not in m4sugar; use
10371 quadrigraphs to work around this.
10372 @end defmac
10374 @defmac m4_divert (@var{diversion})
10375 @msindex{divert}
10376 M4sugar relies heavily on diversions, so rather than behaving as a
10377 primitive, @code{m4_divert} behaves like:
10378 @example
10379 m4_divert_pop()m4_divert_push([@var{diversion}])
10380 @end example
10381 @noindent
10382 @xref{Diversion support}, for more details about the use of the
10383 diversion stack.
10384 @end defmac
10386 @defmac m4_exit (@var{exit-status})
10387 @msindex{exit}
10388 This macro corresponds to @code{m4exit}.
10389 @end defmac
10391 @defmac m4_if (@var{comment})
10392 @defmacx m4_if (@var{string-1}, @var{string-2}, @var{equal}, @ovar{not-equal})
10393 @defmacx m4_if (@var{string-1}, @var{string-2}, @var{equal}, @dots{})
10394 @msindex{if}
10395 This macro corresponds to @code{ifelse}.  @var{string-1} and
10396 @var{string-2} are compared literally, so usually one of the two
10397 arguments is passed unquoted.  @xref{Conditional constructs}, for more
10398 conditional idioms.
10399 @end defmac
10401 @defmac m4_include (@var{file})
10402 @defmacx m4_sinclude (@var{file})
10403 @msindex{include}
10404 @msindex{sinclude}
10405 Like the M4 builtins, but warn against multiple inclusions of @var{file}.
10406 @end defmac
10408 @defmac m4_mkstemp (@var{template})
10409 @defmacx m4_maketemp (@var{template})
10410 @msindex{maketemp}
10411 @msindex{mkstemp}
10412 Posix requires @code{maketemp} to replace the trailing @samp{X}
10413 characters in @var{template} with the process id, without regards to the
10414 existence of a file by that name, but this a security hole.  When this
10415 was pointed out to the Posix folks, they agreed to invent a new macro
10416 @code{mkstemp} that always creates a uniquely named file, but not all
10417 versions of @acronym{GNU} M4 support the new macro.  In M4sugar,
10418 @code{m4_maketemp} and @code{m4_mkstemp} are synonyms for each other,
10419 and both have the secure semantics regardless of which macro the
10420 underlying M4 provides.
10421 @end defmac
10423 @defmac m4_popdef (@var{macro}@dots{})
10424 @msindex{popdef}
10425 This macro fails if @var{macro} is not defined, even when using older
10426 versions of M4 that did not warn.  See @code{m4_undefine}.
10427 @end defmac
10429 @defmac m4_undefine (@var{macro}@dots{})
10430 @msindex{undefine}
10431 This macro fails if @var{macro} is not defined, even when using older
10432 versions of M4 that did not warn.  Use
10434 @example
10435 m4_ifdef([@var{macro}], [m4_undefine([@var{macro}])])
10436 @end example
10438 @noindent
10439 if you are not sure whether @var{macro} is defined.
10440 @end defmac
10442 @defmac m4_undivert (@var{diversion})
10443 @msindex{undivert}
10444 Unlike the M4 builtin, only one diversion can be undiverted per
10445 invocation.  Also, since the M4sugar diversion stack prefers named
10446 diversions, the use of @code{m4_undivert} to include files is risky.
10447 @xref{Diversion support}, for more details about the use of the
10448 diversion stack.
10449 @end defmac
10451 @defmac m4_wrap (@var{text})
10452 @defmacx m4_wrap_lifo (@var{text})
10453 @msindex{wrap}
10454 @msindex{wrap_lifo}
10455 These macros correspond to @code{m4wrap}.  Posix requires arguments of
10456 multiple wrap calls to be reprocessed at @acronym{EOF} in the same order
10457 as the original calls (first-in, first-out).  @acronym{GNU} M4 versions
10458 through 1.4.10, however, reprocess them in reverse order (last-in,
10459 first-out).  Both orders are useful, therefore, you can rely on
10460 @code{m4_wrap} to provide FIFO semantics and @code{m4_wrap_lifo} for
10461 LIFO semantics, regardless of the underlying @acronym{GNU} M4 version.
10463 Unlike the @acronym{GNU} M4 builtin, these macros only recognize one
10464 argument, and avoid token pasting between consecutive invocations.  On
10465 the other hand, nested calls to @code{m4_wrap} from within wrapped text
10466 work just as in the builtin.
10467 @end defmac
10470 @node Diagnostic Macros
10471 @subsection Diagnostic messages from M4sugar
10472 @cindex Messages, from @command{M4sugar}
10474 When macros statically diagnose abnormal situations, benign or fatal,
10475 they should report them using these macros.  For issuing dynamic issues,
10476 i.e., when @command{configure} is run, see @ref{Printing Messages}.
10478 @defmac m4_assert (@var{expression}, @dvar{exit-status, 1})
10479 @msindex{assert}
10480 Assert that the arithmetic @var{expression} evaluates to non-zero.
10481 Otherwise, issue a fatal error, and exit @command{autom4te} with
10482 @var{exit-status}.
10483 @end defmac
10485 @defmac m4_errprintn (@var{message})
10486 @msindex{errprintn}
10487 Similar to the builtin @code{m4_errprint}, except that a newline is
10488 guaranteed after @var{message}.
10489 @end defmac
10491 @anchor{m4_fatal}
10492 @defmac m4_fatal (@var{message})
10493 @msindex{fatal}
10494 Report a severe error @var{message} prefixed with the current location,
10495 and have @command{autom4te} die.
10496 @end defmac
10498 @defmac m4_location
10499 @msindex{location}
10500 Useful as a prefix in a message line.  Short for:
10501 @example
10502 __file__:__line__
10503 @end example
10504 @end defmac
10506 @anchor{m4_warn}
10507 @defmac m4_warn (@var{category}, @var{message})
10508 @msindex{warn}
10509 Report @var{message} as a warning (or as an error if requested by the
10510 user) if warnings of the @var{category} are turned on.  If the message
10511 is emitted, it is prefixed with the current location, and followed by a
10512 call trace of all macros defined via @code{AC_DEFUN} used to get to the
10513 current expansion.  You are encouraged to use standard categories, which
10514 currently include:
10516 @table @samp
10517 @item all
10518 messages that don't fall into one of the following categories.  Use of an
10519 empty @var{category} is equivalent.
10521 @item cross
10522 related to cross compilation issues.
10524 @item obsolete
10525 use of an obsolete construct.
10527 @item syntax
10528 dubious syntactic constructs, incorrectly ordered macro calls.
10529 @end table
10530 @end defmac
10533 @node Diversion support
10534 @subsection Diversion support
10536 M4sugar makes heavy use of diversions, because it is often the case that
10537 text that must appear early in the output is not discovered until late
10538 in the input.  Additionally, some of the topological sorting algorithms
10539 used in resolving macro dependencies use diversions.  Therefore, most
10540 macros should not need to change diversions directly, but rather rely on
10541 higher-level M4sugar macros to manage diversions transparently.
10543 To make diversion management easier, M4sugar uses the concept of named
10544 diversions.  Rather than using diversion numbers directly, it is nicer
10545 to associate a name with each diversion; the diversion number associated
10546 with a particular diversion name is an implementation detail, so you
10547 should only use diversion names.  In general, you should not output text
10548 to a named diversion until after calling the appropriate initialization
10549 routine for your language (@code{m4_init}, @code{AS_INIT},
10550 @code{AT_INIT}, @dots{}), although there are some exceptions documented
10551 below.
10553 M4sugar defines two named diversions.
10554 @table @code
10555 @item KILL
10556 Text written to this diversion is discarded.  This is the default
10557 diversion once M4sugar is initialized.
10558 @item GROW
10559 This diversion is used behind the scenes by topological sorting macros,
10560 such as @code{AC_REQUIRE}.
10561 @end table
10563 M4sh adds several more named diversions.
10564 @table @code
10565 @item BINSH
10566 This diversion is reserved for the @samp{#!} interpreter line.
10567 @item HEADER-REVISION
10568 This diversion holds text from @code{AC_REVISION}.
10569 @item HEADER-COMMENT
10570 This diversion holds comments about the purpose of a file.
10571 @item HEADER-COPYRIGHT
10572 This diversion is managed by @code{AC_COPYRIGHT}.
10573 @item M4SH-SANITIZE
10574 This diversion contains M4sh sanitization code, used to ensure M4sh is
10575 executing in a reasonable shell environment.
10576 @item M4SH-INIT
10577 This diversion contains M4sh initialization code, initializing variables
10578 that are required by other M4sh macros.
10579 @item BODY
10580 This diversion contains the body of the shell code, and is the default
10581 diversion once M4sh is initialized.
10582 @end table
10584 Autotest inherits diversions from M4sh, and changes the default
10585 diversion from @code{BODY} back to @code{KILL}.  It also adds several
10586 more named diversions, with the following subset designed for developer
10587 use.
10588 @table @code
10589 @item PREPARE_TESTS
10590 This diversion contains initialization sequences which are executed
10591 after @file{atconfig} and @file{atlocal}, and after all command line
10592 arguments have been parsed, but prior to running any tests.  It can be
10593 used to set up state that is required across all tests.  This diversion
10594 will work even before @code{AT_INIT}.
10595 @end table
10597 For now, the named diversions of Autoconf and Autoheader, and the
10598 remaining diversions of Autotest, are not documented.  In other words,
10599 intentionally outputting text into an undocumented diversion is subject
10600 to breakage in a future release of Autoconf.
10602 @defmac m4_divert_once (@var{diversion}, @ovar{content})
10603 @msindex{divert_once}
10604 Similar to @code{m4_divert_text}, except that @var{content} is only
10605 output to @var{diversion} if this is the first time that
10606 @code{m4_divert_once} has been called with its particular arguments.
10607 @end defmac
10609 @defmac m4_divert_pop (@ovar{diversion})
10610 @msindex{divert_pop}
10611 If provided, check that the current diversion is indeed @var{diversion}.
10612 Then change to the diversion located earlier on the stack, giving an
10613 error if an attempt is made to pop beyond the initial m4sugar diversion
10614 of @code{KILL}.
10615 @end defmac
10617 @defmac m4_divert_push (@var{diversion})
10618 @msindex{divert_push}
10619 Remember the former diversion on the diversion stack, and output
10620 subsequent text into @var{diversion}.  M4sugar maintains a diversion
10621 stack, and issues an error if there is not a matching pop for every
10622 push.
10623 @end defmac
10625 @defmac m4_divert_text (@var{diversion}, @ovar{content})
10626 @msindex{divert_text}
10627 Output @var{content} and a newline into @var{diversion}, without
10628 affecting the current diversion.  Shorthand for:
10629 @example
10630 m4_divert_push([@var{diversion}])@var{content}
10631 m4_divert_pop([@var{diversion}])dnl
10632 @end example
10633 @end defmac
10635 @defmac m4_init
10636 @msindex{init}
10637 Initialize the M4sugar environment, setting up the default named
10638 diversion to be @code{KILL}.
10639 @end defmac
10641 @node Conditional constructs
10642 @subsection Conditional constructs
10644 The following macros provide additional conditional contructs, as
10645 convenience wrappers around @code{m4_if}.
10647 @defmac m4_bmatch (@var{string}, @var{regex-1}, @var{value-1}, @
10648   @ovar{regex-2}, @ovar{value-2}, @dots{}, @ovar{default})
10649 @msindex{bmatch}
10650 The string @var{string} is repeatedly compared against a series of
10651 @var{regex} arguments; if a match is found, the expansion is the
10652 corresponding @var{value}, otherwise, the macro moves on to the next
10653 @var{regex}.  If no @var{regex} match, then the result is the optional
10654 @var{default}, or nothing.
10655 @end defmac
10657 @defmac m4_bpatsubsts (@var{string}, @var{regex-1}, @var{subst-1}, @
10658   @ovar{regex-2}, @ovar{subst-2}, @dots{})
10659 @msindex{bpatsubsts}
10660 The string @var{string} is altered by @var{regex-1} and @var{subst-1},
10661 as if by:
10662 @example
10663 m4_bpatsubst([[@var{string}]], [@var{regex}], [@var{subst}])
10664 @end example
10666 @noindent
10667 The result of the substitution is then passed through the next set of
10668 @var{regex} and @var{subst}, and so forth.  An empty @var{subst} implies
10669 deletion of any matched portions in the current string.  Note that this
10670 macro over-quotes @var{string}; this behavior is intentional, so that
10671 the result of each step of the recursion remains as a quoted string.
10672 However, it means that anchors (@samp{^} and @samp{$} in the @var{regex}
10673 will line up with the extra quotations, and not the characters of the
10674 original string.  The overquoting is removed after the final
10675 substitution.
10676 @end defmac
10678 @defmac m4_case (@var{string}, @var{value-1}, @var{if-value-1}, @
10679   @ovar{value-2}, @ovar{if-value-2}, @dots{}, @ovar{default})
10680 @msindex{case}
10681 Test @var{string} against multiple @var{value} possibilities, resulting
10682 in the first @var{if-value} for a match, or in the optional
10683 @var{default}.  This is shorthand for:
10684 @example
10685 m4_if([@var{string}], [@var{value-1}], [@var{if-value-1}],
10686       [@var{string}], [@var{value-2}], [@var{if-value-2}], @dots{},
10687       [@var{default}])
10688 @end example
10689 @end defmac
10691 @defmac m4_cond (@var{test-1}, @var{value-1}, @var{if-value-1}, @
10692   @ovar{test-2}, @ovar{value-2}, @ovar{if-value-2}, @dots{}, @ovar{default})
10693 @msindex{cond}
10694 This macro was introduced in Autoconf 2.62.  Similar to @code{m4_if},
10695 except that each @var{test} is expanded only when it is encountered.
10696 This is useful for short-circuiting expensive tests; while @code{m4_if}
10697 requires all its strings to be expanded up front before doing
10698 comparisons, @code{m4_cond} only expands a @var{test} when all earlier
10699 tests have failed.
10701 For an example, these two sequences give the same result, but in the
10702 case where @samp{$1} does not contain a backslash, the @code{m4_cond}
10703 version only expands @code{m4_index} once, instead of five times, for
10704 faster computation if this is a common case for @samp{$1}.  Notice that
10705 every third argument is unquoted for @code{m4_if}, and quoted for
10706 @code{m4_cond}:
10708 @example
10709 m4_if(m4_index([$1], [\]), [-1], [$2],
10710       m4_eval(m4_index([$1], [\\]) >= 0), [1], [$2],
10711       m4_eval(m4_index([$1], [\$]) >= 0), [1], [$2],
10712       m4_eval(m4_index([$1], [\`]) >= 0), [1], [$3],
10713       m4_eval(m4_index([$1], [\"]) >= 0), [1], [$3],
10714       [$2])
10715 m4_cond([m4_index([$1], [\])], [-1], [$2],
10716         [m4_eval(m4_index([$1], [\\]) >= 0)], [1], [$2],
10717         [m4_eval(m4_index([$1], [\$]) >= 0)], [1], [$2],
10718         [m4_eval(m4_index([$1], [\`]) >= 0)], [1], [$3],
10719         [m4_eval(m4_index([$1], [\"]) >= 0)], [1], [$3],
10720         [$2])
10721 @end example
10722 @end defmac
10724 @defmac m4_default (@var{expr-1}, @var{expr-2})
10725 @defmacx m4_default_quoted (@var{expr-1}, @var{expr-2})
10726 @msindex{default}
10727 @msindex{default_quoted}
10728 If @var{expr-1} is not empty, use it.  Otherwise, select @var{expr-2}.
10729 @code{m4_default} expands the result, while @code{m4_default_quoted}
10730 does not.  Useful for providing a fixed default if the expression that
10731 results in @var{expr-1} would otherwise be empty.
10733 @example
10734 m4_define([active], [ACTIVE])dnl
10735 m4_define([demo1], [m4_default([$1], [$2])])dnl
10736 m4_define([demo2], [m4_default_quoted([$1], [$2])])dnl
10737 demo1([active], [default])
10738 @result{}ACTIVE
10739 demo1([], [active])
10740 @result{}ACTIVE
10741 demo2([active], [default])
10742 @result{}active
10743 demo2([], [active])
10744 @result{}active
10745 @end example
10746 @end defmac
10748 @defmac m4_ifndef (@var{macro}, @var{if-not-defined}, @ovar{if-defined})
10749 @msindex{ifndef}
10750 This is shorthand for:
10751 @example
10752 m4_ifdef([@var{macro}], [@var{if-defined}], [@var{if-not-defined}])
10753 @end example
10754 @end defmac
10756 @defmac m4_ifset (@var{macro}, @ovar{if-true}, @ovar{if-false})
10757 @msindex{ifset}
10758 If @var{macro} is undefined, or is defined as the empty string, expand
10759 to @var{if-false}.  Otherwise, expands to @var{if-true}.  Similar to:
10760 @example
10761 m4_ifval(m4_defn([@var{macro}]), [@var{if-true}], [@var{if-false}])
10762 @end example
10763 @noindent
10764 except that it is not an error if @var{macro} is undefined.
10765 @end defmac
10767 @defmac m4_ifval (@var{cond}, @ovar{if-true}, @ovar{if-false})
10768 @msindex{ifval}
10769 Expands to @var{if-true} if @var{cond} is not empty, otherwise to
10770 @var{if-false}.  This is shorthand for:
10771 @example
10772 m4_if([@var{cond}], [], [@var{if-true}], [@var{if-false}])
10773 @end example
10774 @end defmac
10776 @defmac m4_ifvaln (@var{cond}, @ovar{if-true}, @ovar{if-false})
10777 @msindex{ifvaln}
10778 Similar to @code{m4_ifval}, except guarantee that a newline is present
10779 after any non-empty expansion.
10780 @end defmac
10782 @defmac m4_n (@var{text})
10783 @msindex{n}
10784 Expand to @var{text}, and add a newline if @var{text} is not empty.
10785 @end defmac
10788 @node Looping constructs
10789 @subsection Looping constructs
10791 The following macros are useful in implementing recursive algorithms in
10792 M4, including loop operations.  An M4 list is formed by quoting a list
10793 of quoted elements; generally the lists are comma-separated, although
10794 @code{m4_foreach_w} is whitespace-separated.  For example, the list
10795 @samp{[[a], [b,c]]} contains two elements: @samp{[a]} and @samp{[b,c]}.
10796 It is common to see lists with unquoted elements when those elements are
10797 not likely to be macro names, as in @samp{[fputc_unlocked,
10798 fgetc_unlocked]}.
10800 Although not generally recommended, it is possible for quoted lists to
10801 have side effects; all side effects are expanded only once, and prior to
10802 visiting any list element.  On the other hand, the fact that unquoted
10803 macros are expanded exactly once means that macros without side effects
10804 can be used to generate lists.  For example,
10806 @example
10807 m4_foreach([i], [[1], [2], [3]m4_errprintn([hi])], [i])
10808 @error{}hi
10809 @result{}123
10810 m4_define([list], [[1], [2], [3]])
10811 @result{}
10812 m4_foreach([i], [list], [i])
10813 @result{}123
10814 @end example
10816 @defmac m4_car (@var{list})
10817 @msindex{car}
10818 Expands to the quoted first element of the comma-separated quoted
10819 @var{list}.  Often used with @code{m4_cdr} to recursively iterate
10820 through a list.  Generally, when using quoted lists of quoted elements,
10821 @code{m4_car} should be called without any extra quotes.
10822 @end defmac
10824 @defmac m4_cdr (@var{list})
10825 @msindex{cdr}
10826 Expands to a quoted list of all but the first element of the
10827 comma-separated quoted @var{list}, or the empty string if @var{list} had
10828 only one element.  Generally, when using quoted lists of quoted
10829 elements, @code{m4_cdr} should be called without any extra quotes.
10831 For example, this is a simple implementation of @code{m4_map}; note how
10832 each iteration checks for the end of recursion, then merely applies the
10833 first argument to the first element of the list, then repeats with the
10834 rest of the list.  (The actual implementation in M4sugar is a bit more
10835 involved, to gain some speed and share code with @code{m4_map_sep}).
10836 @example
10837 m4_define([m4_map], [m4_ifval([$2],
10838   [m4_apply([$1], m4_car($2))[]$0([$1], m4_cdr($2))])])dnl
10839 m4_map([ m4_eval], [[[1]], [[1+1]], [[10],[16]]])
10840 @result{} 1 2 a
10841 @end example
10842 @end defmac
10844 @defmac m4_for (@var{var}, @var{first}, @var{last}, @ovar{step}, @
10845   @var{expression})
10846 @msindex{for}
10847 Loop over the numeric values between @var{first} and @var{last}
10848 including bounds by increments of @var{step}.  For each iteration,
10849 expand @var{expression} with the numeric value assigned to @var{var}.
10850 If @var{step} is omitted, it defaults to @samp{1} or @samp{-1} depending
10851 on the order of the limits.  If given, @var{step} has to match this
10852 order.  The number of iterations is determined independently from
10853 definition of @var{var}; iteration cannot be short-circuited or
10854 lengthened by modifying @var{var} from within @var{expression}.
10855 @end defmac
10857 @defmac m4_foreach (@var{var}, @var{list}, @var{expression})
10858 @msindex{foreach}
10859 Loop over the comma-separated M4 list @var{list}, assigning each value
10860 to @var{var}, and expand @var{expression}.  The following example
10861 outputs two lines:
10863 @example
10864 m4_foreach([myvar], [[foo], [bar, baz]],
10865            [echo myvar
10866 ])dnl
10867 @result{}echo foo
10868 @result{}echo bar, baz
10869 @end example
10870 @end defmac
10872 @anchor{m4_foreach_w}
10873 @defmac m4_foreach_w (@var{var}, @var{list}, @var{expression})
10874 @msindex{foreach_w}
10875 Loop over the white-space-separated list @var{list}, assigning each value
10876 to @var{var}, and expand @var{expression}.
10878 The deprecated macro @code{AC_FOREACH} is an alias of
10879 @code{m4_foreach_w}.
10880 @end defmac
10882 @defmac m4_map (@var{macro}, @var{list})
10883 @defmacx m4_mapall (@var{macro}, @var{list})
10884 @defmacx m4_map_sep (@var{macro}, @var{separator}, @var{list})
10885 @defmacx m4_mapall_sep (@var{macro}, @var{separator}, @var{list})
10886 @msindex{map}
10887 @msindex{mapall}
10888 @msindex{map_sep}
10889 @msindex{mapall_sep}
10890 Loop over the comma separated quoted list of argument descriptions in
10891 @var{list}, and invoke @var{macro} with the arguments.  An argument
10892 description is in turn a comma-separated quoted list of quoted elements,
10893 suitable for @code{m4_apply}.  The macros @code{m4_map} and
10894 @code{m4_map_sep} ignore empty argument descriptions, while
10895 @code{m4_mapall} and @code{m4_mapall_sep} invoke @var{macro} with no
10896 arguments.  The macros @code{m4_map_sep} and @code{m4_mapall_sep}
10897 additionally expand @var{separator} between invocations of @var{macro}.
10899 Note that @var{separator} is expanded, unlike in @code{m4_join}.  When
10900 separating output with commas, this means that the map result can be
10901 used as a series of arguments, by using a single-quoted comma as
10902 @var{separator}, or as a single string, by using a double-quoted comma.
10904 @example
10905 m4_map([m4_count], [])
10906 @result{}
10907 m4_map([ m4_count], [[],
10908                      [[1]],
10909                      [[1], [2]]])
10910 @result{} 1 2
10911 m4_mapall([ m4_count], [[],
10912                         [[1]],
10913                         [[1], [2]]])
10914 @result{} 0 1 2
10915 m4_map_sep([m4_eval], [,], [[[1+2]],
10916                             [[10], [16]]])
10917 @result{}3,a
10918 m4_map_sep([m4_echo], [,], [[[a]], [[b]]])
10919 @result{}a,b
10920 m4_count(m4_map_sep([m4_echo], [,], [[[a]], [[b]]]))
10921 @result{}2
10922 m4_map_sep([m4_echo], [[,]], [[[a]], [[b]]])
10923 @result{}a,b
10924 m4_count(m4_map_sep([m4_echo], [[,]], [[[a]], [[b]]]))
10925 @result{}1
10926 @end example
10927 @end defmac
10929 @defmac m4_shiftn (@var{count}, @dots{})
10930 @defmacx m4_shift2 (@dots{})
10931 @defmacx m4_shift3 (@dots{})
10932 @msindex{shift2}
10933 @msindex{shift3}
10934 @msindex{shiftn}
10935 @code{m4_shiftn} performs @var{count} iterations of @code{m4_shift},
10936 along with validation that enough arguments were passed in to match the
10937 shift count, and that the count is positive.  @code{m4_shift2} and
10938 @code{m4_shift3} are specializations
10939 of @code{m4_shiftn}, introduced in Autoconf 2.62, and are more efficient
10940 for two and three shifts, respectively.
10941 @end defmac
10944 @node Evaluation Macros
10945 @subsection Evaluation Macros
10947 The following macros give some control over the order of the evaluation
10948 by adding or removing levels of quotes.
10950 @defmac m4_apply (@var{macro}, @var{list})
10951 @msindex{apply}
10952 Apply the elements of the quoted, comma-separated @var{list} as the
10953 arguments to @var{macro}.  If @var{list} is empty, invoke @var{macro}
10954 without arguments.  Note the difference between @code{m4_indir}, which
10955 expects its first argument to be a macro name but can use names that are
10956 otherwise invalid, and @code{m4_apply}, where @var{macro} can contain
10957 other text, but must end in a valid macro name.
10958 @example
10959 m4_apply([m4_count], [])
10960 @result{}0
10961 m4_apply([m4_count], [[]])
10962 @result{}1
10963 m4_apply([m4_count], [[1], [2]])
10964 @result{}2
10965 m4_apply([m4_join], [[|], [1], [2]])
10966 @result{}1|2
10967 @end example
10968 @end defmac
10970 @defmac m4_count (@var{arg}, @dots{})
10971 @msindex{count}
10972 This macro returns the decimal count of the number of arguments it was
10973 passed.
10974 @end defmac
10976 @defmac m4_do (@var{arg}, @dots{})
10977 @msindex{do}
10978 This macro loops over its arguments and expands each @var{arg} in
10979 sequence.  Its main use is for readability; it allows the use of
10980 indentation and fewer @code{dnl} to result in the same expansion.  This
10981 macro guarantees that no expansion will be concatenated with subsequent
10982 text; to achieve full concatenation, use @code{m4_unquote(m4_join([],
10983 @var{arg@dots{}}))}.
10985 @example
10986 m4_define([ab],[1])m4_define([bc],[2])m4_define([abc],[3])dnl
10987 m4_do([a],[b])c
10988 @result{}abc
10989 m4_unquote(m4_join([],[a],[b]))c
10990 @result{}3
10991 m4_define([a],[A])m4_define([b],[B])m4_define([c],[C])dnl
10992 m4_define([AB],[4])m4_define([BC],[5])m4_define([ABC],[6])dnl
10993 m4_do([a],[b])c
10994 @result{}ABC
10995 m4_unquote(m4_join([],[a],[b]))c
10996 @result{}3
10997 @end example
10998 @end defmac
11000 @defmac m4_dquote (@var{arg}, @dots{})
11001 @msindex{dquote}
11002 Return the arguments as a quoted list of quoted arguments.
11003 Conveniently, if there is just one @var{arg}, this effectively adds a
11004 level of quoting.
11005 @end defmac
11007 @defmac m4_dquote_elt (@var{arg}, @dots{})
11008 @msindex{dquote_elt}
11009 Return the arguments as a series of double-quoted arguments.  Whereas
11010 @code{m4_dquote} returns a single argument, @code{m4_dquote_elt} returns
11011 as many arguments as it was passed.
11012 @end defmac
11014 @defmac m4_echo (@var{arg}, @dots{})
11015 @msindex{echo}
11016 Return the arguments, with the same level of quoting.  Other than
11017 discarding whitespace after unquoted commas, this macro is a no-op.
11018 @end defmac
11020 @defmac m4_expand (@var{arg})
11021 @msindex{expand}
11022 Return the expansion of @var{arg} as a quoted string.  Whereas
11023 @code{m4_quote} is designed to collect expanded text into a single
11024 argument, @code{m4_expand} is designed to perform one level of expansion
11025 on quoted text.  The distinction is in the treatment of whitespace
11026 following a comma in the original @var{arg}.  Any time multiple
11027 arguments are collected into one with @code{m4_quote}, the M4 argument
11028 collection rules discard the whitespace.  However, with @code{m4_expand},
11029 whitespace is preserved, even after the expansion of macros contained in
11030 @var{arg}.
11032 @example
11033 m4_define([active], [ACT, IVE])dnl
11034 m4_define([active2], [[ACT, IVE]])dnl
11035 m4_quote(active, active)
11036 @result{}ACT,IVE,ACT,IVE
11037 m4_expand([active, active])
11038 @result{}ACT, IVE, ACT, IVE
11039 m4_quote(active2, active2)
11040 @result{}ACT, IVE,ACT, IVE
11041 m4_expand([active2, active2])
11042 @result{}ACT, IVE, ACT, IVE
11043 @end example
11045 Note that @code{m4_expand} cannot handle an @var{arg} that expands to
11046 literal unbalanced quotes, but that quadrigraphs can be used when
11047 unbalanced output is necessary.  Likewise, unbalanced parentheses must
11048 be supplied with double quoting or a quadrigraph.
11050 @example
11051 m4_define([pattern], [[!@@<:@@]])dnl
11052 m4_define([bar], [BAR])dnl
11053 m4_expand([case $foo in
11054   m4_defn([pattern])@@:@}@@ bar ;;
11055   *[)] blah ;;
11056 esac])
11057 @result{}case $foo in
11058 @result{}  [![]) BAR ;;
11059 @result{}  *) blah ;;
11060 @result{}esac
11061 @end example
11062 @end defmac
11064 @defmac m4_ignore (@dots{})
11065 @msindex{ignore}
11066 This macro was introduced in Autoconf 2.62.  Expands to nothing,
11067 ignoring all of its arguments.  By itself, this isn't very useful.
11068 However, it can be used to conditionally ignore an arbitrary number of
11069 arguments, by deciding which macro name to apply to a list of arguments.
11070 @example
11071 dnl foo outputs a message only if [debug] is defined.
11072 m4_define([foo],
11073 [m4_ifdef([debug],[AC_MSG_NOTICE],[m4_ignore])([debug message])])
11074 @end example
11076 Note that for earlier versions of Autoconf, the macro @code{__gnu__} can
11077 serve the same purpose, although it is less readable.
11078 @end defmac
11080 @defmac m4_make_list (@var{arg}, @dots{})
11081 @msindex{make_list}
11082 This macro exists to aid debugging of M4sugar algorithms.  Its net
11083 effect is similar to @code{m4_dquote}---it produces a quoted list of
11084 quoted arguments, for each @var{arg}.  The difference is that this
11085 version uses a comma-newline separator instead of just comma, to improve
11086 readability of the list; with the result that it is less efficient than
11087 @code{m4_dquote}.
11088 @example
11089 m4_define([zero],[0])m4_define([one],[1])m4_define([two],[2])dnl
11090 m4_dquote(zero, [one], [[two]])
11091 @result{}[0],[one],[[two]]
11092 m4_make_list(zero, [one], [[two]])
11093 @result{}[0],
11094 @result{}[one],
11095 @result{}[[two]]
11096 m4_foreach([number], m4_dquote(zero, [one], [[two]]), [ number])
11097 @result{} 0 1 two
11098 m4_foreach([number], m4_make_list(zero, [one], [[two]]), [ number])
11099 @result{} 0 1 two
11100 @end example
11101 @end defmac
11103 @c m4_noquote is too dangerous to document - it invokes macros that
11104 @c probably rely on @samp{[]} nested quoting for proper operation.  The
11105 @c user should generally prefer m4_unquote instead.
11107 @defmac m4_quote (@var{arg}, @dots{})
11108 @msindex{quote}
11109 Return the arguments as a single entity, i.e., wrap them into a pair of
11110 quotes.  This effectively collapses multiple arguments into one,
11111 although it loses whitespace after unquoted commas in the process.
11112 @end defmac
11114 @defmac m4_reverse (@var{arg}, @dots{})
11115 @msindex{reverse}
11116 Outputs each argument with the same level of quoting, but in reverse
11117 order, and with space following each comma for readability.
11119 @example
11120 m4_define([active], [ACT,IVE])
11121 @result{}
11122 m4_reverse(active, [active])
11123 @result{}active, IVE, ACT
11124 @end example
11125 @end defmac
11127 @defmac m4_unquote (@var{arg}, @dots{})
11128 @msindex{unquote}
11129 This macro was introduced in Autoconf 2.62.  Expand each argument,
11130 separated by commas.  For a single @var{arg}, this effectively removes a
11131 layer of quoting, and @code{m4_unquote([@var{arg}])} is more efficient
11132 than the equivalent @code{m4_do([@var{arg}])}.  For multiple arguments,
11133 this results in an unquoted list of expansions.  This is commonly used
11134 with @code{m4_split}, in order to convert a single quoted list into a
11135 series of quoted elements.
11136 @end defmac
11138 The following example aims at emphasizing the difference between several
11139 scenarios: not using these macros, using @code{m4_defn}, using
11140 @code{m4_quote}, using @code{m4_dquote}, and using @code{m4_expand}.
11142 @example
11143 $ @kbd{cat example.m4}
11144 dnl Overquote, so that quotes are visible.
11145 m4_define([show], [$[]1 = [$1], $[]@@ = [$@@]])
11146 m4_define([a], [A])
11147 m4_define([mkargs], [1, 2[,] 3])
11148 m4_define([arg1], [[$1]])
11149 m4_divert([0])dnl
11150 show(a, b)
11151 show([a, b])
11152 show(m4_quote(a, b))
11153 show(m4_dquote(a, b))
11154 show(m4_expand([a, b]))
11156 arg1(mkargs)
11157 arg1([mkargs])
11158 arg1(m4_defn([mkargs]))
11159 arg1(m4_quote(mkargs))
11160 arg1(m4_dquote(mkargs))
11161 arg1(m4_expand([mkargs]))
11162 $ @kbd{autom4te -l m4sugar example.m4}
11163 $1 = A, $@@ = [A],[b]
11164 $1 = a, b, $@@ = [a, b]
11165 $1 = A,b, $@@ = [A,b]
11166 $1 = [A],[b], $@@ = [[A],[b]]
11167 $1 = A, b, $@@ = [A, b]
11170 mkargs
11171 1, 2[,] 3
11172 1,2, 3
11173 [1],[2, 3]
11174 1, 2, 3
11175 @end example
11178 @node Text processing Macros
11179 @subsection String manipulation in M4
11181 The following macros may be used to manipulate strings in M4.  Many of
11182 the macros in this section intentionally result in quoted strings as
11183 output, rather than subjecting the arguments to further expansions.  As
11184 a result, if you are manipulating text that contains active M4
11185 characters, the arguments are passed with single quoting rather than
11186 double.
11188 @defmac m4_append (@var{macro-name}, @var{string}, @ovar{separator})
11189 @defmacx m4_append_uniq (@var{macro-name}, @var{string}, @ovar{separator} @
11190   @ovar{if-uniq}, @ovar{if-duplicate})
11191 @msindex{append}
11192 @msindex{append_uniq}
11193 Redefine @var{macro-name} to its former contents with @var{separator}
11194 and @var{string} added at the end.  If @var{macro-name} was undefined
11195 before (but not if it was defined but empty), then no @var{separator} is
11196 added.  As of Autoconf 2.62, neither @var{string} nor @var{separator}
11197 are expanded during this macro; instead, they are expanded when
11198 @var{macro-name} is invoked.
11200 @code{m4_append} can be used to grow strings, and @code{m4_append_uniq}
11201 to grow strings without duplicating substrings.  Additionally,
11202 @code{m4_append_uniq} takes two optional parameters as of Autoconf 2.62;
11203 @var{if-uniq} is expanded if @var{string} was appended, and
11204 @var{if-duplicate} is expanded if @var{string} was already present.
11205 Also, @code{m4_append_uniq} warns if @var{separator} is not empty, but
11206 occurs within @var{string}, since that can lead to duplicates.
11208 Note that @code{m4_append} can scale linearly in the length of the final
11209 string, depending on the quality of the underlying M4 implementation,
11210 while @code{m4_append_uniq} has an inherent quadratic scaling factor.
11211 If an algorithm can tolerate duplicates in the final string, use the
11212 former for speed.  If duplicates must be avoided, consider using
11213 @code{m4_set_add} instead (@pxref{Set manipulation Macros}).
11215 @example
11216 m4_define([active], [ACTIVE])dnl
11217 m4_append([sentence], [This is an])dnl
11218 m4_append([sentence], [ active ])dnl
11219 m4_append([sentence], [symbol.])dnl
11220 sentence
11221 @result{}This is an ACTIVE symbol.
11222 m4_undefine([active])dnl
11223 @result{}This is an active symbol.
11224 m4_append_uniq([list], [one], [, ], [new], [existing])
11225 @result{}new
11226 m4_append_uniq([list], [one], [, ], [new], [existing])
11227 @result{}existing
11228 m4_append_uniq([list], [two], [, ], [new], [existing])
11229 @result{}new
11230 m4_append_uniq([list], [three], [, ], [new], [existing])
11231 @result{}new
11232 m4_append_uniq([list], [two], [, ], [new], [existing])
11233 @result{}existing
11234 list
11235 @result{}one, two, three
11236 m4_dquote(list)
11237 @result{}[one],[two],[three]
11238 m4_append([list2], [one], [[, ]])dnl
11239 m4_append_uniq([list2], [two], [[, ]])dnl
11240 m4_append([list2], [three], [[, ]])dnl
11241 list2
11242 @result{}one, two, three
11243 m4_dquote(list2)
11244 @result{}[one, two, three]
11245 @end example
11246 @end defmac
11248 @defmac m4_append_uniq_w (@var{macro-name}, @var{strings})
11249 @msindex{append_uniq_w}
11250 This macro was introduced in Autoconf 2.62.  It is similar to
11251 @code{m4_append_uniq}, but treats @var{strings} as a whitespace
11252 separated list of words to append, and only appends unique words.
11253 @var{macro-name} is updated with a single space between new words.
11254 @example
11255 m4_append_uniq_w([numbers], [1 1 2])dnl
11256 m4_append_uniq_w([numbers], [ 2 3 ])dnl
11257 numbers
11258 @result{}1 2 3
11259 @end example
11260 @end defmac
11262 @defmac m4_combine (@ovar{separator}, @var{prefix-list}, @ovar{infix}, @
11263   @var{suffix-1}, @ovar{suffix-2}, @dots{})
11264 @msindex{combine}
11265 This macro produces a quoted string containing the pairwise combination
11266 of every element of the quoted, comma-separated @var{prefix-list}, and
11267 every element from the @var{suffix} arguments.  Each pairwise
11268 combination is joined with @var{infix} in the middle, and successive
11269 pairs are joined by @var{separator}.  No expansion occurs on any of the
11270 arguments.  No output occurs if either the @var{prefix} or @var{suffix}
11271 list is empty, but the lists can contain empty elements.
11272 @example
11273 m4_define([a], [oops])dnl
11274 m4_combine([, ], [[a], [b], [c]], [-], [1], [2], [3])
11275 @result{}a-1, a-2, a-3, b-1, b-2, b-3, c-1, c-2, c-3
11276 m4_combine([, ], [[a], [b]], [-])
11277 @result{}
11278 m4_combine([, ], [[a], [b]], [-], [])
11279 @result{}a-, b-
11280 m4_combine([, ], [], [-], [1], [2])
11281 @result{}
11282 m4_combine([, ], [[]], [-], [1], [2])
11283 @result{}-1, -2
11284 @end example
11285 @end defmac
11287 @defmac m4_flatten (@var{string})
11288 @msindex{flatten}
11289 Flatten @var{string} into a single line.  Delete all backslash-newline
11290 pairs, and replace all remaining newlines with a space.  The result is
11291 still a quoted string.
11292 @end defmac
11294 @defmac m4_join (@ovar{separator}, @var{args}@dots{})
11295 @defmacx m4_joinall (@ovar{separator}, @var{args}@dots{})
11296 @msindex{join}
11297 @msindex{joinall}
11298 Concatenate each @var{arg}, separated by @var{separator}.
11299 @code{joinall} uses every argument, while @code{join} omits empty
11300 arguments so that there are no back-to-back separators in the output.
11301 The result is a quoted string.
11302 @example
11303 m4_define([active], [ACTIVE])dnl
11304 m4_join([|], [one], [], [active], [two])
11305 @result{}one|active|two
11306 m4_joinall([|], [one], [], [active], [two])
11307 @result{}one||active|two
11308 @end example
11310 Note that if all you intend to do is join @var{args} with commas between
11311 them, to form a quoted list suitable for @code{m4_foreach}, it is more
11312 efficient to use @code{m4_dquote}.
11313 @end defmac
11315 @defmac m4_newline
11316 @msindex{newline}
11317 This macro was introduced in Autoconf 2.62, and expands to a newline.
11318 It is primarily useful for maintaining macro formatting, and ensuring
11319 that M4 does not discard leading whitespace during argument collection.
11320 @end defmac
11322 @defmac m4_normalize (@var{string})
11323 @msindex{normalize}
11324 Remove leading and trailing spaces and tabs, sequences of
11325 backslash-then-newline, and replace multiple spaces, tabs, and newlines
11326 with a single space.  This is a combination of @code{m4_flatten} and
11327 @code{m4_strip}.
11328 @end defmac
11330 @defmac m4_re_escape (@var{string})
11331 @msindex{re_escape}
11332 Backslash-escape all characters in @var{string} that are active in
11333 regexps.
11334 @end defmac
11336 @defmac m4_split (@var{string}, @dvar{regexp, [\t ]+})
11337 @msindex{split}
11338 Split @var{string} into an M4 list of elements quoted by @samp{[} and
11339 @samp{]}, while keeping white space at the beginning and at the end.
11340 If @var{regexp} is given, use it instead of @samp{[\t ]+} for splitting.
11341 If @var{string} is empty, the result is an empty list.
11342 @end defmac
11344 @defmac m4_strip (@var{string})
11345 @msindex{strip}
11346 Strip whitespace from @var{string}.  Sequences of spaces and tabs are
11347 reduced to a single space, then leading and trailing spaces are removed.
11348 The result is still a quoted string.  Note that this does not interfere
11349 with newlines; if you want newlines stripped as well, consider
11350 @code{m4_flatten}, or do it all at once with @code{m4_normalize}.
11351 @end defmac
11353 @defmac m4_text_box (@var{message}, @dvar{frame, -})
11354 @msindex{text_box}
11355 Add a text box around @var{message}, using @var{frame} as the border
11356 character above and below the message.  The frame correctly accounts for
11357 the subsequent expansion of @var{message}.  For example:
11358 @example
11359 m4_define([macro], [abc])dnl
11360 m4_text_box([macro])
11361 @result{}## --- ##
11362 @result{}## abc ##
11363 @result{}## --- ##
11364 @end example
11366 The @var{message} must contain balanced quotes and parentheses, although
11367 quadrigraphs can be used to work around this.
11368 @end defmac
11370 @defmac m4_text_wrap (@var{string}, @ovar{prefix}, @
11371   @dvar{prefix1, @var{prefix}}, @dvar{width, 79})
11372 @msindex{text_wrap}
11373 Break @var{string} into a series of whitespace-separated words, then
11374 output those words separated by spaces, and wrapping lines any time the
11375 output would exceed @var{width} columns.  If given, @var{prefix1} begins
11376 the first line, and @var{prefix} begins all wrapped lines.  If
11377 @var{prefix1} is longer than @var{prefix}, then the first line consists
11378 of just @var{prefix1}.  If @var{prefix} is longer than @var{prefix1},
11379 padding is inserted so that the first word of @var{string} begins at the
11380 same indentation as all wrapped lines.  Note that using literal tab
11381 characters in any of the arguments will interfere with the calculation
11382 of width.  No expansions occur on @var{prefix}, @var{prefix1}, or the
11383 words of @var{string}, although quadrigraphs are recognized.
11385 For some examples:
11386 @example
11387 m4_text_wrap([Short string */], [   ], [/* ], [20])
11388 @result{}/* Short string */
11389 m4_text_wrap([Much longer string */], [   ], [/* ], [20])
11390 @result{}/* Much longer
11391 @result{}   string */
11392 m4_text_wrap([Short doc.], [          ], [  --short ], [30])
11393 @result{}  --short Short doc.
11394 m4_text_wrap([Short doc.], [          ], [  --too-wide ], [30])
11395 @result{}  --too-wide
11396 @result{}          Short doc.
11397 m4_text_wrap([Super long documentation.], [     ],
11398              [  --too-wide ], 30)
11399 @result{}  --too-wide
11400 @result{}     Super long
11401 @result{}     documentation.
11402 @end example
11403 @end defmac
11405 @defmac m4_tolower (@var{string})
11406 @defmacx m4_toupper (@var{string})
11407 @msindex{tolower}
11408 @msindex{toupper}
11409 Return @var{string} with letters converted to upper or lower case,
11410 respectively.
11411 @end defmac
11413 @node Number processing Macros
11414 @subsection Arithmetic computation in M4
11416 The following macros facilitate integer arithmetic operations.
11417 Where a parameter is documented as taking an arithmetic expression, you
11418 can use anything that can be parsed by @code{m4_eval}.
11420 @defmac m4_cmp (@var{expr-1}, @var{expr-2})
11421 @msindex{cmp}
11422 Compare the arithmetic expressions @var{expr-1} and @var{expr-2}, and
11423 expand to @samp{-1} if @var{expr-1} is smaller, @samp{0} if they are
11424 equal, and @samp{1} if @var{expr-1} is larger.
11425 @end defmac
11427 @defmac m4_list_cmp (@var{list-1}, @var{list-2})
11428 @msindex{list_cmp}
11429 Compare the two M4 lists consisting of comma-separated arithmetic
11430 expressions, left to right.  Expand to @samp{-1} for the first element
11431 pairing where the value from @var{list-1} is smaller, @samp{1} where the
11432 value from @var{list-2} is smaller, or @samp{0} if both lists have the
11433 same values.  If one list is shorter than the other, the remaining
11434 elements of the longer list are compared against zero.
11435 @example
11436 m4_list_cmp([1, 0],       [1])
11437 @result{}0
11438 m4_list_cmp([1, [1 * 0]], [1, 0])
11439 @result{}0
11440 m4_list_cmp([1, 2],       [1, 0])
11441 @result{}1
11442 m4_list_cmp([1, [1+1], 3],[1, 2])
11443 @result{}1
11444 m4_list_cmp([1, 2, -3],   [1, 2])
11445 @result{}-1
11446 m4_list_cmp([1, 0],       [1, 2])
11447 @result{}-1
11448 m4_list_cmp([1],          [1, 2])
11449 @result{}-1
11450 @end example
11451 @end defmac
11453 @defmac m4_max (@var{arg}, @dots{})
11454 @msindex{max}
11455 This macro was introduced in Autoconf 2.62.  Expand to the decimal value
11456 of the maximum arithmetic expression among all the arguments.
11457 @end defmac
11459 @defmac m4_min (@var{arg}, @dots{})
11460 @msindex{min}
11461 This macro was introduced in Autoconf 2.62.  Expand to the decimal value
11462 of the minimum arithmetic expression among all the arguments.
11463 @end defmac
11465 @defmac m4_sign (@var{expr})
11466 @msindex{sign}
11467 Expand to @samp{-1} if the arithmetic expression @var{expr} is negative,
11468 @samp{1} if it is positive, and @samp{0} if it is zero.
11469 @end defmac
11471 @anchor{m4_version_compare}
11472 @defmac m4_version_compare (@var{version-1}, @var{version-2})
11473 @msindex{version_compare}
11474 This macro was introduced in Autoconf 2.53, but had a number of
11475 usability limitations that were not lifted until Autoconf 2.62.  Compare
11476 the version strings @var{version-1} and @var{version-2}, and expand to
11477 @samp{-1} if @var{version-1} is smaller, @samp{0} if they are the same,
11478 or @samp{1} @var{version-2} is smaller.  Version strings must be a list
11479 of elements separated by @samp{.}, @samp{,} or @samp{-}, where each
11480 element is a number along with optional case-insensitive letters
11481 designating beta releases.  The comparison stops at the leftmost element
11482 that contains a difference, although a 0 element compares equal to a
11483 missing element.
11485 It is permissible to include commit identifiers in @var{version}, such
11486 as an abbreviated SHA1 of the commit, provided there is still a
11487 monotonically increasing prefix to allow for accurate version-based
11488 comparisons.  For example, this paragraph was written when the
11489 development snapshot of autoconf claimed to be at version
11490 @samp{2.61a-248-dc51}, or 248 commits after the 2.61a release, with an
11491 abbreviated commit identification of @samp{dc51}.
11493 @example
11494 m4_version_compare([1.1], [2.0])
11495 @result{}-1
11496 m4_version_compare([2.0b], [2.0a])
11497 @result{}1
11498 m4_version_compare([1.1.1], [1.1.1a])
11499 @result{}-1
11500 m4_version_compare([1.2], [1.1.1a])
11501 @result{}1
11502 m4_version_compare([1.0], [1])
11503 @result{}0
11504 m4_version_compare([1.1pre], [1.1PRE])
11505 @result{}0
11506 m4_version_compare([1.1a], [1,10])
11507 @result{}-1
11508 m4_version_compare([2.61a], [2.61a-248-dc51])
11509 @result{}-1
11510 m4_version_compare([2.61b], [2.61a-248-dc51])
11511 @result{}1
11512 @end example
11513 @end defmac
11516 @node Set manipulation Macros
11517 @subsection Set manipulation in M4
11518 @cindex Set manipulation
11519 @cindex Data structure, set
11520 @cindex Unordered set manipulation
11522 Sometimes, it is necessary to track a set of data, where the order does
11523 not matter and where there are no duplicates in the set.  The following
11524 macros facilitate set manipulations.  Each set is an opaque object,
11525 which can only be accessed via these basic operations.  The underlying
11526 implementation guarantees linear scaling for set creation, which is more
11527 efficient than using the quadratic @code{m4_append_uniq}.  Both set
11528 names and values can be arbitrary strings, except for unbalanced quotes.
11529 This implementation ties up memory for removed elements until the next
11530 operation that must traverse all the elements of a set; and although
11531 that may slow down some operations until the memory for removed elements
11532 is pruned, it still guarantees linear performance.
11534 @defmac m4_set_add (@var{set}, @var{value}, @ovar{if-uniq}, @ovar{if-dup})
11535 @msindex{set_add}
11536 Adds the string @var{value} as a member of set @var{set}.  Expand
11537 @var{if-uniq} if the element was added, or @var{if-dup} if it was
11538 previously in the set.  Operates in amortized constant time, so that set
11539 creation scales linearly.
11540 @end defmac
11542 @defmac m4_set_add_all (@var{set}, @var{value}@dots{})
11543 @msindex{set_add_all}
11544 Adds each @var{value} to the set @var{set}.  This is slightly more
11545 efficient than repeatedly invoking @code{m4_set_add}.
11546 @end defmac
11548 @defmac m4_set_contains (@var{set}, @var{value}, @ovar{if-present}, @
11549  @ovar{if-absent})
11550 @msindex{set_contains}
11551 Expands @var{if-present} if the string @var{value} is a member of
11552 @var{set}, otherwise @var{if-absent}.
11554 @example
11555 m4_set_contains([a], [1], [yes], [no])
11556 @result{}no
11557 m4_set_add([a], [1], [added], [dup])
11558 @result{}added
11559 m4_set_add([a], [1], [added], [dup])
11560 @result{}dup
11561 m4_set_contains([a], [1], [yes], [no])
11562 @result{}yes
11563 m4_set_remove([a], [1], [removed], [missing])
11564 @result{}removed
11565 m4_set_contains([a], [1], [yes], [no])
11566 @result{}no
11567 m4_set_remove([a], [1], [removed], [missing])
11568 @result{}missing
11569 @end example
11570 @end defmac
11572 @defmac m4_set_contents (@var{set}, @ovar{sep})
11573 @defmacx m4_set_dump (@var{set}, @ovar{sep})
11574 @msindex{set_contents}
11575 @msindex{set_dump}
11576 Expands to a single string consisting of all the members of the set
11577 @var{set}, each separated by @var{sep}, which is not expanded.
11578 @code{m4_set_contents} leaves the elements in @var{set} but reclaims any
11579 memory occupied by removed elements, while @code{m4_set_dump} is a
11580 faster one-shot action that also deletes the set.  No provision is made
11581 for disambiguating members that contain a non-empty @var{sep} as a
11582 substring; use @code{m4_set_empty} to distinguish between an empty set
11583 and the set containing only the empty string.  The order of the output
11584 is unspecified; in the current implementation, part of the speed of
11585 @code{m4_set_dump} results from using a different output order than
11586 @code{m4_set_contents}.  These macros scale linearly in the size of the
11587 set before memory pruning, and @code{m4_set_contents([@var{set}],
11588 [@var{sep}])} is faster than
11589 @code{m4_joinall([@var{sep}]m4_set_listc([@var{set}]))}.
11591 @example
11592 m4_set_add_all([a], [1], [2], [3])
11593 @result{}
11594 m4_set_contents([a], [-])
11595 @result{}1-2-3
11596 m4_joinall([-]m4_set_listc([a]))
11597 @result{}1-2-3
11598 m4_set_dump([a], [-])
11599 @result{}3-2-1
11600 m4_set_contents([a])
11601 @result{}
11602 m4_set_add([a], [])
11603 @result{}
11604 m4_set_contents([a], [-])
11605 @result{}
11606 @end example
11607 @end defmac
11609 @defmac m4_set_delete (@var{set})
11610 @msindex{set_delete}
11611 Delete all elements and memory associated with @var{set}.  This is
11612 linear in the set size, and faster than removing one element at a time.
11613 @end defmac
11615 @defmac m4_set_difference (@var{seta}, @var{setb})
11616 @defmacx m4_set_intersection (@var{seta}, @var{setb})
11617 @defmacx m4_set_union (@var{seta}, @var{setb})
11618 @msindex{set_difference}
11619 @msindex{set_intersection}
11620 @msindex{set_union}
11621 Compute the relation between @var{seta} and @var{setb}, and output the
11622 result as a list of quoted arguments without duplicates and with a
11623 leading comma.  Set difference selects the elements in @var{seta} but
11624 not @var{setb}, intersection selects only elements in both sets, and
11625 union selects elements in either set.  These actions are linear in the
11626 sum of the set sizes.  The leading comma is necessary to distinguish
11627 between no elements and the empty string as the only element.
11629 @example
11630 m4_set_add_all([a], [1], [2], [3])
11631 @result{}
11632 m4_set_add_all([b], [3], [], [4])
11633 @result{}
11634 m4_set_difference([a], [b])
11635 @result{},1,2
11636 m4_set_difference([b], [a])
11637 @result{},,4
11638 m4_set_intersection([a], [b])
11639 @result{},3
11640 m4_set_union([a], [b])
11641 @result{},1,2,3,,4
11642 @end example
11643 @end defmac
11645 @defmac m4_set_empty (@var{set}, @ovar{if-empty}, @ovar{if-elements})
11646 @msindex{set_empty}
11647 Expand @var{if-empty} if the set @var{set} has no elements, otherwise
11648 expand @var{if-elements}.  This macro operates in constant time.  Using
11649 this macro can help disambiguate output from @code{m4_set_contents} or
11650 @code{m4_set_list}.
11651 @end defmac
11653 @defmac m4_set_foreach (@var{set}, @var{variable}, @var{action})
11654 @msindex{set_foreach}
11655 For each element in the set @var{set}, expand @var{action} with the
11656 macro @var{variable} defined as the set element.  Behavior is
11657 unspecified if @var{action} recursively lists the contents of @var{set}
11658 (although listing other sets is acceptable), or if it modifies the set
11659 in any way other than removing the element currently contained in
11660 @var{variable}.  This macro is faster than the corresponding
11661 @code{m4_foreach([@var{variable}],
11662 m4_indir([m4_dquote]m4_set_listc([@var{set}])), [@var{action}])}.
11664 @example
11665 m4_set_add_all([a]m4_for([i], [1], [5], [], [,i]))
11666 @result{}
11667 m4_set_contents([a])
11668 @result{}12345
11669 m4_set_foreach([a], [i],
11670   [m4_if(m4_eval(i&1), [0], [m4_set_remove([a], i, [i])])])
11671 @result{}24
11672 m4_set_contents([a])
11673 @result{}135
11674 @end example
11675 @end defmac
11677 @defmac m4_set_list (@var{set})
11678 @defmacx m4_set_listc (@var{set})
11679 @msindex{set_list}
11680 @msindex{set_listc}
11681 Produce a list of arguments, where each argument is a quoted element
11682 from the set @var{set}.  The variant @code{m4_set_listc} is unambiguous,
11683 by adding a leading comma if there are any set elements, whereas the
11684 variant @code{m4_set_list} cannot distinguish between an empty set and a
11685 set containing only the empty string.  These can be directly used in
11686 macros that take multiple arguments, such as @code{m4_join} or
11687 @code{m4_set_add_all}, or wrapped by @code{m4_dquote} for macros that
11688 take a quoted list, such as @code{m4_map} or @code{m4_foreach}.  Any
11689 memory occupied by removed elements is reclaimed during these macros.
11691 @example
11692 m4_set_add_all([a], [1], [2], [3])
11693 @result{}
11694 m4_set_list([a])
11695 @result{}1,2,3
11696 m4_set_list([b])
11697 @result{}
11698 m4_set_listc([b])
11699 @result{}
11700 m4_count(m4_set_list([b]))
11701 @result{}1
11702 m4_set_empty([b], [0], [m4_count(m4_set_list([b]))])
11703 @result{}0
11704 m4_set_add([b], [])
11705 @result{}
11706 m4_set_list([b])
11707 @result{}
11708 m4_set_listc([b])
11709 @result{},
11710 m4_count(m4_set_list([b]))
11711 @result{}1
11712 m4_set_empty([b], [0], [m4_count(m4_set_list([b]))])
11713 @result{}1
11714 @end example
11715 @end defmac
11717 @defmac m4_set_remove (@var{set}, @var{value}, @ovar{if-present}, @
11718  @ovar{if-absent})
11719 @msindex{set_remove}
11720 If @var{value} is an element in the set @var{set}, then remove it and
11721 expand @var{if-present}.  Otherwise expand @var{if-absent}.  This macro
11722 operates in constant time so that multiple removals will scale linearly
11723 rather than quadratically; but when used outside of
11724 @code{m4_set_foreach}, it leaves memory occupied until the set is later
11725 compacted by @code{m4_set_contents} or @code{m4_set_list}.  Several
11726 other set operations are then less efficient between the time of element
11727 removal and subsequent memory compaction, but still maintain their
11728 guaranteed scaling performance.
11729 @end defmac
11731 @defmac m4_set_size (@var{set})
11732 @msindex{set_size}
11733 Expand to the size of the set @var{set}.  This implementation operates
11734 in constant time, and is thus more efficient than
11735 @code{m4_eval(m4_count(m4_set_listc([set])) - 1)}.
11736 @end defmac
11739 @node Forbidden Patterns
11740 @subsection Forbidden Patterns
11741 @cindex Forbidden patterns
11742 @cindex Patterns, forbidden
11744 M4sugar provides a means to define suspicious patterns, patterns
11745 describing tokens which should not be found in the output.  For
11746 instance, if an Autoconf @file{configure} script includes tokens such as
11747 @samp{AC_DEFINE}, or @samp{dnl}, then most probably something went
11748 wrong (typically a macro was not evaluated because of overquotation).
11750 M4sugar forbids all the tokens matching @samp{^_?m4_} and @samp{^dnl$}.
11751 Additional layers, such as M4sh and Autoconf, add additional forbidden
11752 patterns to the list.
11754 @defmac m4_pattern_forbid (@var{pattern})
11755 @msindex{pattern_forbid}
11756 Declare that no token matching @var{pattern} must be found in the output.
11757 Comments are not checked; this can be a problem if, for instance, you
11758 have some macro left unexpanded after an @samp{#include}.  No consensus
11759 is currently found in the Autoconf community, as some people consider it
11760 should be valid to name macros in comments (which doesn't make sense to
11761 the authors of this documentation: input, such as macros, should be
11762 documented by @samp{dnl} comments; reserving @samp{#}-comments to
11763 document the output).
11764 @end defmac
11766 Of course, you might encounter exceptions to these generic rules, for
11767 instance you might have to refer to @samp{$m4_flags}.
11769 @defmac m4_pattern_allow (@var{pattern})
11770 @msindex{pattern_allow}
11771 Any token matching @var{pattern} is allowed, including if it matches an
11772 @code{m4_pattern_forbid} pattern.
11773 @end defmac
11775 @node Programming in M4sh
11776 @chapter Programming in M4sh
11778 M4sh, pronounced ``mash'', is aiming at producing portable Bourne shell
11779 scripts.  This name was coined by Lars J. Aas, who notes that,
11780 according to the Webster's Revised Unabridged Dictionary (1913):
11782 @quotation
11783 Mash \Mash\, n.  [Akin to G. meisch, maisch, meische, maische, mash,
11784 wash, and prob.@: to AS. miscian to mix.  See ``Mix''.]
11786 @enumerate 1
11787 @item
11788 A mass of mixed ingredients reduced to a soft pulpy state by beating or
11789 pressure@enddots{}
11791 @item
11792 A mixture of meal or bran and water fed to animals.
11794 @item
11795 A mess; trouble.  [Obs.] --Beau.@: & Fl.
11796 @end enumerate
11797 @end quotation
11800 For the time being, it is not mature enough to be widely used.
11802 M4sh reserves the M4 macro namespace @samp{^_AS_} for internal use, and
11803 the namespace @samp{^AS_} for M4sh macros.  It also reserves the shell
11804 and environment variable namespace @samp{^as_}, and the here-doc
11805 delimiter namespace @samp{^_AS[A-Z]} in the output file.  You should not
11806 define your own macros or output shell code that conflicts with these
11807 namespaces.
11809 @menu
11810 * Common Shell Constructs::     Portability layer for common shell constructs
11811 * Initialization Macros::       Macros to establish a sane shell environment
11812 * File Descriptor Macros::      File descriptor macros for input and output
11813 @end menu
11815 @node Common Shell Constructs
11816 @section Common Shell Constructs
11818 M4sh provides portable alternatives for some common shell constructs
11819 that unfortunately are not portable in practice.
11821 @c Deprecated, to be replaced by a better API
11822 @ignore
11823 @defmac AS_BASENAME (@var{file-name})
11824 @asindex{BASENAME}
11825 Output the non-directory portion of @var{file-name}.  For example,
11826 if @code{$file} is @samp{/one/two/three}, the command
11827 @code{base=`AS_BASENAME(["$file"])`} sets @code{base} to @samp{three}.
11828 @end defmac
11829 @end ignore
11831 @defmac AS_CASE (@var{word}, @ovar{pattern1}, @ovar{if-matched1}, @
11832   @dots{}, @ovar{default})
11833 @asindex{CASE}
11834 Expand into a shell @samp{case} statement, where @var{word} is matched
11835 against one or more patterns.  @var{if-matched} is run if the
11836 corresponding pattern matched @var{word}, else @var{default} is run.
11837 @end defmac
11839 @c Deprecated, to be replaced by a better API
11840 @ignore
11841 @defmac AS_DIRNAME (@var{file-name})
11842 @asindex{DIRNAME}
11843 Output the directory portion of @var{file-name}.  For example,
11844 if @code{$file} is @samp{/one/two/three}, the command
11845 @code{dir=`AS_DIRNAME(["$file"])`} sets @code{dir} to @samp{/one/two}.
11846 @end defmac
11847 @end ignore
11849 @defmac AS_IF (@var{test1}, @ovar{run-if-true1}, @dots{}, @ovar{run-if-false})
11850 @asindex{IF}
11851 Run shell code @var{test1}.  If @var{test1} exits with a zero status then
11852 run shell code @var{run-if-true1}, else examine further tests.  If no test
11853 exits with a zero status, run shell code @var{run-if-false}, with
11854 simplifications if either @var{run-if-true1} or @var{run-if-false1}
11855 is empty.  For example,
11857 @example
11858 AS_IF([test "$foo" = yes], [HANDLE_FOO([yes])],
11859       [test "$foo" != no], [HANDLE_FOO([maybe])],
11860       [echo foo not specified])
11861 @end example
11863 @noindent
11864 ensures any required macros of @code{HANDLE_FOO}
11865 are expanded before the first test.
11866 @end defmac
11868 @defmac AS_MKDIR_P (@var{file-name})
11869 @asindex{MKDIR_P}
11870 Make the directory @var{file-name}, including intervening directories
11871 as necessary.  This is equivalent to @samp{mkdir -p -- @var{file-name}},
11872 except that it is portable to older versions of @command{mkdir} that
11873 lack support for the @option{-p} option or for the @option{--}
11874 delimiter.  Also, @code{AS_MKDIR_P}
11875 succeeds if @var{file-name} is a symbolic link to an existing directory,
11876 even though Posix is unclear whether @samp{mkdir -p} should
11877 succeed in that case.  If creation of @var{file-name} fails, exit the
11878 script.
11880 Also see the @code{AC_PROG_MKDIR_P} macro (@pxref{Particular Programs}).
11881 @end defmac
11883 @defmac AS_TR_CPP (@var{expression})
11884 @asindex{TR_CPP}
11885 Transform @var{expression} into a valid right-hand side for a C @code{#define}.
11886 For example:
11888 @example
11889 # This outputs "#define HAVE_CHAR_P 1".
11890 type="char *"
11891 echo "#define AS_TR_CPP([HAVE_$type]) 1"
11892 @end example
11893 @end defmac
11895 @defmac AS_TR_SH (@var{expression})
11896 @asindex{TR_SH}
11897 Transform @var{expression} into a valid shell variable name.  For example:
11899 @example
11900 # This outputs "Have it!".
11901 header="sys/some file.h"
11902 AS_TR_SH([HAVE_$header])=yes
11903 if test "$HAVE_sys_some_file_h" = yes; then echo "Have it!"; fi
11904 @end example
11905 @end defmac
11907 @defmac AS_SET_CATFILE (@var{var}, @var{dir}, @var{file})
11908 @asindex{SET_CATFILE}
11909 Set the shell variable @var{var} to @var{dir}/@var{file}, but
11910 optimizing the common cases (@var{dir} or @var{file} is @samp{.},
11911 @var{file} is absolute, etc.).
11912 @end defmac
11914 @defmac AS_VERSION_COMPARE (@var{version-1}, @var{version-2}, @
11915   @ovar{action-if-less}, @ovar{action-if-equal}, @ovar{action-if-greater})
11916 @asindex{VERSION_COMPARE}
11917 Compare two strings @var{version-1} and @var{version-2}, possibly
11918 containing shell variables, as version strings, and expand
11919 @var{action-if-less}, @var{action-if-equal}, or @var{action-if-greater}
11920 depending upon the result.
11921 The algorithm to compare is similar to the one used by strverscmp in
11922 glibc (@pxref{String/Array Comparison, , String/Array Comparison, libc,
11923 The @acronym{GNU} C Library}).
11924 @end defmac
11926 @node Initialization Macros
11927 @section Initialization Macros
11929 @defmac AS_BOURNE_COMPATIBLE
11930 @asindex{BOURNE_COMPATIBLE}
11931 Set up the shell to be more compatible with the Bourne shell as
11932 standardized by Posix, if possible.  This may involve setting
11933 environment variables, or setting options, or similar
11934 implementation-specific actions.  This macro is deprecated, since
11935 @code{AS_INIT} already invokes it.
11936 @end defmac
11938 @defmac AS_INIT
11939 @asindex{INIT}
11940 Initialize the M4sh environment.  This macro calls @code{m4_init}, then
11941 outputs the @code{#! /bin/sh} line, a notice about where the output was
11942 generated from, and code to sanitize the environment for the rest of the
11943 script.  Finally, it changes the current diversion to @code{BODY}.
11944 @end defmac
11946 @defmac AS_SHELL_SANITIZE
11947 @asindex{SHELL_SANITIZE}
11948 Initialize the shell suitably for @command{configure} scripts.  This has
11949 the effect of @code{AS_BOURNE_COMPATIBLE}, and sets some other
11950 environment variables for predictable results from configuration tests.
11951 For example, it sets @env{LC_ALL} to change to the default C locale.
11952 @xref{Special Shell Variables}.  This macro is deprecated, since
11953 @code{AS_INIT} already invokes it.
11954 @end defmac
11957 @node File Descriptor Macros
11958 @section File Descriptor Macros
11959 @cindex input
11960 @cindex standard input
11961 @cindex file descriptors
11962 @cindex descriptors
11963 @cindex low-level output
11964 @cindex output, low-level
11966 The following macros define file descriptors used to output messages
11967 (or input values) from @file{configure} scripts.
11968 For example:
11970 @example
11971 echo "$wombats found" >&AS_MESSAGE_LOG_FD
11972 echo 'Enter desired kangaroo count:' >&AS_MESSAGE_FD
11973 read kangaroos <&AS_ORIGINAL_STDIN_FD`
11974 @end example
11976 @noindent
11977 However doing so is seldom needed, because Autoconf provides higher
11978 level macros as described below.
11980 @defmac AS_MESSAGE_FD
11981 @asindex{MESSAGE_FD}
11982 The file descriptor for @samp{checking for...}  messages and results.
11983 Normally this directs messages to the standard output, however when
11984 @command{configure} is run with the @option{-q} option, messages sent to
11985 @code{AS_MESSAGE_FD} are discarded.
11987 If you want to display some messages, consider using one of the printing
11988 macros (@pxref{Printing Messages}) instead.  Copies of messages output
11989 via these macros are also recorded in @file{config.log}.
11990 @end defmac
11992 @defmac AS_MESSAGE_LOG_FD
11993 @asindex{MESSAGE_LOG_FD}
11995 The file descriptor for messages logged to @file{config.log}.  Macros
11996 that run tools, like @code{AC_COMPILE_IFELSE} (@pxref{Running the
11997 Compiler}), redirect all output to this descriptor.  You may want to do
11998 so if you develop such a low-level macro.
11999 @end defmac
12001 @defmac AS_ORIGINAL_STDIN_FD
12002 @asindex{ORIGINAL_STDIN_FD}
12003 The file descriptor for the original standard input.
12005 When @command{configure} runs, it may accidentally execute an
12006 interactive command that has the same name as the non-interactive meant
12007 to be used or checked.  If the standard input was the terminal, such
12008 interactive programs would cause @command{configure} to stop, pending
12009 some user input.  Therefore @command{configure} redirects its standard
12010 input from @file{/dev/null} during its initialization.  This is not
12011 normally a problem, since @command{configure} normally does not need
12012 user input.
12014 In the extreme case where your @file{configure} script really needs to
12015 obtain some values from the original standard input, you can read them
12016 explicitly from @code{AS_ORIGINAL_STDIN_FD}.
12017 @end defmac
12020 @c =================================================== Writing Autoconf Macros.
12022 @node Writing Autoconf Macros
12023 @chapter Writing Autoconf Macros
12025 When you write a feature test that could be applicable to more than one
12026 software package, the best thing to do is encapsulate it in a new macro.
12027 Here are some instructions and guidelines for writing Autoconf macros.
12029 @menu
12030 * Macro Definitions::           Basic format of an Autoconf macro
12031 * Macro Names::                 What to call your new macros
12032 * Reporting Messages::          Notifying @command{autoconf} users
12033 * Dependencies Between Macros::  What to do when macros depend on other macros
12034 * Obsoleting Macros::           Warning about old ways of doing things
12035 * Coding Style::                Writing Autoconf macros @`a la Autoconf
12036 @end menu
12038 @node Macro Definitions
12039 @section Macro Definitions
12041 @acindex{DEFUN}
12042 Autoconf macros are defined using the @code{AC_DEFUN} macro, which is
12043 similar to the M4 builtin @code{m4_define} macro.  In addition to
12044 defining a macro, @code{AC_DEFUN} adds to it some code that is used to
12045 constrain the order in which macros are called (@pxref{Prerequisite
12046 Macros}).
12048 An Autoconf macro definition looks like this:
12050 @example
12051 AC_DEFUN(@var{macro-name}, @var{macro-body})
12052 @end example
12054 You can refer to any arguments passed to the macro as @samp{$1},
12055 @samp{$2}, etc.  @xref{Definitions, , How to define new macros, m4.info,
12056 @acronym{GNU} M4}, for more complete information on writing M4 macros.
12058 Be sure to properly quote both the @var{macro-body} @emph{and} the
12059 @var{macro-name} to avoid any problems if the macro happens to have
12060 been previously defined.
12062 Each macro should have a header comment that gives its prototype, and a
12063 brief description.  When arguments have default values, display them in
12064 the prototype.  For example:
12066 @example
12067 # AC_MSG_ERROR(ERROR, [EXIT-STATUS = 1])
12068 # --------------------------------------
12069 m4_define([AC_MSG_ERROR],
12070   [@{ AS_MESSAGE([error: $1], [2])
12071      exit m4_default([$2], [1]); @}])
12072 @end example
12074 Comments about the macro should be left in the header comment.  Most
12075 other comments make their way into @file{configure}, so just keep
12076 using @samp{#} to introduce comments.
12078 @cindex @code{dnl}
12079 If you have some special comments about pure M4 code, comments
12080 that make no sense in @file{configure} and in the header comment, then
12081 use the builtin @code{dnl}: it causes M4 to discard the text
12082 through the next newline.
12084 Keep in mind that @code{dnl} is rarely needed to introduce comments;
12085 @code{dnl} is more useful to get rid of the newlines following macros
12086 that produce no output, such as @code{AC_REQUIRE}.
12089 @node Macro Names
12090 @section Macro Names
12092 All of the public Autoconf macros have all-uppercase names in the
12093 namespace @samp{^AC_} to prevent them from accidentally conflicting with
12094 other text; Autoconf also reserves the namespace @samp{^_AC_} for
12095 internal macros.  All shell variables that they use for internal
12096 purposes have mostly-lowercase names starting with @samp{ac_}.  Autoconf
12097 also uses here-doc delimiters in the namespace @samp{^_AC[A-Z]}.  During
12098 @command{configure}, files produced by Autoconf make heavy use of the
12099 file system namespace @samp{^conf}.
12101 Since Autoconf is built on top of M4sugar (@pxref{Programming in
12102 M4sugar}) and M4sh (@pxref{Programming in M4sh}), you must also be aware
12103 of those namespaces (@samp{^_?\(m4\|AS\)_}).  And since
12104 @file{configure.ac} is also designed to be scanned by Autoheader,
12105 Autoscan, Autoupdate, and Automake, you should be aware of the
12106 @samp{^_?A[HNUM]_} namespaces.  In general, you @emph{should not use}
12107 the namespace of a package that does not own the macro or shell code you
12108 are writing.
12110 To ensure that your macros don't conflict with present or future
12111 Autoconf macros, you should prefix your own macro names and any shell
12112 variables they use with some other sequence.  Possibilities include your
12113 initials, or an abbreviation for the name of your organization or
12114 software package.  Historically, people have not always followed the
12115 rule of using a namespace appropriate for their package, and this has
12116 made it difficult for determining the origin of a macro (and where to
12117 report bugs about that macro), as well as difficult for the true
12118 namespace owner to add new macros without interference from pre-existing
12119 uses of third-party macros.  Perhaps the best example of this confusion
12120 is the @code{AM_GNU_GETTEXT} macro, which belongs, not to Automake, but
12121 to Gettext.
12123 Most of the Autoconf macros' names follow a structured naming convention
12124 that indicates the kind of feature check by the name.  The macro names
12125 consist of several words, separated by underscores, going from most
12126 general to most specific.  The names of their cache variables use the
12127 same convention (@pxref{Cache Variable Names}, for more information on
12128 them).
12130 The first word of the name after the namepace initials (such as
12131 @samp{AC_}) usually tells the category
12132 of the feature being tested.  Here are the categories used in Autoconf for
12133 specific test macros, the kind of macro that you are more likely to
12134 write.  They are also used for cache variables, in all-lowercase.  Use
12135 them where applicable; where they're not, invent your own categories.
12137 @table @code
12138 @item C
12139 C language builtin features.
12140 @item DECL
12141 Declarations of C variables in header files.
12142 @item FUNC
12143 Functions in libraries.
12144 @item GROUP
12145 Posix group owners of files.
12146 @item HEADER
12147 Header files.
12148 @item LIB
12149 C libraries.
12150 @item PROG
12151 The base names of programs.
12152 @item MEMBER
12153 Members of aggregates.
12154 @item SYS
12155 Operating system features.
12156 @item TYPE
12157 C builtin or declared types.
12158 @item VAR
12159 C variables in libraries.
12160 @end table
12162 After the category comes the name of the particular feature being
12163 tested.  Any further words in the macro name indicate particular aspects
12164 of the feature.  For example, @code{AC_PROG_CC_STDC} checks whether the
12165 C compiler supports @acronym{ISO} Standard C.
12167 An internal macro should have a name that starts with an underscore;
12168 Autoconf internals should therefore start with @samp{_AC_}.
12169 Additionally, a macro that is an internal subroutine of another macro
12170 should have a name that starts with an underscore and the name of that
12171 other macro, followed by one or more words saying what the internal
12172 macro does.  For example, @code{AC_PATH_X} has internal macros
12173 @code{_AC_PATH_X_XMKMF} and @code{_AC_PATH_X_DIRECT}.
12175 @node Reporting Messages
12176 @section Reporting Messages
12177 @cindex Messages, from @command{autoconf}
12179 When macros statically diagnose abnormal situations, benign or fatal, it
12180 is possible to make @command{autoconf} detect the problem, and refuse to
12181 create @file{configure} in the case of an error.  The macros in this
12182 section are considered obsolescent, and new code should use M4sugar
12183 macros for this purpose, see @ref{Diagnostic Macros}.
12185 On the other hand, it is possible to want to detect errors when
12186 @command{configure} is run, which are dependent on the environment of
12187 the user rather than the maintainer.  For dynamic diagnostics, see
12188 @ref{Printing Messages}.
12190 @defmac AC_DIAGNOSE (@var{category}, @var{message})
12191 @acindex{DIAGNOSE}
12192 Report @var{message} as a warning (or as an error if requested by the
12193 user) if warnings of the @var{category} are turned on.  This macro is
12194 obsolescent; you are encouraged to use:
12195 @example
12196 m4_warn([@var{category}], [@var{message}])
12197 @end example
12198 @noindent
12199 instead.  @xref{m4_warn}, for more details, including valid
12200 @var{category} names.
12201 @end defmac
12203 @defmac AC_WARNING (@var{message})
12204 @acindex{WARNING}
12205 Report @var{message} as a syntax warning.  This macro is obsolescent;
12206 you are encouraged to use:
12207 @example
12208 m4_warn([syntax], [@var{message}])
12209 @end example
12210 @noindent
12211 instead.  @xref{m4_warn}, for more details, as well as better
12212 finer-grained categories of warnings (not all problems have to do with
12213 syntax).
12214 @end defmac
12216 @defmac AC_FATAL (@var{message})
12217 @acindex{FATAL}
12218 Report a severe error @var{message}, and have @command{autoconf} die.
12219 This macro is obsolescent; you are encouraged to use:
12220 @example
12221 m4_fatal([@var{message}])
12222 @end example
12223 @noindent
12224 instead.  @xref{m4_fatal}, for more details.
12225 @end defmac
12227 When the user runs @samp{autoconf -W error}, warnings from
12228 @code{m4_warn} (including those issued through @code{AC_DIAGNOSE} and
12229 @code{AC_WARNING}) are reported as errors, see @ref{autoconf Invocation}.
12231 @node Dependencies Between Macros
12232 @section Dependencies Between Macros
12233 @cindex Dependencies between macros
12235 Some Autoconf macros depend on other macros having been called first in
12236 order to work correctly.  Autoconf provides a way to ensure that certain
12237 macros are called if needed and a way to warn the user if macros are
12238 called in an order that might cause incorrect operation.
12240 @menu
12241 * Prerequisite Macros::         Ensuring required information
12242 * Suggested Ordering::          Warning about possible ordering problems
12243 * One-Shot Macros::             Ensuring a macro is called only once
12244 @end menu
12246 @node Prerequisite Macros
12247 @subsection Prerequisite Macros
12248 @cindex Prerequisite macros
12249 @cindex Macros, prerequisites
12251 A macro that you write might need to use values that have previously
12252 been computed by other macros.  For example, @code{AC_DECL_YYTEXT}
12253 examines the output of @code{flex} or @code{lex}, so it depends on
12254 @code{AC_PROG_LEX} having been called first to set the shell variable
12255 @code{LEX}.
12257 Rather than forcing the user of the macros to keep track of the
12258 dependencies between them, you can use the @code{AC_REQUIRE} macro to do
12259 it automatically.  @code{AC_REQUIRE} can ensure that a macro is only
12260 called if it is needed, and only called once.
12262 @defmac AC_REQUIRE (@var{macro-name})
12263 @acindex{REQUIRE}
12264 If the M4 macro @var{macro-name} has not already been called, call it
12265 (without any arguments).  Make sure to quote @var{macro-name} with
12266 square brackets.  @var{macro-name} must have been defined using
12267 @code{AC_DEFUN} or else contain a call to @code{AC_PROVIDE} to indicate
12268 that it has been called.
12270 @code{AC_REQUIRE} must be used inside a macro defined by @code{AC_DEFUN}; it
12271 must not be called from the top level.
12272 @end defmac
12274 @code{AC_REQUIRE} is often misunderstood.  It really implements
12275 dependencies between macros in the sense that if one macro depends upon
12276 another, the latter is expanded @emph{before} the body of the
12277 former.  To be more precise, the required macro is expanded before
12278 the outermost defined macro in the current expansion stack.
12279 In particular, @samp{AC_REQUIRE([FOO])} is not replaced with the body of
12280 @code{FOO}.  For instance, this definition of macros:
12282 @example
12283 @group
12284 AC_DEFUN([TRAVOLTA],
12285 [test "$body_temperature_in_celsius" -gt "38" &&
12286   dance_floor=occupied])
12287 AC_DEFUN([NEWTON_JOHN],
12288 [test "$hair_style" = "curly" &&
12289   dance_floor=occupied])
12290 @end group
12292 @group
12293 AC_DEFUN([RESERVE_DANCE_FLOOR],
12294 [if date | grep '^Sat.*pm' >/dev/null 2>&1; then
12295   AC_REQUIRE([TRAVOLTA])
12296   AC_REQUIRE([NEWTON_JOHN])
12297 fi])
12298 @end group
12299 @end example
12301 @noindent
12302 with this @file{configure.ac}
12304 @example
12305 AC_INIT([Dance Manager], [1.0], [bug-dance@@example.org])
12306 RESERVE_DANCE_FLOOR
12307 if test "$dance_floor" = occupied; then
12308   AC_MSG_ERROR([cannot pick up here, let's move])
12310 @end example
12312 @noindent
12313 does not leave you with a better chance to meet a kindred soul at
12314 other times than Saturday night since it expands into:
12316 @example
12317 @group
12318 test "$body_temperature_in_Celsius" -gt "38" &&
12319   dance_floor=occupied
12320 test "$hair_style" = "curly" &&
12321   dance_floor=occupied
12323 if date | grep '^Sat.*pm' >/dev/null 2>&1; then
12327 @end group
12328 @end example
12330 This behavior was chosen on purpose: (i) it prevents messages in
12331 required macros from interrupting the messages in the requiring macros;
12332 (ii) it avoids bad surprises when shell conditionals are used, as in:
12334 @example
12335 @group
12336 if @dots{}; then
12337   AC_REQUIRE([SOME_CHECK])
12339 @dots{}
12340 SOME_CHECK
12341 @end group
12342 @end example
12344 The helper macros @code{AS_IF} and @code{AS_CASE} may be used to
12345 enforce expansion of required macros outside of shell conditional
12346 constructs.  You are furthermore encouraged to put all @code{AC_REQUIRE} calls
12347 at the beginning of a macro.  You can use @code{dnl} to avoid the empty
12348 lines they leave.
12350 @node Suggested Ordering
12351 @subsection Suggested Ordering
12352 @cindex Macros, ordering
12353 @cindex Ordering macros
12355 Some macros should be run before another macro if both are called, but
12356 neither @emph{requires} that the other be called.  For example, a macro
12357 that changes the behavior of the C compiler should be called before any
12358 macros that run the C compiler.  Many of these dependencies are noted in
12359 the documentation.
12361 Autoconf provides the @code{AC_BEFORE} macro to warn users when macros
12362 with this kind of dependency appear out of order in a
12363 @file{configure.ac} file.  The warning occurs when creating
12364 @command{configure} from @file{configure.ac}, not when running
12365 @command{configure}.
12367 For example, @code{AC_PROG_CPP} checks whether the C compiler
12368 can run the C preprocessor when given the @option{-E} option.  It should
12369 therefore be called after any macros that change which C compiler is
12370 being used, such as @code{AC_PROG_CC}.  So @code{AC_PROG_CC} contains:
12372 @example
12373 AC_BEFORE([$0], [AC_PROG_CPP])dnl
12374 @end example
12376 @noindent
12377 This warns the user if a call to @code{AC_PROG_CPP} has already occurred
12378 when @code{AC_PROG_CC} is called.
12380 @defmac AC_BEFORE (@var{this-macro-name}, @var{called-macro-name})
12381 @acindex{BEFORE}
12382 Make M4 print a warning message to the standard error output if
12383 @var{called-macro-name} has already been called.  @var{this-macro-name}
12384 should be the name of the macro that is calling @code{AC_BEFORE}.  The
12385 macro @var{called-macro-name} must have been defined using
12386 @code{AC_DEFUN} or else contain a call to @code{AC_PROVIDE} to indicate
12387 that it has been called.
12388 @end defmac
12390 @node One-Shot Macros
12391 @subsection One-Shot Macros
12392 @cindex One-shot macros
12393 @cindex Macros, called once
12395 Some macros should be called only once, either because calling them
12396 multiple time is unsafe, or because it is bad style.  For instance
12397 Autoconf ensures that @code{AC_CANONICAL_BUILD} and cousins
12398 (@pxref{Canonicalizing}) are evaluated only once, because it makes no
12399 sense to run these expensive checks more than once.  Such one-shot
12400 macros can be defined using @code{AC_DEFUN_ONCE}.
12402 @defmac AC_DEFUN_ONCE (@var{macro-name}, @var{macro-body})
12403 @acindex{DEFUN_ONCE}
12405 Declare macro @var{macro-name} like @code{AC_DEFUN} would (@pxref{Macro
12406 Definitions}), and emit a warning any time the macro is called more than
12407 once.
12408 @end defmac
12410 Obviously it is not sensible to evaluate a macro defined by
12411 @code{AC_DEFUN_ONCE} in a macro defined by @code{AC_DEFUN}.
12412 Most of the time you want to use @code{AC_REQUIRE} (@pxref{Prerequisite
12413 Macros}).
12415 @node Obsoleting Macros
12416 @section Obsoleting Macros
12417 @cindex Obsoleting macros
12418 @cindex Macros, obsoleting
12420 Configuration and portability technology has evolved over the years.
12421 Often better ways of solving a particular problem are developed, or
12422 ad-hoc approaches are systematized.  This process has occurred in many
12423 parts of Autoconf.  One result is that some of the macros are now
12424 considered @dfn{obsolete}; they still work, but are no longer considered
12425 the best thing to do, hence they should be replaced with more modern
12426 macros.  Ideally, @command{autoupdate} should replace the old macro calls
12427 with their modern implementation.
12429 Autoconf provides a simple means to obsolete a macro.
12431 @anchor{AU_DEFUN}
12432 @defmac AU_DEFUN (@var{old-macro}, @var{implementation}, @ovar{message})
12433 @auindex{DEFUN}
12434 Define @var{old-macro} as @var{implementation}.  The only difference
12435 with @code{AC_DEFUN} is that the user is warned that
12436 @var{old-macro} is now obsolete.
12438 If she then uses @command{autoupdate}, the call to @var{old-macro} is
12439 replaced by the modern @var{implementation}.  @var{message} should
12440 include information on what to do after running @command{autoupdate};
12441 @command{autoupdate} prints it as a warning, and includes it
12442 in the updated @file{configure.ac} file.
12444 The details of this macro are hairy: if @command{autoconf} encounters an
12445 @code{AU_DEFUN}ed macro, all macros inside its second argument are expanded
12446 as usual.  However, when @command{autoupdate} is run, only M4 and M4sugar
12447 macros are expanded here, while all other macros are disabled and
12448 appear literally in the updated @file{configure.ac}.
12449 @end defmac
12451 @defmac AU_ALIAS (@var{old-name}, @var{new-name})
12452 @auindex{ALIAS}
12453 Used if the @var{old-name} is to be replaced by a call to @var{new-macro}
12454 with the same parameters.  This happens for example if the macro was renamed.
12455 @end defmac
12457 @node Coding Style
12458 @section Coding Style
12459 @cindex Coding style
12461 The Autoconf macros follow a strict coding style.  You are encouraged to
12462 follow this style, especially if you intend to distribute your macro,
12463 either by contributing it to Autoconf itself, or via other means.
12465 The first requirement is to pay great attention to the quotation.  For
12466 more details, see @ref{Autoconf Language}, and @ref{M4 Quotation}.
12468 Do not try to invent new interfaces.  It is likely that there is a macro
12469 in Autoconf that resembles the macro you are defining: try to stick to
12470 this existing interface (order of arguments, default values, etc.).  We
12471 @emph{are} conscious that some of these interfaces are not perfect;
12472 nevertheless, when harmless, homogeneity should be preferred over
12473 creativity.
12475 Be careful about clashes both between M4 symbols and between shell
12476 variables.
12478 If you stick to the suggested M4 naming scheme (@pxref{Macro Names}),
12479 you are unlikely to generate conflicts.  Nevertheless, when you need to
12480 set a special value, @emph{avoid using a regular macro name}; rather,
12481 use an ``impossible'' name.  For instance, up to version 2.13, the macro
12482 @code{AC_SUBST} used to remember what @var{symbol} macros were already defined
12483 by setting @code{AC_SUBST_@var{symbol}}, which is a regular macro name.
12484 But since there is a macro named @code{AC_SUBST_FILE}, it was just
12485 impossible to @samp{AC_SUBST(FILE)}!  In this case,
12486 @code{AC_SUBST(@var{symbol})} or @code{_AC_SUBST(@var{symbol})} should
12487 have been used (yes, with the parentheses).
12488 @c or better yet, high-level macros such as @code{m4_expand_once}
12490 No Autoconf macro should ever enter the user-variable name space; i.e.,
12491 except for the variables that are the actual result of running the
12492 macro, all shell variables should start with @code{ac_}.  In
12493 addition, small macros or any macro that is likely to be embedded in
12494 other macros should be careful not to use obvious names.
12496 @cindex @code{dnl}
12497 Do not use @code{dnl} to introduce comments: most of the comments you
12498 are likely to write are either header comments which are not output
12499 anyway, or comments that should make their way into @file{configure}.
12500 There are exceptional cases where you do want to comment special M4
12501 constructs, in which case @code{dnl} is right, but keep in mind that it
12502 is unlikely.
12504 M4 ignores the leading blanks and newlines before each argument.
12505 Use this feature to
12506 indent in such a way that arguments are (more or less) aligned with the
12507 opening parenthesis of the macro being called.  For instance, instead of
12509 @example
12510 AC_CACHE_CHECK(for EMX OS/2 environment,
12511 ac_cv_emxos2,
12512 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM(, [return __EMX__;])],
12513 [ac_cv_emxos2=yes], [ac_cv_emxos2=no])])
12514 @end example
12516 @noindent
12517 write
12519 @example
12520 AC_CACHE_CHECK([for EMX OS/2 environment], [ac_cv_emxos2],
12521 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([], [return __EMX__;])],
12522                    [ac_cv_emxos2=yes],
12523                    [ac_cv_emxos2=no])])
12524 @end example
12526 @noindent
12527 or even
12529 @example
12530 AC_CACHE_CHECK([for EMX OS/2 environment],
12531                [ac_cv_emxos2],
12532                [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([],
12533                                                    [return __EMX__;])],
12534                                   [ac_cv_emxos2=yes],
12535                                   [ac_cv_emxos2=no])])
12536 @end example
12538 When using @code{AC_RUN_IFELSE} or any macro that cannot work when
12539 cross-compiling, provide a pessimistic value (typically @samp{no}).
12541 Feel free to use various tricks to prevent auxiliary tools, such as
12542 syntax-highlighting editors, from behaving improperly.  For instance,
12543 instead of:
12545 @example
12546 m4_bpatsubst([$1], [$"])
12547 @end example
12549 @noindent
12552 @example
12553 m4_bpatsubst([$1], [$""])
12554 @end example
12556 @noindent
12557 so that Emacsen do not open an endless ``string'' at the first quote.
12558 For the same reasons, avoid:
12560 @example
12561 test $[#] != 0
12562 @end example
12564 @noindent
12565 and use:
12567 @example
12568 test $[@@%:@@] != 0
12569 @end example
12571 @noindent
12572 Otherwise, the closing bracket would be hidden inside a @samp{#}-comment,
12573 breaking the bracket-matching highlighting from Emacsen.  Note the
12574 preferred style to escape from M4: @samp{$[1]}, @samp{$[@@]}, etc.  Do
12575 not escape when it is unnecessary.  Common examples of useless quotation
12576 are @samp{[$]$1} (write @samp{$$1}), @samp{[$]var} (use @samp{$var}),
12577 etc.  If you add portability issues to the picture, you'll prefer
12578 @samp{$@{1+"$[@@]"@}} to @samp{"[$]@@"}, and you'll prefer do something
12579 better than hacking Autoconf @code{:-)}.
12581 When using @command{sed}, don't use @option{-e} except for indenting
12582 purposes.  With the @code{s} and @code{y} commands, the preferred
12583 separator is @samp{/} unless @samp{/} itself might appear in the pattern
12584 or replacement, in which case you should use @samp{|}, or optionally
12585 @samp{,} if you know the pattern and replacement cannot contain a file
12586 name.  If none of these characters will do, choose a printable character
12587 that cannot appear in the pattern or replacement.  Characters from the
12588 set @samp{"#$&'()*;<=>?`|~} are good choices if the pattern or
12589 replacement might contain a file name, since they have special meaning
12590 to the shell and are less likely to occur in file names.
12592 @xref{Macro Definitions}, for details on how to define a macro.  If a
12593 macro doesn't use @code{AC_REQUIRE}, is expected to never be the object
12594 of an @code{AC_REQUIRE} directive, and macros required by other macros
12595 inside arguments do not need to be expanded before this macro, then
12596 use @code{m4_define}.  In case of doubt, use @code{AC_DEFUN}.
12597 All the @code{AC_REQUIRE} statements should be at the beginning of the
12598 macro, and each statement should be followed by @code{dnl}.
12600 You should not rely on the number of arguments: instead of checking
12601 whether an argument is missing, test that it is not empty.  It provides
12602 both a simpler and a more predictable interface to the user, and saves
12603 room for further arguments.
12605 Unless the macro is short, try to leave the closing @samp{])} at the
12606 beginning of a line, followed by a comment that repeats the name of the
12607 macro being defined.  This introduces an additional newline in
12608 @command{configure}; normally, that is not a problem, but if you want to
12609 remove it you can use @samp{[]dnl} on the last line.  You can similarly
12610 use @samp{[]dnl} after a macro call to remove its newline.  @samp{[]dnl}
12611 is recommended instead of @samp{dnl} to ensure that M4 does not
12612 interpret the @samp{dnl} as being attached to the preceding text or
12613 macro output.  For example, instead of:
12615 @example
12616 AC_DEFUN([AC_PATH_X],
12617 [AC_MSG_CHECKING([for X])
12618 AC_REQUIRE_CPP()
12619 @r{# @dots{}omitted@dots{}}
12620   AC_MSG_RESULT([libraries $x_libraries, headers $x_includes])
12621 fi])
12622 @end example
12624 @noindent
12625 you would write:
12627 @example
12628 AC_DEFUN([AC_PATH_X],
12629 [AC_REQUIRE_CPP()[]dnl
12630 AC_MSG_CHECKING([for X])
12631 @r{# @dots{}omitted@dots{}}
12632   AC_MSG_RESULT([libraries $x_libraries, headers $x_includes])
12633 fi[]dnl
12634 ])# AC_PATH_X
12635 @end example
12637 If the macro is long, try to split it into logical chunks.  Typically,
12638 macros that check for a bug in a function and prepare its
12639 @code{AC_LIBOBJ} replacement should have an auxiliary macro to perform
12640 this setup.  Do not hesitate to introduce auxiliary macros to factor
12641 your code.
12643 In order to highlight the recommended coding style, here is a macro
12644 written the old way:
12646 @example
12647 dnl Check for EMX on OS/2.
12648 dnl _AC_EMXOS2
12649 AC_DEFUN(_AC_EMXOS2,
12650 [AC_CACHE_CHECK(for EMX OS/2 environment, ac_cv_emxos2,
12651 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM(, return __EMX__;)],
12652 ac_cv_emxos2=yes, ac_cv_emxos2=no)])
12653 test "$ac_cv_emxos2" = yes && EMXOS2=yes])
12654 @end example
12656 @noindent
12657 and the new way:
12659 @example
12660 # _AC_EMXOS2
12661 # ----------
12662 # Check for EMX on OS/2.
12663 m4_define([_AC_EMXOS2],
12664 [AC_CACHE_CHECK([for EMX OS/2 environment], [ac_cv_emxos2],
12665 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([], [return __EMX__;])],
12666                    [ac_cv_emxos2=yes],
12667                    [ac_cv_emxos2=no])])
12668 test "$ac_cv_emxos2" = yes && EMXOS2=yes[]dnl
12669 ])# _AC_EMXOS2
12670 @end example
12675 @c ============================================= Portable Shell Programming
12677 @node Portable Shell
12678 @chapter Portable Shell Programming
12679 @cindex Portable shell programming
12681 When writing your own checks, there are some shell-script programming
12682 techniques you should avoid in order to make your code portable.  The
12683 Bourne shell and upward-compatible shells like the Korn shell and Bash
12684 have evolved over the years, but to prevent trouble, do not take
12685 advantage of features that were added after Unix version 7, circa
12686 1977 (@pxref{Systemology}).
12688 You should not use aliases, negated character classes, or other features
12689 that are not found in all Bourne-compatible shells; restrict yourself
12690 to the lowest common denominator.  Even @code{unset} is not supported
12691 by all shells!
12693 Shell functions are considered portable nowadays.  However, some pitfalls
12694 have to be avoided for portable use of shell functions (@pxref{Shell
12695 Functions}).
12697 Some ancient systems have quite
12698 small limits on the length of the @samp{#!} line; for instance, 32
12699 bytes (not including the newline) on SunOS 4.
12700 A few ancient 4.2@acronym{BSD} based systems (such as Dynix circa 1984)
12701 required a single space between the @samp{#!} and the @samp{/}.
12702 However, these ancient systems are no longer of practical concern.
12704 The set of external programs you should run in a @command{configure} script
12705 is fairly small.  @xref{Utilities in Makefiles, , Utilities in
12706 Makefiles, standards, @acronym{GNU} Coding Standards}, for the list.  This
12707 restriction allows users to start out with a fairly small set of
12708 programs and build the rest, avoiding too many interdependencies between
12709 packages.
12711 Some of these external utilities have a portable subset of features; see
12712 @ref{Limitations of Usual Tools}.
12714 There are other sources of documentation about shells.  The
12715 specification for the Posix
12716 @uref{http://@/www.opengroup.org/@/susv3/@/utilities/@/xcu_chap02@/.html, Shell
12717 Command Language}, though more generous than the restrictive shell
12718 subset described above, is fairly portable nowadays.  Also please see
12719 @uref{http://@/www.faqs.org/@/faqs/@/unix-faq/@/shell/, the Shell FAQs}.
12721 @menu
12722 * Shellology::                  A zoology of shells
12723 * Here-Documents::              Quirks and tricks
12724 * File Descriptors::            FDs and redirections
12725 * File System Conventions::     File names
12726 * Shell Pattern Matching::      Pattern matching
12727 * Shell Substitutions::         Variable and command expansions
12728 * Assignments::                 Varying side effects of assignments
12729 * Parentheses::                 Parentheses in shell scripts
12730 * Slashes::                     Slashes in shell scripts
12731 * Special Shell Variables::     Variables you should not change
12732 * Shell Functions::             What to look out for if you use them
12733 * Limitations of Builtins::     Portable use of not so portable /bin/sh
12734 * Limitations of Usual Tools::  Portable use of portable tools
12735 @end menu
12737 @node Shellology
12738 @section Shellology
12739 @cindex Shellology
12741 There are several families of shells, most prominently the Bourne family
12742 and the C shell family which are deeply incompatible.  If you want to
12743 write portable shell scripts, avoid members of the C shell family.  The
12744 @uref{http://@/www.faqs.org/@/faqs/@/unix-faq/@/shell/@/shell-differences/, the
12745 Shell difference FAQ} includes a small history of Posix shells, and a
12746 comparison between several of them.
12748 Below we describe some of the members of the Bourne shell family.
12750 @table @asis
12751 @item Ash
12752 @cindex Ash
12753 Ash is often used on @acronym{GNU}/Linux and @acronym{BSD}
12754 systems as a light-weight Bourne-compatible shell.  Ash 0.2 has some
12755 bugs that are fixed in the 0.3.x series, but portable shell scripts
12756 should work around them, since version 0.2 is still shipped with many
12757 @acronym{GNU}/Linux distributions.
12759 To be compatible with Ash 0.2:
12761 @itemize @minus
12762 @item
12763 don't use @samp{$?} after expanding empty or unset variables,
12764 or at the start of an @command{eval}:
12766 @example
12767 foo=
12768 false
12769 $foo
12770 echo "Do not use it: $?"
12771 false
12772 eval 'echo "Do not use it: $?"'
12773 @end example
12775 @item
12776 don't use command substitution within variable expansion:
12778 @example
12779 cat $@{FOO=`bar`@}
12780 @end example
12782 @item
12783 beware that single builtin substitutions are not performed by a
12784 subshell, hence their effect applies to the current shell!  @xref{Shell
12785 Substitutions}, item ``Command Substitution''.
12786 @end itemize
12788 @item Bash
12789 @cindex Bash
12790 To detect whether you are running Bash, test whether
12791 @code{BASH_VERSION} is set.  To require
12792 Posix compatibility, run @samp{set -o posix}.  @xref{Bash POSIX
12793 Mode, , Bash Posix Mode, bash, The @acronym{GNU} Bash Reference
12794 Manual}, for details.
12796 @item Bash 2.05 and later
12797 @cindex Bash 2.05 and later
12798 Versions 2.05 and later of Bash use a different format for the
12799 output of the @command{set} builtin, designed to make evaluating its
12800 output easier.  However, this output is not compatible with earlier
12801 versions of Bash (or with many other shells, probably).  So if
12802 you use Bash 2.05 or higher to execute @command{configure},
12803 you'll need to use Bash 2.05 for all other build tasks as well.
12805 @item Ksh
12806 @cindex Ksh
12807 @cindex Korn shell
12808 @prindex @samp{ksh}
12809 @prindex @samp{ksh88}
12810 @prindex @samp{ksh93}
12811 The Korn shell is compatible with the Bourne family and it mostly
12812 conforms to Posix.  It has two major variants commonly
12813 called @samp{ksh88} and @samp{ksh93}, named after the years of initial
12814 release.  It is usually called @command{ksh}, but is called @command{sh}
12815 on some hosts if you set your path appropriately.
12817 Solaris systems have three variants:
12818 @prindex @command{/usr/bin/ksh} on Solaris
12819 @command{/usr/bin/ksh} is @samp{ksh88}; it is
12820 standard on Solaris 2.0 and later.
12821 @prindex @command{/usr/xpg4/bin/sh} on Solaris
12822 @command{/usr/xpg4/bin/sh} is a Posix-compliant variant of
12823 @samp{ksh88}; it is standard on Solaris 9 and later.
12824 @prindex @command{/usr/dt/bin/dtksh} on Solaris
12825 @command{/usr/dt/bin/dtksh} is @samp{ksh93}.
12826 Variants that are not standard may be parts of optional
12827 packages.  There is no extra charge for these packages, but they are
12828 not part of a minimal OS install and therefore some installations may
12829 not have it.
12831 Starting with Tru64 Version 4.0, the Korn shell @command{/usr/bin/ksh}
12832 is also available as @command{/usr/bin/posix/sh}.  If the environment
12833 variable @env{BIN_SH} is set to @code{xpg4}, subsidiary invocations of
12834 the standard shell conform to Posix.
12836 @item Pdksh
12837 @prindex @samp{pdksh}
12838 A public-domain clone of the Korn shell called @command{pdksh} is widely
12839 available: it has most of the @samp{ksh88} features along with a few of
12840 its own.  It usually sets @code{KSH_VERSION}, except if invoked as
12841 @command{/bin/sh} on Open@acronym{BSD}, and similarly to Bash you can require
12842 Posix compatibility by running @samp{set -o posix}.  Unfortunately, with
12843 @command{pdksh} 5.2.14 (the latest stable version as of January 2007)
12844 Posix mode is buggy and causes @command{pdksh} to depart from Posix in
12845 at least one respect:
12847 @example
12848 $ @kbd{echo "`echo \"hello\"`"}
12849 hello
12850 $ @kbd{set -o posix}
12851 $ @kbd{echo "`echo \"hello\"`"}
12852 "hello"
12853 @end example
12855 The last line of output contains spurious quotes.  This is yet another
12856 reason why portable shell code should not contain
12857 @code{"`@dots{}\"@dots{}\"@dots{}`"} constructs (@pxref{Shell
12858 Substitutions}).
12860 @item Zsh
12861 @cindex Zsh
12862 To detect whether you are running @command{zsh}, test whether
12863 @code{ZSH_VERSION} is set.  By default @command{zsh} is @emph{not}
12864 compatible with the Bourne shell: you must execute @samp{emulate sh},
12865 and for @command{zsh} versions before 3.1.6-dev-18 you must also
12866 set @code{NULLCMD} to @samp{:}.  @xref{Compatibility, , Compatibility,
12867 zsh, The Z Shell Manual}, for details.
12869 The default Mac OS X @command{sh} was originally Zsh; it was changed to
12870 Bash in Mac OS X 10.2.
12871 @end table
12873 The following discussion between Russ Allbery and Robert Lipe is worth
12874 reading:
12876 @noindent
12877 Russ Allbery:
12879 @quotation
12880 The @acronym{GNU} assumption that @command{/bin/sh} is the one and only shell
12881 leads to a permanent deadlock.  Vendors don't want to break users'
12882 existing shell scripts, and there are some corner cases in the Bourne
12883 shell that are not completely compatible with a Posix shell.  Thus,
12884 vendors who have taken this route will @emph{never} (OK@dots{}``never say
12885 never'') replace the Bourne shell (as @command{/bin/sh}) with a
12886 Posix shell.
12887 @end quotation
12889 @noindent
12890 Robert Lipe:
12892 @quotation
12893 This is exactly the problem.  While most (at least most System V's) do
12894 have a Bourne shell that accepts shell functions most vendor
12895 @command{/bin/sh} programs are not the Posix shell.
12897 So while most modern systems do have a shell @emph{somewhere} that meets the
12898 Posix standard, the challenge is to find it.
12899 @end quotation
12901 @node Here-Documents
12902 @section Here-Documents
12903 @cindex Here-documents
12904 @cindex Shell here-documents
12906 Don't rely on @samp{\} being preserved just because it has no special
12907 meaning together with the next symbol.  In the native @command{sh}
12908 on Open@acronym{BSD} 2.7 @samp{\"} expands to @samp{"} in here-documents with
12909 unquoted delimiter.  As a general rule, if @samp{\\} expands to @samp{\}
12910 use @samp{\\} to get @samp{\}.
12912 With Open@acronym{BSD} 2.7's @command{sh}
12914 @example
12915 @group
12916 $ @kbd{cat <<EOF
12917 > \" \\
12918 > EOF}
12919 " \
12920 @end group
12921 @end example
12923 @noindent
12924 and with Bash:
12926 @example
12927 @group
12928 bash-2.04$ @kbd{cat <<EOF
12929 > \" \\
12930 > EOF}
12931 \" \
12932 @end group
12933 @end example
12935 Some shells mishandle large here-documents: for example,
12936 Solaris 10 @command{dtksh} and the UnixWare 7.1.1 Posix shell, which are
12937 derived from Korn shell version M-12/28/93d, mishandle braced variable
12938 expansion that crosses a 1024- or 4096-byte buffer boundary
12939 within a here-document.  Only the part of the variable name after the boundary
12940 is used.  For example, @code{$@{variable@}} could be replaced by the expansion
12941 of @code{$@{ble@}}.  If the end of the variable name is aligned with the block
12942 boundary, the shell reports an error, as if you used @code{$@{@}}.
12943 Instead of @code{$@{variable-default@}}, the shell may expand
12944 @code{$@{riable-default@}}, or even @code{$@{fault@}}.  This bug can often
12945 be worked around by omitting the braces: @code{$variable}.  The bug was
12946 fixed in
12947 @samp{ksh93g} (1998-04-30) but as of 2006 many operating systems were
12948 still shipping older versions with the bug.
12950 Many shells (including the Bourne shell) implement here-documents
12951 inefficiently.  In particular, some shells can be extremely inefficient when
12952 a single statement contains many here-documents.  For instance if your
12953 @file{configure.ac} includes something like:
12955 @example
12956 @group
12957 if <cross_compiling>; then
12958   assume this and that
12959 else
12960   check this
12961   check that
12962   check something else
12963   @dots{}
12964   on and on forever
12965   @dots{}
12967 @end group
12968 @end example
12970 A shell parses the whole @code{if}/@code{fi} construct, creating
12971 temporary files for each here-document in it.  Some shells create links
12972 for such here-documents on every @code{fork}, so that the clean-up code
12973 they had installed correctly removes them.  It is creating the links
12974 that can take the shell forever.
12976 Moving the tests out of the @code{if}/@code{fi}, or creating multiple
12977 @code{if}/@code{fi} constructs, would improve the performance
12978 significantly.  Anyway, this kind of construct is not exactly the
12979 typical use of Autoconf.  In fact, it's even not recommended, because M4
12980 macros can't look into shell conditionals, so we may fail to expand a
12981 macro when it was expanded before in a conditional path, and the
12982 condition turned out to be false at runtime, and we end up not
12983 executing the macro at all.
12985 @node File Descriptors
12986 @section File Descriptors
12987 @cindex Descriptors
12988 @cindex File descriptors
12989 @cindex Shell file descriptors
12991 Most shells, if not all (including Bash, Zsh, Ash), output traces on
12992 stderr, even for subshells.  This might result in undesirable content
12993 if you meant to capture the standard-error output of the inner command:
12995 @example
12996 $ @kbd{ash -x -c '(eval "echo foo >&2") 2>stderr'}
12997 $ @kbd{cat stderr}
12998 + eval echo foo >&2
12999 + echo foo
13001 $ @kbd{bash -x -c '(eval "echo foo >&2") 2>stderr'}
13002 $ @kbd{cat stderr}
13003 + eval 'echo foo >&2'
13004 ++ echo foo
13006 $ @kbd{zsh -x -c '(eval "echo foo >&2") 2>stderr'}
13007 @i{# Traces on startup files deleted here.}
13008 $ @kbd{cat stderr}
13009 +zsh:1> eval echo foo >&2
13010 +zsh:1> echo foo
13012 @end example
13014 @noindent
13015 One workaround is to grep out uninteresting lines, hoping not to remove
13016 good ones.
13018 If you intend to redirect both standard error and standard output,
13019 redirect standard output first.  This works better with @acronym{HP-UX},
13020 since its shell mishandles tracing if standard error is redirected
13021 first:
13023 @example
13024 $ @kbd{sh -x -c ': 2>err >out'}
13025 + :
13026 + 2> err $ @kbd{cat err}
13027 1> out
13028 @end example
13030 Don't try to redirect the standard error of a command substitution.  It
13031 must be done @emph{inside} the command substitution.  When running
13032 @samp{: `cd /zorglub` 2>/dev/null} expect the error message to
13033 escape, while @samp{: `cd /zorglub 2>/dev/null`} works properly.
13035 It is worth noting that Zsh (but not Ash nor Bash) makes it possible
13036 in assignments though: @samp{foo=`cd /zorglub` 2>/dev/null}.
13038 When catering to old systems, don't redirect the same file descriptor
13039 several times, as you are doomed to failure under Ultrix.
13041 @example
13042 ULTRIX V4.4 (Rev. 69) System #31: Thu Aug 10 19:42:23 GMT 1995
13043 UWS V4.4 (Rev. 11)
13044 $ @kbd{eval 'echo matter >fullness' >void}
13045 illegal io
13046 $ @kbd{eval '(echo matter >fullness)' >void}
13047 illegal io
13048 $ @kbd{(eval '(echo matter >fullness)') >void}
13049 Ambiguous output redirect.
13050 @end example
13052 @noindent
13053 In each case the expected result is of course @file{fullness} containing
13054 @samp{matter} and @file{void} being empty.  However, this bug is
13055 probably not of practical concern to modern platforms.
13057 Solaris 10 @command{sh} will try to optimize away a @command{:} command
13058 in a loop after the first iteration, even if it is redirected:
13060 @example
13061 $ @kbd{for i in 1 2 3 ; do : >x$i; done}
13062 $ @kbd{ls}
13064 @end example
13066 @noindent
13067 As a workaround, @command{echo} or @command{eval} can be used.
13069 Don't rely on file descriptors 0, 1, and 2 remaining closed in a
13070 subsidiary program.  If any of these descriptors is closed, the
13071 operating system may open an unspecified file for the descriptor in the
13072 new process image.  Posix says this may be done only if the subsidiary
13073 program is set-user-ID or set-group-ID, but @acronym{HP-UX} 11.23 does
13074 it even for ordinary programs.
13076 Don't rely on open file descriptors being open in child processes.  In
13077 @command{ksh}, file descriptors above 2 which are opened using
13078 @samp{exec @var{n}>file} are closed by a subsequent @samp{exec} (such as
13079 that involved in the fork-and-exec which runs a program or script).
13080 Thus, using @command{sh}, we have:
13082 @example
13083 $ @kbd{cat ./descrips}
13084 #!/bin/sh -
13085 echo hello >&5
13086 $ @kbd{exec 5>t}
13087 $ @kbd{./descrips}
13088 $ @kbd{cat t}
13089 hello
13091 @end example
13093 @noindent
13094 But using ksh:
13096 @example
13097 $ @kbd{exec 5>t}
13098 $ @kbd{./descrips}
13099 hello
13100 $ @kbd{cat t}
13102 @end example
13104 @noindent
13105 Within the process which runs the @samp{descrips} script, file
13106 descriptor 5 is closed.
13108 Don't rely on redirection to a closed file descriptor to cause an
13109 error.  With Solaris @command{/bin/sh}, when the redirection fails, the
13110 output goes to the original file descriptor.
13112 @example
13113 $ @kbd{bash -c 'echo hi >&3' 3>&-; echo $?}
13114 bash: 3: Bad file descriptor
13116 $ @kbd{/bin/sh -c 'echo hi >&3' 3>&-; echo $?}
13119 @end example
13121 @acronym{DOS} variants cannot rename or remove open files, such as in
13122 @samp{mv foo bar >foo} or @samp{rm foo >foo}, even though this is
13123 perfectly portable among Posix hosts.
13125 A few ancient systems reserved some file descriptors.  By convention,
13126 file descriptor 3 was opened to @file{/dev/tty} when you logged into
13127 Eighth Edition (1985) through Tenth Edition Unix (1989).  File
13128 descriptor 4 had a special use on the Stardent/Kubota Titan (circa
13129 1990), though we don't now remember what it was.  Both these systems are
13130 obsolete, so it's now safe to treat file descriptors 3 and 4 like any
13131 other file descriptors.
13133 @node File System Conventions
13134 @section File System Conventions
13135 @cindex File system conventions
13137 Autoconf uses shell-script processing extensively, so the file names
13138 that it processes should not contain characters that are special to the
13139 shell.  Special characters include space, tab, newline, @sc{nul}, and
13140 the following:
13142 @example
13143 " # $ & ' ( ) * ; < = > ? [ \ ` |
13144 @end example
13146 Also, file names should not begin with @samp{~} or @samp{-}, and should
13147 contain neither @samp{-} immediately after @samp{/} nor @samp{~}
13148 immediately after @samp{:}.  On Posix-like platforms, directory names
13149 should not contain @samp{:}, as this runs afoul of @samp{:} used as the
13150 path separator.
13152 These restrictions apply not only to the files that you distribute, but
13153 also to the absolute file names of your source, build, and destination
13154 directories.
13156 On some Posix-like platforms, @samp{!} and @samp{^} are special too, so
13157 they should be avoided.
13159 Posix lets implementations treat leading @file{//} specially, but
13160 requires leading @file{///} and beyond to be equivalent to @file{/}.
13161 Most Unix variants treat @file{//} like @file{/}.  However, some treat
13162 @file{//} as a ``super-root'' that can provide access to files that are
13163 not otherwise reachable from @file{/}.  The super-root tradition began
13164 with Apollo Domain/OS, which died out long ago, but unfortunately Cygwin
13165 has revived it.
13167 While @command{autoconf} and friends are usually run on some Posix
13168 variety, they can be used on other systems, most notably @acronym{DOS}
13169 variants.  This impacts several assumptions regarding file names.
13171 @noindent
13172 For example, the following code:
13174 @example
13175 case $foo_dir in
13176   /*) # Absolute
13177      ;;
13178   *)
13179      foo_dir=$dots$foo_dir ;;
13180 esac
13181 @end example
13183 @noindent
13184 fails to properly detect absolute file names on those systems, because
13185 they can use a drivespec, and usually use a backslash as directory
13186 separator.  If you want to be portable to @acronym{DOS} variants (at the
13187 price of rejecting valid but oddball Posix file names like @file{a:\b}),
13188 you can check for absolute file names like this:
13190 @cindex absolute file names, detect
13191 @example
13192 case $foo_dir in
13193   [\\/]* | ?:[\\/]* ) # Absolute
13194      ;;
13195   *)
13196      foo_dir=$dots$foo_dir ;;
13197 esac
13198 @end example
13200 @noindent
13201 Make sure you quote the brackets if appropriate and keep the backslash as
13202 first character (@pxref{Limitations of Builtins}).
13204 Also, because the colon is used as part of a drivespec, these systems don't
13205 use it as path separator.  When creating or accessing paths, you can use the
13206 @code{PATH_SEPARATOR} output variable instead.  @command{configure} sets this
13207 to the appropriate value for the build system (@samp{:} or @samp{;}) when it
13208 starts up.
13210 File names need extra care as well.  While @acronym{DOS} variants
13211 that are Posixy enough to run @command{autoconf} (such as @acronym{DJGPP})
13212 are usually able to handle long file names properly, there are still
13213 limitations that can seriously break packages.  Several of these issues
13214 can be easily detected by the
13215 @uref{ftp://@/ftp.gnu.org/@/gnu/@/non-gnu/@/doschk/@/doschk-1.1.tar.gz, doschk}
13216 package.
13218 A short overview follows; problems are marked with @sc{sfn}/@sc{lfn} to
13219 indicate where they apply: @sc{sfn} means the issues are only relevant to
13220 plain @acronym{DOS}, not to @acronym{DOS} under Microsoft Windows
13221 variants, while @sc{lfn} identifies problems that exist even under
13222 Microsoft Windows variants.
13224 @table @asis
13225 @item No multiple dots (@sc{sfn})
13226 @acronym{DOS} cannot handle multiple dots in file names.  This is an especially
13227 important thing to remember when building a portable configure script,
13228 as @command{autoconf} uses a .in suffix for template files.
13230 This is perfectly OK on Posix variants:
13232 @example
13233 AC_CONFIG_HEADERS([config.h])
13234 AC_CONFIG_FILES([source.c foo.bar])
13235 AC_OUTPUT
13236 @end example
13238 @noindent
13239 but it causes problems on @acronym{DOS}, as it requires @samp{config.h.in},
13240 @samp{source.c.in} and @samp{foo.bar.in}.  To make your package more portable
13241 to @acronym{DOS}-based environments, you should use this instead:
13243 @example
13244 AC_CONFIG_HEADERS([config.h:config.hin])
13245 AC_CONFIG_FILES([source.c:source.cin foo.bar:foobar.in])
13246 AC_OUTPUT
13247 @end example
13249 @item No leading dot (@sc{sfn})
13250 @acronym{DOS} cannot handle file names that start with a dot.  This is usually
13251 not important for @command{autoconf}.
13253 @item Case insensitivity (@sc{lfn})
13254 @acronym{DOS} is case insensitive, so you cannot, for example, have both a
13255 file called @samp{INSTALL} and a directory called @samp{install}.  This
13256 also affects @command{make}; if there's a file called @samp{INSTALL} in
13257 the directory, @samp{make install} does nothing (unless the
13258 @samp{install} target is marked as PHONY).
13260 @item The 8+3 limit (@sc{sfn})
13261 Because the @acronym{DOS} file system only stores the first 8 characters of
13262 the file name and the first 3 of the extension, those must be unique.
13263 That means that @file{foobar-part1.c}, @file{foobar-part2.c} and
13264 @file{foobar-prettybird.c} all resolve to the same file name
13265 (@file{FOOBAR-P.C}).  The same goes for @file{foo.bar} and
13266 @file{foo.bartender}.
13268 The 8+3 limit is not usually a problem under Microsoft Windows, as it
13269 uses numeric
13270 tails in the short version of file names to make them unique.  However, a
13271 registry setting can turn this behavior off.  While this makes it
13272 possible to share file trees containing long file names between @sc{sfn}
13273 and @sc{lfn} environments, it also means the above problem applies there
13274 as well.
13276 @item Invalid characters (@sc{lfn})
13277 Some characters are invalid in @acronym{DOS} file names, and should therefore
13278 be avoided.  In a @sc{lfn} environment, these are @samp{/}, @samp{\},
13279 @samp{?}, @samp{*}, @samp{:}, @samp{<}, @samp{>}, @samp{|} and @samp{"}.
13280 In a @sc{sfn} environment, other characters are also invalid.  These
13281 include @samp{+}, @samp{,}, @samp{[} and @samp{]}.
13283 @item Invalid names (@sc{lfn})
13284 Some @acronym{DOS} file names are reserved, and cause problems if you
13285 try to use files with those names.  These names include @file{CON},
13286 @file{AUX}, @file{COM1}, @file{COM2}, @file{COM3}, @file{COM4},
13287 @file{LPT1}, @file{LPT2}, @file{LPT3}, @file{NUL}, and @file{PRN}.
13288 File names are case insensitive, so even names like
13289 @file{aux/config.guess} are disallowed.
13291 @end table
13293 @node Shell Pattern Matching
13294 @section Shell Pattern Matching
13295 @cindex Shell pattern matching
13297 Nowadays portable patterns can use negated character classes like
13298 @samp{[!-aeiou]}.  The older syntax @samp{[^-aeiou]} is supported by
13299 some shells but not others; hence portable scripts should never use
13300 @samp{^} as the first character of a bracket pattern.
13302 Outside the C locale, patterns like @samp{[a-z]} are problematic since
13303 they may match characters that are not lower-case letters.
13305 @node Shell Substitutions
13306 @section Shell Substitutions
13307 @cindex Shell substitutions
13309 Contrary to a persistent urban legend, the Bourne shell does not
13310 systematically split variables and back-quoted expressions, in particular
13311 on the right-hand side of assignments and in the argument of @code{case}.
13312 For instance, the following code:
13314 @example
13315 case "$given_srcdir" in
13316 .)  top_srcdir="`echo "$dots" | sed 's|/$||'`" ;;
13317 *)  top_srcdir="$dots$given_srcdir" ;;
13318 esac
13319 @end example
13321 @noindent
13322 is more readable when written as:
13324 @example
13325 case $given_srcdir in
13326 .)  top_srcdir=`echo "$dots" | sed 's|/$||'` ;;
13327 *)  top_srcdir=$dots$given_srcdir ;;
13328 esac
13329 @end example
13331 @noindent
13332 and in fact it is even @emph{more} portable: in the first case of the
13333 first attempt, the computation of @code{top_srcdir} is not portable,
13334 since not all shells properly understand @code{"`@dots{}"@dots{}"@dots{}`"}.
13335 Worse yet, not all shells understand @code{"`@dots{}\"@dots{}\"@dots{}`"}
13336 the same way.  There is just no portable way to use double-quoted
13337 strings inside double-quoted back-quoted expressions (pfew!).
13339 @table @code
13340 @item $@@
13341 @cindex @samp{"$@@"}
13342 One of the most famous shell-portability issues is related to
13343 @samp{"$@@"}.  When there are no positional arguments, Posix says
13344 that @samp{"$@@"} is supposed to be equivalent to nothing, but the
13345 original Unix version 7 Bourne shell treated it as equivalent to
13346 @samp{""} instead, and this behavior survives in later implementations
13347 like Digital Unix 5.0.
13349 The traditional way to work around this portability problem is to use
13350 @samp{$@{1+"$@@"@}}.  Unfortunately this method does not work with
13351 Zsh (3.x and 4.x), which is used on Mac OS X@.  When emulating
13352 the Bourne shell, Zsh performs word splitting on @samp{$@{1+"$@@"@}}:
13354 @example
13355 zsh $ @kbd{emulate sh}
13356 zsh $ @kbd{for i in "$@@"; do echo $i; done}
13357 Hello World
13359 zsh $ @kbd{for i in $@{1+"$@@"@}; do echo $i; done}
13360 Hello
13361 World
13363 @end example
13365 @noindent
13366 Zsh handles plain @samp{"$@@"} properly, but we can't use plain
13367 @samp{"$@@"} because of the portability problems mentioned above.
13368 One workaround relies on Zsh's ``global aliases'' to convert
13369 @samp{$@{1+"$@@"@}} into @samp{"$@@"} by itself:
13371 @example
13372 test "$@{ZSH_VERSION+set@}" = set && alias -g '$@{1+"$@@"@}'='"$@@"'
13373 @end example
13375 Zsh only recognizes this alias when a shell word matches it exactly;
13376 @samp{"foo"$@{1+"$@@"@}} remains subject to word splitting.  Since this
13377 case always yields at least one shell word, use plain @samp{"$@@"}.
13379 A more conservative workaround is to avoid @samp{"$@@"} if it is
13380 possible that there may be no positional arguments.  For example,
13381 instead of:
13383 @example
13384 cat conftest.c "$@@"
13385 @end example
13387 you can use this instead:
13389 @example
13390 case $# in
13391 0) cat conftest.c;;
13392 *) cat conftest.c "$@@";;
13393 esac
13394 @end example
13396 Autoconf macros often use the @command{set} command to update
13397 @samp{$@@}, so if you are writing shell code intended for
13398 @command{configure} you should not assume that the value of @samp{$@@}
13399 persists for any length of time.
13402 @item $@{10@}
13403 @cindex positional parameters
13404 The 10th, 11th, @dots{} positional parameters can be accessed only after
13405 a @code{shift}.  The 7th Edition shell reported an error if given
13406 @code{$@{10@}}, and
13407 Solaris 10 @command{/bin/sh} still acts that way:
13409 @example
13410 $ @kbd{set 1 2 3 4 5 6 7 8 9 10}
13411 $ @kbd{echo $@{10@}}
13412 bad substitution
13413 @end example
13415 @item $@{@var{var}:-@var{value}@}
13416 @c Info cannot handle `:' in index entries.
13417 @c @cindex $@{@var{var}:-@var{value}@}
13418 Old @acronym{BSD} shells, including the Ultrix @code{sh}, don't accept the
13419 colon for any shell substitution, and complain and die.
13420 Similarly for $@{@var{var}:=@var{value}@}, $@{@var{var}:?@var{value}@}, etc.
13422 @item $@{@var{var}=@var{literal}@}
13423 @cindex $@{@var{var}=@var{literal}@}
13424 Be sure to quote:
13426 @example
13427 : $@{var='Some words'@}
13428 @end example
13430 @noindent
13431 otherwise some shells, such as on Digital Unix V 5.0, die because
13432 of a ``bad substitution''.
13434 @sp 1
13436 Solaris @command{/bin/sh} has a frightening bug in its interpretation
13437 of this.  Imagine you need set a variable to a string containing
13438 @samp{@}}.  This @samp{@}} character confuses Solaris @command{/bin/sh}
13439 when the affected variable was already set.  This bug can be exercised
13440 by running:
13442 @example
13443 $ @kbd{unset foo}
13444 $ @kbd{foo=$@{foo='@}'@}}
13445 $ @kbd{echo $foo}
13447 $ @kbd{foo=$@{foo='@}'   # no error; this hints to what the bug is}
13448 $ @kbd{echo $foo}
13450 $ @kbd{foo=$@{foo='@}'@}}
13451 $ @kbd{echo $foo}
13452 @}@}
13453  ^ ugh!
13454 @end example
13456 It seems that @samp{@}} is interpreted as matching @samp{$@{}, even
13457 though it is enclosed in single quotes.  The problem doesn't happen
13458 using double quotes.
13460 @item $@{@var{var}=@var{expanded-value}@}
13461 @cindex $@{@var{var}=@var{expanded-value}@}
13462 On Ultrix,
13463 running
13465 @example
13466 default="yu,yaa"
13467 : $@{var="$default"@}
13468 @end example
13470 @noindent
13471 sets @var{var} to @samp{M-yM-uM-,M-yM-aM-a}, i.e., the 8th bit of
13472 each char is set.  You don't observe the phenomenon using a simple
13473 @samp{echo $var} since apparently the shell resets the 8th bit when it
13474 expands $var.  Here are two means to make this shell confess its sins:
13476 @example
13477 $ @kbd{cat -v <<EOF
13478 $var
13479 EOF}
13480 @end example
13482 @noindent
13485 @example
13486 $ @kbd{set | grep '^var=' | cat -v}
13487 @end example
13489 One classic incarnation of this bug is:
13491 @example
13492 default="a b c"
13493 : $@{list="$default"@}
13494 for c in $list; do
13495   echo $c
13496 done
13497 @end example
13499 @noindent
13500 You'll get @samp{a b c} on a single line.  Why?  Because there are no
13501 spaces in @samp{$list}: there are @samp{M- }, i.e., spaces with the 8th
13502 bit set, hence no IFS splitting is performed!!!
13504 One piece of good news is that Ultrix works fine with @samp{:
13505 $@{list=$default@}}; i.e., if you @emph{don't} quote.  The bad news is
13506 then that @acronym{QNX} 4.25 then sets @var{list} to the @emph{last} item of
13507 @var{default}!
13509 The portable way out consists in using a double assignment, to switch
13510 the 8th bit twice on Ultrix:
13512 @example
13513 list=$@{list="$default"@}
13514 @end example
13516 @noindent
13517 @dots{}but beware of the @samp{@}} bug from Solaris (see above).  For safety,
13518 use:
13520 @example
13521 test "$@{var+set@}" = set || var=@var{@{value@}}
13522 @end example
13524 @item $@{#@var{var}@}
13525 @itemx $@{@var{var}%@var{word}@}
13526 @itemx $@{@var{var}%%@var{word}@}
13527 @itemx $@{@var{var}#@var{word}@}
13528 @itemx $@{@var{var}##@var{word}@}
13529 @cindex $@{#@var{var}@}
13530 @cindex $@{@var{var}%@var{word}@}
13531 @cindex $@{@var{var}%%@var{word}@}
13532 @cindex $@{@var{var}#@var{word}@}
13533 @cindex $@{@var{var}##@var{word}@}
13534 Posix requires support for these usages, but they do not work with many
13535 traditional shells, e.g., Solaris 10 @command{/bin/sh}.
13537 Also, @command{pdksh} 5.2.14 mishandles some @var{word} forms.  For
13538 example if @samp{$1} is @samp{a/b} and @samp{$2} is @samp{a}, then
13539 @samp{$@{1#$2@}} should yield @samp{/b}, but with @command{pdksh} it
13540 yields the empty string.
13543 @item `@var{commands}`
13544 @cindex `@var{commands}`
13545 @cindex Command Substitution
13546 Posix requires shells to trim all trailing newlines from command
13547 output before substituting it, so assignments like
13548 @samp{dir=`echo "$file" | tr a A`} do not work as expected if
13549 @samp{$file} ends in a newline.
13551 While in general it makes no sense, do not substitute a single builtin
13552 with side effects, because Ash 0.2, trying to optimize, does not fork a
13553 subshell to perform the command.
13555 For instance, if you wanted to check that @command{cd} is silent, do not
13556 use @samp{test -z "`cd /`"} because the following can happen:
13558 @example
13559 $ @kbd{pwd}
13560 /tmp
13561 $ @kbd{test -z "`cd /`" && pwd}
13563 @end example
13565 @noindent
13566 The result of @samp{foo=`exit 1`} is left as an exercise to the reader.
13568 The MSYS shell leaves a stray byte in the expansion of a double-quoted
13569 command substitution of a native program, if the end of the substitution
13570 is not aligned with the end of the double quote.  This may be worked
13571 around by inserting another pair of quotes:
13573 @example
13574 $ @kbd{echo "`printf 'foo\r\n'` bar" > broken}
13575 $ @kbd{echo "`printf 'foo\r\n'`"" bar" | cmp - broken}
13576 - broken differ: char 4, line 1
13577 @end example
13579 Upon interrupt or SIGTERM, some shells may abort a command substitution,
13580 replace it with a null string, and wrongly evaluate the enclosing
13581 command before entering the trap or ending the script.  This can lead to
13582 spurious errors:
13584 @example
13585 $ @kbd{sh -c 'if test `sleep 5; echo hi` = hi; then echo yes; fi'}
13586 $ @kbd{^C}
13587 sh: test: hi: unexpected operator/operand
13588 @end example
13590 @noindent
13591 You can avoid this by assigning the command substitution to a temporary
13592 variable:
13594 @example
13595 $ @kbd{sh -c 'res=`sleep 5; echo hi`
13596          if test "x$res" = xhi; then echo yes; fi'}
13597 $ @kbd{^C}
13598 @end example
13600 @item $(@var{commands})
13601 @cindex $(@var{commands})
13602 This construct is meant to replace @samp{`@var{commands}`},
13603 and it has most of the problems listed under @code{`@var{commands}`}.
13605 This construct can be
13606 nested while this is impossible to do portably with back quotes.
13607 Unfortunately it is not yet universally supported.  Most notably, even recent
13608 releases of Solaris don't support it:
13610 @example
13611 $ @kbd{showrev -c /bin/sh | grep version}
13612 Command version: SunOS 5.10 Generic 121005-03 Oct 2006
13613 $ @kbd{echo $(echo blah)}
13614 syntax error: `(' unexpected
13615 @end example
13617 @noindent
13618 nor does @sc{irix} 6.5's Bourne shell:
13619 @example
13620 $ @kbd{uname -a}
13621 IRIX firebird-image 6.5 07151432 IP22
13622 $ @kbd{echo $(echo blah)}
13623 $(echo blah)
13624 @end example
13626 If you do use @samp{$(@var{commands})}, make sure that the commands
13627 do not start with a parenthesis, as that would cause confusion with
13628 a different notation @samp{$((@var{expression}))} that in modern
13629 shells is an arithmetic expression not a command.  To avoid the
13630 confusion, insert a space between the two opening parentheses.
13632 Avoid @var{commands} that contain unbalanced parentheses in
13633 here-documents, comments, or case statement patterns, as many shells
13634 mishandle them.  For example, Bash 3.1, @samp{ksh88}, @command{pdksh}
13635 5.2.14, and Zsh 4.2.6 all mishandle the following valid command:
13637 @example
13638 echo $(case x in x) echo hello;; esac)
13639 @end example
13642 @item $((@var{expression}))
13643 @cindex $((@var{expression}))
13644 Arithmetic expansion is not portable as some shells (most
13645 notably Solaris 10 @command{/bin/sh}) don't support it.
13647 Among shells that do support @samp{$(( ))}, not all of them obey the
13648 Posix rule that octal and hexadecimal constants must be recognized:
13650 @example
13651 $ @kbd{bash -c 'echo $(( 010 + 0x10 ))'}
13653 $ @kbd{zsh -c 'echo $(( 010 + 0x10 ))'}
13655 $ @kbd{zsh -c 'emulate sh; echo $(( 010 + 0x10 ))'}
13657 $ @kbd{pdksh -c 'echo $(( 010 + 0x10 ))'}
13658 pdksh:  010 + 0x10 : bad number `0x10'
13659 $ @kbd{pdksh -c 'echo $(( 010 ))'}
13661 @end example
13663 When it is available, using arithmetic expansion provides a noticeable
13664 speedup in script execution; but testing for support requires
13665 @command{eval} to avoid syntax errors.  If shell function support can
13666 be assumed, then this construct can be used to assign @samp{foo}
13667 to an arithmetic result, provided all numeric arguments are provided in
13668 decimal and without a leading zero:
13670 @example
13671 if ( eval 'test $(( 1 + 1 )) = 2' ) 2>/dev/null; then
13672   eval 'func_arith ()
13673   @{
13674     func_arith_result=$(( $* ))
13675   @}'
13676 else
13677   func_arith ()
13678   @{
13679     func_arith_result=`expr "$@@"`
13680   @}
13682 func_arith 1 + 1
13683 foo=$func_arith_result
13684 @end example
13687 @item ^
13688 @cindex ^ quoting
13689 Always quote @samp{^}, otherwise traditional shells such as
13690 @command{/bin/sh} on Solaris 10 treat this like @samp{|}.
13692 @end table
13695 @node Assignments
13696 @section Assignments
13697 @cindex Shell assignments
13699 When setting several variables in a row, be aware that the order of the
13700 evaluation is undefined.  For instance @samp{foo=1 foo=2; echo $foo}
13701 gives @samp{1} with Solaris @command{/bin/sh}, but @samp{2} with Bash.
13702 You must use
13703 @samp{;} to enforce the order: @samp{foo=1; foo=2; echo $foo}.
13705 Don't rely on the following to find @file{subdir/program}:
13707 @example
13708 PATH=subdir$PATH_SEPARATOR$PATH program
13709 @end example
13711 @noindent
13712 as this does not work with Zsh 3.0.6.  Use something like this
13713 instead:
13715 @example
13716 (PATH=subdir$PATH_SEPARATOR$PATH; export PATH; exec program)
13717 @end example
13719 Don't rely on the exit status of an assignment: Ash 0.2 does not change
13720 the status and propagates that of the last statement:
13722 @example
13723 $ @kbd{false || foo=bar; echo $?}
13725 $ @kbd{false || foo=`:`; echo $?}
13727 @end example
13729 @noindent
13730 and to make things even worse, @acronym{QNX} 4.25 just sets the exit status
13731 to 0 in any case:
13733 @example
13734 $ @kbd{foo=`exit 1`; echo $?}
13736 @end example
13738 To assign default values, follow this algorithm:
13740 @enumerate
13741 @item
13742 If the default value is a literal and does not contain any closing
13743 brace, use:
13745 @example
13746 : $@{var='my literal'@}
13747 @end example
13749 @item
13750 If the default value contains no closing brace, has to be expanded, and
13751 the variable being initialized is not intended to be IFS-split
13752 (i.e., it's not a list), then use:
13754 @example
13755 : $@{var="$default"@}
13756 @end example
13758 @item
13759 If the default value contains no closing brace, has to be expanded, and
13760 the variable being initialized is intended to be IFS-split (i.e., it's a list),
13761 then use:
13763 @example
13764 var=$@{var="$default"@}
13765 @end example
13767 @item
13768 If the default value contains a closing brace, then use:
13770 @example
13771 test "$@{var+set@}" = set || var="has a '@}'"
13772 @end example
13773 @end enumerate
13775 In most cases @samp{var=$@{var="$default"@}} is fine, but in case of
13776 doubt, just use the last form.  @xref{Shell Substitutions}, items
13777 @samp{$@{@var{var}:-@var{value}@}} and @samp{$@{@var{var}=@var{value}@}}
13778 for the rationale.
13780 @node Parentheses
13781 @section Parentheses in Shell Scripts
13782 @cindex Shell parentheses
13784 Beware of two opening parentheses in a row, as many shell
13785 implementations treat them specially.  Posix requires that the command
13786 @samp{((cat))} must behave like @samp{(cat)}, but many shells, including
13787 Bash and the Korn shell, treat @samp{((cat))} as an arithmetic
13788 expression equivalent to @samp{let "cat"}, and may or may not report an
13789 error when they detect that @samp{cat} is not a number.  As another
13790 example, @samp{pdksh} 5.2.14 misparses the following code:
13792 @example
13793 if ((true) || false); then
13794   echo ok
13796 @end example
13798 @noindent
13799 To work around this problem, insert a space between the two opening
13800 parentheses.  There is a similar problem and workaround with
13801 @samp{$((}; see @ref{Shell Substitutions}.
13803 @node Slashes
13804 @section Slashes in Shell Scripts
13805 @cindex Shell slashes
13807 Unpatched Tru64 5.1 @command{sh} omits the last slash of command-line
13808 arguments that contain two trailing slashes:
13810 @example
13811 $ @kbd{echo / // /// //// .// //.}
13812 / / // /// ./ //.
13813 $ @kbd{x=//}
13814 $ @kbd{eval "echo \$x"}
13816 $ @kbd{set -x}
13817 $ @kbd{echo abc | tr -t ab //}
13818 + echo abc
13819 + tr -t ab /
13821 @end example
13823 Unpatched Tru64 4.0 @command{sh} adds a slash after @samp{"$var"} if the
13824 variable is empty and the second double-quote is followed by a word that
13825 begins and ends with slash:
13827 @example
13828 $ @kbd{sh -xc 'p=; echo "$p"/ouch/'}
13830 + echo //ouch/
13831 //ouch/
13832 @end example
13834 However, our understanding is that patches are available, so perhaps
13835 it's not worth worrying about working around these horrendous bugs.
13837 @node Special Shell Variables
13838 @section Special Shell Variables
13839 @cindex Shell variables
13840 @cindex Special shell variables
13842 Some shell variables should not be used, since they can have a deep
13843 influence on the behavior of the shell.  In order to recover a sane
13844 behavior from the shell, some variables should be unset, but
13845 @command{unset} is not portable (@pxref{Limitations of Builtins}) and a
13846 fallback value is needed.
13848 As a general rule, shell variable names containing a lower-case letter
13849 are safe; you can define and use these variables without worrying about
13850 their effect on the underlying system, and without worrying about
13851 whether the shell changes them unexpectedly.  (The exception is the
13852 shell variable @code{status}, as described below.)
13854 Here is a list of names that are known to cause trouble.  This list is
13855 not exhaustive, but you should be safe if you avoid the name
13856 @code{status} and names containing only upper-case letters and
13857 underscores.
13859 @c Alphabetical order, case insensitive, `A' before `a'.
13860 @table @code
13861 @item _
13862 Many shells reserve @samp{$_} for various purposes, e.g., the name of
13863 the last command executed.
13865 @item BIN_SH
13866 @evindex BIN_SH
13867 In Tru64, if @env{BIN_SH} is set to @code{xpg4}, subsidiary invocations of
13868 the standard shell conform to Posix.
13870 @item CDPATH
13871 @evindex CDPATH
13872 When this variable is set it specifies a list of directories to search
13873 when invoking @code{cd} with a relative file name that did not start
13874 with @samp{./} or @samp{../}.  Posix
13875 1003.1-2001 says that if a nonempty directory name from @env{CDPATH}
13876 is used successfully, @code{cd} prints the resulting absolute
13877 file name.  Unfortunately this output can break idioms like
13878 @samp{abs=`cd src && pwd`} because @code{abs} receives the name twice.
13879 Also, many shells do not conform to this part of Posix; for
13880 example, @command{zsh} prints the result only if a directory name
13881 other than @file{.} was chosen from @env{CDPATH}.
13883 In practice the shells that have this problem also support
13884 @command{unset}, so you can work around the problem as follows:
13886 @example
13887 (unset CDPATH) >/dev/null 2>&1 && unset CDPATH
13888 @end example
13890 You can also avoid output by ensuring that your directory name is
13891 absolute or anchored at @samp{./}, as in @samp{abs=`cd ./src && pwd`}.
13893 Autoconf-generated scripts automatically unset @env{CDPATH} if
13894 possible, so you need not worry about this problem in those scripts.
13896 @item DUALCASE
13897 @evindex DUALCASE
13898 In the MKS shell, case statements and file name generation are
13899 case-insensitive unless @env{DUALCASE} is nonzero.
13900 Autoconf-generated scripts export this variable when they start up.
13902 @item ENV
13903 @itemx MAIL
13904 @itemx MAILPATH
13905 @itemx PS1
13906 @itemx PS2
13907 @itemx PS4
13908 @evindex ENV
13909 @evindex MAIL
13910 @evindex MAILPATH
13911 @evindex PS1
13912 @evindex PS2
13913 @evindex PS4
13914 These variables should not matter for shell scripts, since they are
13915 supposed to affect only interactive shells.  However, at least one
13916 shell (the pre-3.0 @sc{uwin} Korn shell) gets confused about
13917 whether it is interactive, which means that (for example) a @env{PS1}
13918 with a side effect can unexpectedly modify @samp{$?}.  To work around
13919 this bug, Autoconf-generated scripts do something like this:
13921 @example
13922 (unset ENV) >/dev/null 2>&1 && unset ENV MAIL MAILPATH
13923 PS1='$ '
13924 PS2='> '
13925 PS4='+ '
13926 @end example
13928 @item FPATH
13929 The Korn shell uses @env{FPATH} to find shell functions, so avoid
13930 @env{FPATH} in portable scripts.  @env{FPATH} is consulted after
13931 @env{PATH}, but you still need to be wary of tests that use @env{PATH}
13932 to find whether a command exists, since they might report the wrong
13933 result if @env{FPATH} is also set.
13935 @item IFS
13936 @evindex IFS
13937 Long ago, shell scripts inherited @env{IFS} from the environment,
13938 but this caused many problems so modern shells ignore any environment
13939 settings for @env{IFS}.
13941 Don't set the first character of @code{IFS} to backslash.  Indeed,
13942 Bourne shells use the first character (backslash) when joining the
13943 components in @samp{"$@@"} and some shells then reinterpret (!)@: the
13944 backslash escapes, so you can end up with backspace and other strange
13945 characters.
13947 The proper value for @code{IFS} (in regular code, not when performing
13948 splits) is @samp{@key{SPC}@key{TAB}@key{RET}}.  The first character is
13949 especially important, as it is used to join the arguments in @samp{$*};
13950 however, note that traditional shells, but also bash-2.04, fail to adhere
13951 to this and join with a space anyway.
13953 @item LANG
13954 @itemx LC_ALL
13955 @itemx LC_COLLATE
13956 @itemx LC_CTYPE
13957 @itemx LC_MESSAGES
13958 @itemx LC_MONETARY
13959 @itemx LC_NUMERIC
13960 @itemx LC_TIME
13961 @evindex LANG
13962 @evindex LC_ALL
13963 @evindex LC_COLLATE
13964 @evindex LC_CTYPE
13965 @evindex LC_MESSAGES
13966 @evindex LC_MONETARY
13967 @evindex LC_NUMERIC
13968 @evindex LC_TIME
13970 Autoconf-generated scripts normally set all these variables to
13971 @samp{C} because so much configuration code assumes the C locale and
13972 Posix requires that locale environment variables be set to
13973 @samp{C} if the C locale is desired.  However, some older, nonstandard
13974 systems (notably @acronym{SCO}) break if locale environment variables
13975 are set to @samp{C}, so when running on these systems
13976 Autoconf-generated scripts unset the variables instead.
13978 @item LANGUAGE
13979 @evindex LANGUAGE
13981 @env{LANGUAGE} is not specified by Posix, but it is a @acronym{GNU}
13982 extension that overrides @env{LC_ALL} in some cases, so
13983 Autoconf-generated scripts set it too.
13985 @item LC_ADDRESS
13986 @itemx LC_IDENTIFICATION
13987 @itemx LC_MEASUREMENT
13988 @itemx LC_NAME
13989 @itemx LC_PAPER
13990 @itemx LC_TELEPHONE
13991 @evindex LC_ADDRESS
13992 @evindex LC_IDENTIFICATION
13993 @evindex LC_MEASUREMENT
13994 @evindex LC_NAME
13995 @evindex LC_PAPER
13996 @evindex LC_TELEPHONE
13998 These locale environment variables are @acronym{GNU} extensions.  They
13999 are treated like their Posix brethren (@env{LC_COLLATE},
14000 etc.)@: as described above.
14002 @item LINENO
14003 Most modern shells provide the current line number in @code{LINENO}.
14004 Its value is the line number of the beginning of the current command.
14005 Autoconf attempts to execute @command{configure} with a shell that
14006 supports @code{LINENO}.
14007 If no such shell is available, it attempts to implement @code{LINENO}
14008 with a Sed prepass that replaces each instance of the string
14009 @code{$LINENO} (not followed by an alphanumeric character) with the
14010 line's number.
14012 You should not rely on @code{LINENO} within @command{eval}, as the
14013 behavior differs in practice.  Also, the possibility of the Sed
14014 prepass means that you should not rely on @code{$LINENO} when quoted,
14015 when in here-documents, or when in long commands that cross line
14016 boundaries.  Subshells should be OK, though.  In the following
14017 example, lines 1, 6, and 9 are portable, but the other instances of
14018 @code{LINENO} are not:
14020 @example
14021 @group
14022 $ @kbd{cat lineno}
14023 echo 1. $LINENO
14024 cat <<EOF
14025 3. $LINENO
14026 4. $LINENO
14028 ( echo 6. $LINENO )
14029 eval 'echo 7. $LINENO'
14030 echo 8. '$LINENO'
14031 echo 9. $LINENO '
14032 10.' $LINENO
14033 @end group
14034 @group
14035 $ @kbd{bash-2.05 lineno}
14036 1. 1
14037 3. 2
14038 4. 2
14039 6. 6
14040 7. 1
14041 8. $LINENO
14042 9. 9
14043 10. 9
14044 @end group
14045 @group
14046 $ @kbd{zsh-3.0.6 lineno}
14047 1. 1
14048 3. 2
14049 4. 2
14050 6. 6
14051 7. 7
14052 8. $LINENO
14053 9. 9
14054 10. 9
14055 @end group
14056 @group
14057 $ @kbd{pdksh-5.2.14 lineno}
14058 1. 1
14059 3. 2
14060 4. 2
14061 6. 6
14062 7. 0
14063 8. $LINENO
14064 9. 9
14065 10. 9
14066 @end group
14067 @group
14068 $ @kbd{sed '=' <lineno |}
14069 > @kbd{  sed '}
14070 > @kbd{    N}
14071 > @kbd{    s,$,-,}
14072 > @kbd{    t loop}
14073 > @kbd{    :loop}
14074 > @kbd{    s,^\([0-9]*\)\(.*\)[$]LINENO\([^a-zA-Z0-9_]\),\1\2\1\3,}
14075 > @kbd{    t loop}
14076 > @kbd{    s,-$,,}
14077 > @kbd{    s,^[0-9]*\n,,}
14078 > @kbd{  ' |}
14079 > @kbd{  sh}
14080 1. 1
14081 3. 3
14082 4. 4
14083 6. 6
14084 7. 7
14085 8. 8
14086 9. 9
14087 10. 10
14088 @end group
14089 @end example
14091 @item NULLCMD
14092 @evindex NULLCMD
14093 When executing the command @samp{>foo}, @command{zsh} executes
14094 @samp{$NULLCMD >foo} unless it is operating in Bourne shell
14095 compatibility mode and the @command{zsh} version is newer
14096 than 3.1.6-dev-18.  If you are using an older @command{zsh}
14097 and forget to set @env{NULLCMD},
14098 your script might be suspended waiting for data on its standard input.
14100 @item PATH_SEPARATOR
14101 @evindex PATH_SEPARATOR
14102 On @acronym{DJGPP} systems, the @env{PATH_SEPARATOR} environment
14103 variable can be set to either @samp{:} or @samp{;} to control the path
14104 separator Bash uses to set up certain environment variables (such as
14105 @env{PATH}).  You can set this variable to @samp{;} if you want
14106 @command{configure} to use @samp{;} as a separator; this might be useful
14107 if you plan to use non-Posix shells to execute files.  @xref{File System
14108 Conventions}, for more information about @code{PATH_SEPARATOR}.
14110 @item PWD
14111 @evindex PWD
14112 Posix 1003.1-2001 requires that @command{cd} and
14113 @command{pwd} must update the @env{PWD} environment variable to point
14114 to the logical name of the current directory, but traditional shells
14115 do not support this.  This can cause confusion if one shell instance
14116 maintains @env{PWD} but a subsidiary and different shell does not know
14117 about @env{PWD} and executes @command{cd}; in this case @env{PWD}
14118 points to the wrong directory.  Use @samp{`pwd`} rather than
14119 @samp{$PWD}.
14121 @item RANDOM
14122 Many shells provide @code{RANDOM}, a variable that returns a different
14123 integer each time it is used.  Most of the time, its value does not
14124 change when it is not used, but on @sc{irix} 6.5 the value changes all
14125 the time.  This can be observed by using @command{set}.  It is common
14126 practice to use @code{$RANDOM} as part of a file name, but code
14127 shouldn't rely on @code{$RANDOM} expanding to a nonempty string.
14129 @item status
14130 This variable is an alias to @samp{$?} for @code{zsh} (at least 3.1.6),
14131 hence read-only.  Do not use it.
14132 @end table
14134 @node Shell Functions
14135 @section Shell Functions
14136 @cindex Shell Functions
14138 Nowadays, it is difficult to find a shell that does not support
14139 shell functions at all.  However, some differences should be expected:
14141 Inside a shell function, you should not rely on the error status of a
14142 subshell if the last command of that subshell was @code{exit} or
14143 @code{trap}, as this triggers bugs in zsh 4.x; while Autoconf tries to
14144 find a shell that does not exhibit the bug, zsh might be the only shell
14145 present on the user's machine.
14147 Likewise, the state of @samp{$?} is not reliable when entering a shell
14148 function.  This has the effect that using a function as the first
14149 command in a @command{trap} handler can cause problems.
14151 @example
14152 $ @kbd{bash -c 'foo()@{ echo $?; @}; trap foo 0; (exit 2); exit 2'; echo $?}
14155 $ @kbd{ash -c 'foo()@{ echo $?; @}; trap foo 0; (exit 2); exit 2'; echo $?}
14158 @end example
14160 Shell variables and functions may share the same namespace, for example
14161 with Solaris 10 @command{/bin/sh}:
14163 @example
14164 $ @kbd{f () @{ :; @}; f=; f}
14165 f: not found
14166 @end example
14168 @noindent
14169 For this reason, Autoconf (actually M4sh, @pxref{Programming in M4sh})
14170 uses the prefix @samp{as_func_} for its functions.
14172 Handling of positional parameters and shell options varies among shells.
14173 For example, Korn shells reset and restore trace output (@samp{set -x})
14174 and other options upon function entry and exit.  Inside a function,
14175 @acronym{IRIX} sh sets @samp{$0} to the function name.
14177 Some ancient Bourne shell variants with function support did not reset
14178 @samp{$@var{i}, @var{i} >= 0}, upon function exit, so effectively the
14179 arguments of the script were lost after the first function invocation.
14180 It is probably not worth worrying about these shells any more.
14182 With @acronym{AIX} sh, a @command{trap} on 0 installed in a shell function
14183 triggers at function exit rather than at script exit, see @xref{Limitations
14184 of Builtins}.
14186 @node Limitations of Builtins
14187 @section Limitations of Shell Builtins
14188 @cindex Shell builtins
14189 @cindex Limitations of shell builtins
14191 No, no, we are serious: some shells do have limitations!  :)
14193 You should always keep in mind that any builtin or command may support
14194 options, and therefore differ in behavior with arguments
14195 starting with a dash.  For instance, the innocent @samp{echo "$word"}
14196 can give unexpected results when @code{word} starts with a dash.  It is
14197 often possible to avoid this problem using @samp{echo "x$word"}, taking
14198 the @samp{x} into account later in the pipe.
14200 @table @asis
14201 @item @command{.}
14202 @c --------------
14203 @prindex @command{.}
14204 Use @command{.} only with regular files (use @samp{test -f}).  Bash
14205 2.03, for instance, chokes on @samp{. /dev/null}.  Remember that
14206 @command{.} uses @env{PATH} if its argument contains no slashes.  Also,
14207 some shells, including bash 3.2, implicitly append the current directory
14208 to this @env{PATH} search, even though Posix forbids it.  So if you want
14209 to use @command{.} on a file @file{foo} in the current directory, you
14210 must use @samp{. ./foo}.
14212 @item @command{!}
14213 @c --------------
14214 @prindex @command{!}
14215 The Unix version 7 shell did not support
14216 negating the exit status of commands with @command{!}, and this feature
14217 is still absent from some shells (e.g., Solaris @command{/bin/sh}).
14218 Other shells, such as FreeBSD @command{/bin/sh} or @command{ash}, have
14219 bugs when using @command{!}:
14221 @example
14222 $ @kbd{sh -c '! : | :'; echo $?}
14224 $ @kbd{ash -c '! : | :'; echo $?}
14226 $ @kbd{sh -c '! @{ :; @}'; echo $?}
14228 $ @kbd{ash -c '! @{ :; @}'; echo $?}
14229 @{: not found
14230 Syntax error: "@}" unexpected
14232 @end example
14234 Shell code like this:
14236 @example
14237 if ! cmp file1 file2 >/dev/null 2>&1; then
14238   echo files differ or trouble
14240 @end example
14242 is therefore not portable in practice.  Typically it is easy to rewrite
14243 such code, e.g.:
14245 @example
14246 cmp file1 file2 >/dev/null 2>&1 ||
14247   echo files differ or trouble
14248 @end example
14250 More generally, one can always rewrite @samp{! @var{command}} as:
14252 @example
14253 if @var{command}; then (exit 1); else :; fi
14254 @end example
14257 @item @command{@{...@}}
14258 @c --------------------
14259 @prindex @command{@{...@}}
14260 Bash 3.2 (and earlier versions) sometimes does not properly set
14261 @samp{$?} when failing to write redirected output of a compound command.
14262 This problem is most commonly observed with @samp{@{@dots{}@}}; it does
14263 not occur with @samp{(@dots{})}.  For example:
14265 @example
14266 $ @kbd{bash -c '@{ echo foo; @} >/bad; echo $?'}
14267 bash: line 1: /bad: Permission denied
14269 $ @kbd{bash -c 'while :; do echo; done >/bad; echo $?'}
14270 bash: line 1: /bad: Permission denied
14272 @end example
14274 To work around the bug, prepend @samp{:;}:
14276 @example
14277 $ @kbd{bash -c ':;@{ echo foo; @} >/bad; echo $?'}
14278 bash: line 1: /bad: Permission denied
14280 @end example
14283 @item @command{break}
14284 @c ------------------
14285 @prindex @command{break}
14286 The use of @samp{break 2} etc.@: is safe.
14289 @item @command{case}
14290 @c -----------------
14291 @prindex @command{case}
14292 You don't need to quote the argument; no splitting is performed.
14294 You don't need the final @samp{;;}, but you should use it.
14296 Posix requires support for @code{case} patterns with opening
14297 parentheses like this:
14299 @example
14300 case $file_name in
14301   (*.c) echo "C source code";;
14302 esac
14303 @end example
14305 @noindent
14306 but the @code{(} in this example is not portable to many Bourne
14307 shell implementations, which is a pity for those of us using tools that
14308 rely on balanced parentheses.  For instance, with Solaris
14309 @command{/bin/sh}:
14311 @example
14312 $ @kbd{case foo in (foo) echo foo;; esac}
14313 @error{}syntax error: `(' unexpected
14314 @end example
14316 @noindent
14317 The leading @samp{(} can be omitted safely.  In contexts where
14318 unbalanced parentheses cause other problems, such as when using a case
14319 statement as an argument to an Autoconf macro, you can also resort to
14320 creative shell comments to supply the balance:
14322 @example
14323 case $file_name in #(
14324   *.c) echo "C source code";;
14325 esac
14326 @end example
14328 Zsh handles pattern fragments derived from parameter expansions or
14329 command substitutions as though quoted:
14331 @example
14332 $ pat=\?; case aa in ?$pat) echo match;; esac
14333 $ pat=\?; case a? in ?$pat) echo match;; esac
14334 match
14335 @end example
14337 @noindent
14338 Because of a bug in its @code{fnmatch}, Bash fails to properly
14339 handle backslashes in character classes:
14341 @example
14342 bash-2.02$ @kbd{case /tmp in [/\\]*) echo OK;; esac}
14343 bash-2.02$
14344 @end example
14346 @noindent
14347 This is extremely unfortunate, since you are likely to use this code to
14348 handle Posix or @sc{ms-dos} absolute file names.  To work around this
14349 bug, always put the backslash first:
14351 @example
14352 bash-2.02$ @kbd{case '\TMP' in [\\/]*) echo OK;; esac}
14354 bash-2.02$ @kbd{case /tmp in [\\/]*) echo OK;; esac}
14356 @end example
14358 Many Bourne shells cannot handle closing brackets in character classes
14359 correctly.
14361 Some shells also have problems with backslash escaping in case you do not want
14362 to match the backslash: both a backslash and the escaped character match this
14363 pattern.  To work around this, specify the character class in a variable, so
14364 that quote removal does not apply afterwards, and the special characters don't
14365 have to be backslash-escaped:
14367 @example
14368 $ @kbd{case '\' in [\<]) echo OK;; esac}
14370 $ @kbd{scanset='[<]'; case '\' in $scanset) echo OK;; esac}
14372 @end example
14374 Even with this, Solaris @command{ksh} matches a backslash if the set
14375 contains any
14376 of the characters @samp{|}, @samp{&}, @samp{(}, or @samp{)}.
14378 Conversely, Tru64 @command{ksh} (circa 2003) erroneously always matches
14379 a closing parenthesis if not specified in a character class:
14381 @example
14382 $ @kbd{case foo in *\)*) echo fail ;; esac}
14383 fail
14384 $ @kbd{case foo in *')'*) echo fail ;; esac}
14385 fail
14386 @end example
14388 Some shells, such as Ash 0.3.8, are confused by an empty
14389 @code{case}/@code{esac}:
14391 @example
14392 ash-0.3.8 $ @kbd{case foo in esac;}
14393 @error{}Syntax error: ";" unexpected (expecting ")")
14394 @end example
14397 @item @command{cd}
14398 @c ---------------
14399 @prindex @command{cd}
14400 Posix 1003.1-2001 requires that @command{cd} must support
14401 the @option{-L} (``logical'') and @option{-P} (``physical'') options,
14402 with @option{-L} being the default.  However, traditional shells do
14403 not support these options, and their @command{cd} command has the
14404 @option{-P} behavior.
14406 Portable scripts should assume neither option is supported, and should
14407 assume neither behavior is the default.  This can be a bit tricky,
14408 since the Posix default behavior means that, for example,
14409 @samp{ls ..} and @samp{cd ..} may refer to different directories if
14410 the current logical directory is a symbolic link.  It is safe to use
14411 @code{cd @var{dir}} if @var{dir} contains no @file{..} components.
14412 Also, Autoconf-generated scripts check for this problem when computing
14413 variables like @code{ac_top_srcdir} (@pxref{Configuration Actions}),
14414 so it is safe to @command{cd} to these variables.
14416 See @xref{Special Shell Variables}, for portability problems involving
14417 @command{cd} and the @env{CDPATH} environment variable.
14418 Also please see the discussion of the @command{pwd} command.
14421 @item @command{echo}
14422 @c -----------------
14423 @prindex @command{echo}
14424 The simple @command{echo} is probably the most surprising source of
14425 portability troubles.  It is not possible to use @samp{echo} portably
14426 unless both options and escape sequences are omitted.  New applications
14427 which are not aiming at portability should use @samp{printf} instead of
14428 @samp{echo}.
14430 Don't expect any option.  @xref{Preset Output Variables}, @code{ECHO_N}
14431 etc.@: for a means to simulate @option{-n}.
14433 Do not use backslashes in the arguments, as there is no consensus on
14434 their handling.  For @samp{echo '\n' | wc -l}, the @command{sh} of
14435 Solaris outputs 2, but Bash and Zsh (in @command{sh} emulation mode) output 1.
14436 The problem is truly @command{echo}: all the shells
14437 understand @samp{'\n'} as the string composed of a backslash and an
14438 @samp{n}.
14440 Because of these problems, do not pass a string containing arbitrary
14441 characters to @command{echo}.  For example, @samp{echo "$foo"} is safe
14442 if you know that @var{foo}'s value cannot contain backslashes and cannot
14443 start with @samp{-}, but otherwise you should use a here-document like
14444 this:
14446 @example
14447 cat <<EOF
14448 $foo
14450 @end example
14453 @item @command{eval}
14454 @c -----------------
14455 @prindex @command{eval}
14456 The @command{eval} command is useful in limited circumstances, e.g.,
14457 using commands like @samp{eval table_$key=\$value} and @samp{eval
14458 value=table_$key} to simulate a hash table when the key is known to be
14459 alphanumeric.  However, @command{eval} is tricky to use on arbitrary
14460 arguments, even when it is implemented correctly.
14462 It is obviously unwise to use @samp{eval $cmd} if the string value of
14463 @samp{cmd} was derived from an untrustworthy source.  But even if the
14464 string value is valid, @samp{eval $cmd} might not work as intended,
14465 since it causes field splitting and file name expansion to occur twice,
14466 once for the @command{eval} and once for the command itself.  It is
14467 therefore safer to use @samp{eval "$cmd"}.  For example, if @var{cmd}
14468 has the value @samp{cat test?.c}, @samp{eval $cmd} might expand to the
14469 equivalent of @samp{cat test;.c} if there happens to be a file named
14470 @file{test;.c} in the current directory; and this in turn
14471 mistakenly attempts to invoke @command{cat} on the file @file{test} and
14472 then execute the command @command{.c}.  To avoid this problem, use
14473 @samp{eval "$cmd"} rather than @samp{eval $cmd}.
14475 However, suppose that you want to output the text of the evaluated
14476 command just before executing it.  Assuming the previous example,
14477 @samp{echo "Executing: $cmd"} outputs @samp{Executing: cat test?.c}, but
14478 this output doesn't show the user that @samp{test;.c} is the actual name
14479 of the copied file.  Conversely, @samp{eval "echo Executing: $cmd"}
14480 works on this example, but it fails with @samp{cmd='cat foo >bar'},
14481 since it mistakenly replaces the contents of @file{bar} by the
14482 string @samp{cat foo}.  No simple, general, and portable solution to
14483 this problem is known.
14485 You should also be wary of common bugs in @command{eval} implementations.
14486 In some shell implementations (e.g., older @command{ash}, Open@acronym{BSD} 3.8
14487 @command{sh}, @command{pdksh} v5.2.14 99/07/13.2, and @command{zsh}
14488 4.2.5), the arguments of @samp{eval} are evaluated in a context where
14489 @samp{$?} is 0, so they exhibit behavior like this:
14491 @example
14492 $ @kbd{false; eval 'echo $?'}
14494 @end example
14496 The correct behavior here is to output a nonzero value,
14497 but portable scripts should not rely on this.
14499 You should not rely on @code{LINENO} within @command{eval}.
14500 @xref{Special Shell Variables}.
14502 @item @command{exec}
14503 @c -----------------
14504 @prindex @command{exec}
14505 Posix describes several categories of shell built-ins.  Special
14506 built-ins (such as @command{exit}) must impact the environment of the
14507 current shell, and need not be available through @command{exec}.  All
14508 other built-ins are regular, and must not propagate variable assignments
14509 to the environment of the current shell.  However, the group of regular
14510 built-ins is further distinguished by commands that do not require a
14511 @env{PATH} search (such as @command{cd}), in contrast to built-ins that
14512 are offered as a more efficient version of something that must still be
14513 found in a @env{PATH} search (such as @command{echo}).  Posix is not
14514 clear on whether @command{exec} must work with the list of 17 utilities
14515 that are invoked without a @env{PATH} search, and many platforms lack an
14516 executable for some of those built-ins:
14518 @example
14519 $ @kbd{sh -c 'exec cd /tmp'}
14520 sh: line 0: exec: cd: not found
14521 @end example
14523 All other built-ins that provide utilities specified by Posix must have
14524 a counterpart executable that exists on @env{PATH}, although Posix
14525 allows @command{exec} to use the built-in instead of the executable.
14526 For example, contrast @command{bash} 3.2 and @command{pdksh} 5.2.14:
14528 @example
14529 $ @kbd{bash -c 'pwd --version' | head -n1}
14530 bash: line 0: pwd: --: invalid option
14531 pwd: usage: pwd [-LP]
14532 $ @kbd{bash -c 'exec pwd --version' | head -n1}
14533 pwd (GNU coreutils) 6.10
14534 $ @kbd{pdksh -c 'exec pwd --version' | head -n1}
14535 pdksh: pwd: --: unknown option
14536 @end example
14538 When it is desired to avoid a regular shell built-in, the workaround is
14539 to use some other forwarding command, such as @command{env} or
14540 @command{nice}, that will ensure a path search:
14542 @example
14543 $ @kbd{pdksh -c 'exec true --version' | head -n1}
14544 $ @kbd{pdksh -c 'nice true --version' | head -n1}
14545 true (GNU coreutils) 6.10
14546 $ @kbd{pdksh -c 'env true --version' | head -n1}
14547 true (GNU coreutils) 6.10
14548 @end example
14550 @item @command{exit}
14551 @c -----------------
14552 @prindex @command{exit}
14553 The default value of @command{exit} is supposed to be @code{$?};
14554 unfortunately, some shells, such as the @acronym{DJGPP} port of Bash 2.04, just
14555 perform @samp{exit 0}.
14557 @example
14558 bash-2.04$ @kbd{foo=`exit 1` || echo fail}
14559 fail
14560 bash-2.04$ @kbd{foo=`(exit 1)` || echo fail}
14561 fail
14562 bash-2.04$ @kbd{foo=`(exit 1); exit` || echo fail}
14563 bash-2.04$
14564 @end example
14566 Using @samp{exit $?} restores the expected behavior.
14568 Some shell scripts, such as those generated by @command{autoconf}, use a
14569 trap to clean up before exiting.  If the last shell command exited with
14570 nonzero status, the trap also exits with nonzero status so that the
14571 invoker can tell that an error occurred.
14573 Unfortunately, in some shells, such as Solaris @command{/bin/sh}, an exit
14574 trap ignores the @code{exit} command's argument.  In these shells, a trap
14575 cannot determine whether it was invoked by plain @code{exit} or by
14576 @code{exit 1}.  Instead of calling @code{exit} directly, use the
14577 @code{AC_MSG_ERROR} macro that has a workaround for this problem.
14580 @item @command{export}
14581 @c -------------------
14582 @prindex @command{export}
14583 The builtin @command{export} dubs a shell variable @dfn{environment
14584 variable}.  Each update of exported variables corresponds to an update
14585 of the environment variables.  Conversely, each environment variable
14586 received by the shell when it is launched should be imported as a shell
14587 variable marked as exported.
14589 Alas, many shells, such as Solaris @command{/bin/sh},
14590 @sc{irix} 6.3, @sc{irix} 5.2,
14591 @acronym{AIX} 4.1.5, and Digital Unix 4.0, forget to
14592 @command{export} the environment variables they receive.  As a result,
14593 two variables coexist: the environment variable and the shell
14594 variable.  The following code demonstrates this failure:
14596 @example
14597 #!/bin/sh
14598 echo $FOO
14599 FOO=bar
14600 echo $FOO
14601 exec /bin/sh $0
14602 @end example
14604 @noindent
14605 when run with @samp{FOO=foo} in the environment, these shells print
14606 alternately @samp{foo} and @samp{bar}, although they should print only
14607 @samp{foo} and then a sequence of @samp{bar}s.
14609 Therefore you should @command{export} again each environment variable
14610 that you update; the export can occur before or after the assignment.
14612 Posix is not clear on whether the @command{export} of an undefined
14613 variable causes the variable to be defined with the value of an empty
14614 string, or merely marks any future definition of a variable by that name
14615 for export.  Various shells behave differently in this regard:
14617 @example
14618 $ @kbd{sh -c 'export foo; env | grep foo'}
14619 $ @kbd{ash -c 'export foo; env | grep foo'}
14620 foo=
14621 @end example
14623 @item @command{false}
14624 @c ------------------
14625 @prindex @command{false}
14626 Don't expect @command{false} to exit with status 1: in native
14627 Solaris @file{/bin/false} exits with status 255.
14630 @item @command{for}
14631 @c ----------------
14632 @prindex @command{for}
14633 To loop over positional arguments, use:
14635 @example
14636 for arg
14638   echo "$arg"
14639 done
14640 @end example
14642 @noindent
14643 You may @emph{not} leave the @code{do} on the same line as @code{for},
14644 since some shells improperly grok:
14646 @example
14647 for arg; do
14648   echo "$arg"
14649 done
14650 @end example
14652 If you want to explicitly refer to the positional arguments, given the
14653 @samp{$@@} bug (@pxref{Shell Substitutions}), use:
14655 @example
14656 for arg in $@{1+"$@@"@}; do
14657   echo "$arg"
14658 done
14659 @end example
14661 @noindent
14662 But keep in mind that Zsh, even in Bourne shell emulation mode, performs
14663 word splitting on @samp{$@{1+"$@@"@}}; see @ref{Shell Substitutions},
14664 item @samp{$@@}, for more.
14667 @item @command{if}
14668 @c ---------------
14669 @prindex @command{if}
14670 Using @samp{!} is not portable.  Instead of:
14672 @example
14673 if ! cmp -s file file.new; then
14674   mv file.new file
14676 @end example
14678 @noindent
14679 use:
14681 @example
14682 if cmp -s file file.new; then :; else
14683   mv file.new file
14685 @end example
14687 There are shells that do not reset the exit status from an @command{if}:
14689 @example
14690 $ @kbd{if (exit 42); then true; fi; echo $?}
14692 @end example
14694 @noindent
14695 whereas a proper shell should have printed @samp{0}.  This is especially
14696 bad in makefiles since it produces false failures.  This is why properly
14697 written makefiles, such as Automake's, have such hairy constructs:
14699 @example
14700 if test -f "$file"; then
14701   install "$file" "$dest"
14702 else
14703   :
14705 @end example
14708 @item @command{printf}
14709 @c ------------------
14710 @prindex @command{printf}
14711 A format string starting with a @samp{-} can cause problems.
14712 Bash interprets it as an option and
14713 gives an error.  And @samp{--} to mark the end of options is not good
14714 in the Net@acronym{BSD} Almquist shell (e.g., 0.4.6) which takes that
14715 literally as the format string.  Putting the @samp{-} in a @samp{%c}
14716 or @samp{%s} is probably easiest:
14718 @example
14719 printf %s -foo
14720 @end example
14722 Bash 2.03 mishandles an escape sequence that happens to evaluate to @samp{%}:
14724 @example
14725 $ @kbd{printf '\045'}
14726 bash: printf: `%': missing format character
14727 @end example
14729 Large outputs may cause trouble.  On Solaris 2.5.1 through 10, for
14730 example, @file{/usr/bin/printf} is buggy, so when using
14731 @command{/bin/sh} the command @samp{printf %010000x 123} normally dumps
14732 core.
14735 @item @command{read}
14736 @c ------------------
14737 @prindex @command{read}
14738 Not all shells support @option{-r} (Solaris @command{/bin/sh} for example).
14741 @item @command{pwd}
14742 @c ----------------
14743 @prindex @command{pwd}
14744 With modern shells, plain @command{pwd} outputs a ``logical''
14745 directory name, some of whose components may be symbolic links.  These
14746 directory names are in contrast to ``physical'' directory names, whose
14747 components are all directories.
14749 Posix 1003.1-2001 requires that @command{pwd} must support
14750 the @option{-L} (``logical'') and @option{-P} (``physical'') options,
14751 with @option{-L} being the default.  However, traditional shells do
14752 not support these options, and their @command{pwd} command has the
14753 @option{-P} behavior.
14755 Portable scripts should assume neither option is supported, and should
14756 assume neither behavior is the default.  Also, on many hosts
14757 @samp{/bin/pwd} is equivalent to @samp{pwd -P}, but Posix
14758 does not require this behavior and portable scripts should not rely on
14761 Typically it's best to use plain @command{pwd}.  On modern hosts this
14762 outputs logical directory names, which have the following advantages:
14764 @itemize @bullet
14765 @item
14766 Logical names are what the user specified.
14767 @item
14768 Physical names may not be portable from one installation
14769 host to another due to network file system gymnastics.
14770 @item
14771 On modern hosts @samp{pwd -P} may fail due to lack of permissions to
14772 some parent directory, but plain @command{pwd} cannot fail for this
14773 reason.
14774 @end itemize
14776 Also please see the discussion of the @command{cd} command.
14779 @item @command{set}
14780 @c ----------------
14781 @prindex @command{set}
14782 With the Free@acronym{BSD} 6.0 shell, the @command{set} command (without
14783 any options) does not sort its output.
14785 The @command{set} builtin faces the usual problem with arguments
14786 starting with a
14787 dash.  Modern shells such as Bash or Zsh understand @option{--} to specify
14788 the end of the options (any argument after @option{--} is a parameter,
14789 even @samp{-x} for instance), but many traditional shells (e.g., Solaris
14790 10 @command{/bin/sh}) simply stop option
14791 processing as soon as a non-option argument is found.  Therefore, use
14792 @samp{dummy} or simply @samp{x} to end the option processing, and use
14793 @command{shift} to pop it out:
14795 @example
14796 set x $my_list; shift
14797 @end example
14799 Avoid @samp{set -}, e.g., @samp{set - $my_list}.  Posix no
14800 longer requires support for this command, and in traditional shells
14801 @samp{set - $my_list} resets the @option{-v} and @option{-x} options, which
14802 makes scripts harder to debug.
14804 Some nonstandard shells do not recognize more than one option
14805 (e.g., @samp{set -e -x} assigns @samp{-x} to the command line).  It is
14806 better to combine them:
14808 @example
14809 set -ex
14810 @end example
14812 The @acronym{BSD} shell has had several problems with the @option{-e}
14813 option, partly because @acronym{BSD} @command{make} traditionally used
14814 @option{-e} even though this was incompatible with Posix
14815 (@pxref{Failure in Make Rules}).  Older versions of the @acronym{BSD}
14816 shell (circa 1990) mishandled @samp{&&}, @samp{||}, @samp{if}, and
14817 @samp{case} when @option{-e} was in effect, causing the shell to exit
14818 unexpectedly in some cases.  This was particularly a problem with
14819 makefiles, and led to circumlocutions like @samp{sh -c 'test -f file ||
14820 touch file'}, where the seemingly-unnecessary @samp{sh -c '@dots{}'}
14821 wrapper works around the bug.
14823 Even relatively-recent versions of the @acronym{BSD} shell (e.g.,
14824 Open@acronym{BSD} 3.4) wrongly exit with @option{-e} if a command within
14825 @samp{&&} fails inside a compound statement.  For example:
14827 @example
14828 #! /bin/sh
14829 set -e
14830 foo=''
14831 test -n "$foo" && exit 1
14832 echo one
14833 if :; then
14834   test -n "$foo" && exit 1
14836 echo two
14837 @end example
14839 @noindent
14840 does not print @samp{two}.  One workaround is to use @samp{if test -n
14841 "$foo"; then exit 1; fi} rather than @samp{test -n "$foo" && exit 1}.
14842 Another possibility is to warn @acronym{BSD} users not to use @samp{sh -e}.
14845 @item @command{shift}
14846 @c ------------------
14847 @prindex @command{shift}
14848 Not only is @command{shift}ing a bad idea when there is nothing left to
14849 shift, but in addition it is not portable: the shell of @acronym{MIPS
14850 RISC/OS} 4.52 refuses to do it.
14852 Don't use @samp{shift 2} etc.; it was not in the 7th Edition Bourne shell,
14853 and it is also absent in many pre-Posix shells.
14856 @item @command{source}
14857 @c -------------------
14858 @prindex @command{source}
14859 This command is not portable, as Posix does not require it; use
14860 @command{.} instead.
14863 @item @command{test}
14864 @c -----------------
14865 @prindex @command{test}
14866 The @code{test} program is the way to perform many file and string
14867 tests.  It is often invoked by the alternate name @samp{[}, but using
14868 that name in Autoconf code is asking for trouble since it is an M4 quote
14869 character.
14871 The @option{-a}, @option{-o}, @samp{(}, and @samp{)} operands are not
14872 portable and should be avoided.  Thus, portable uses of @command{test}
14873 should never have more than four arguments, and scripts should use shell
14874 constructs like @samp{&&} and @samp{||} instead.  If you combine
14875 @samp{&&} and @samp{||} in the same statement, keep in mind that they
14876 have equal precedence, so it is often better to parenthesize even when
14877 this is redundant.  For example:
14879 @smallexample
14880 # Not portable:
14881 test "X$a" = "X$b" -a \
14882   '(' "X$c" != "X$d" -o "X$e" = "X$f" ')'
14884 # Portable:
14885 test "X$a" = "X$b" &&
14886   @{ test "X$c" != "X$d" || test "X$e" = "X$f"; @}
14887 @end smallexample
14889 @command{test} does not process options like most other commands do; for
14890 example, it does not recognize the @option{--} argument as marking the
14891 end of options.
14893 It is safe to use @samp{!} as a @command{test} operator.  For example,
14894 @samp{if test ! -d foo; @dots{}} is portable even though @samp{if ! test
14895 -d foo; @dots{}} is not.
14898 @item @command{test} (files)
14899 @c -------------------------
14900 To enable @command{configure} scripts to support cross-compilation, they
14901 shouldn't do anything that tests features of the build system instead of
14902 the host system.  But occasionally you may find it necessary to check
14903 whether some arbitrary file exists.  To do so, use @samp{test -f} or
14904 @samp{test -r}.  Do not use @samp{test -x}, because 4.3@acronym{BSD} does not
14905 have it.  Do not use @samp{test -e} either, because Solaris @command{/bin/sh}
14906 lacks it.  To test for symbolic links on systems that have them, use
14907 @samp{test -h} rather than @samp{test -L}; either form conforms to
14908 Posix 1003.1-2001, but older shells like Solaris 8
14909 @code{/bin/sh} support only @option{-h}.
14911 @item @command{test} (strings)
14912 @c ---------------------------
14913 Posix says that @samp{test "@var{string}"} succeeds if @var{string} is
14914 not null, but this usage is not portable to traditional platforms like
14915 Solaris 10 @command{/bin/sh}, which mishandle strings like @samp{!} and
14916 @samp{-n}.
14918 Posix also says that @samp{test ! "@var{string}"},
14919 @samp{test -n "@var{string}"} and
14920 @samp{test -z "@var{string}"} work with any string, but many
14921 shells (such as Solaris, @acronym{AIX} 3.2, @sc{unicos} 10.0.0.6,
14922 Digital Unix 4, etc.)@: get confused if
14923 @var{string} looks like an operator:
14925 @example
14926 $ @kbd{test -n =}
14927 test: argument expected
14928 $ @kbd{test ! -n}
14929 test: argument expected
14930 @end example
14932 Similarly, Posix says that both @samp{test "@var{string1}" = "@var{string2"}}
14933 and @samp{test "@var{string1}" != "@var{string2"}} work for any pairs of
14934 strings, but in practice this is not true for troublesome strings that
14935 look like operators or parentheses, or that begin with @samp{-}.
14937 It is best to protect such strings with a leading @samp{X}, e.g.,
14938 @samp{test "X@var{string}" != X} rather than @samp{test -n
14939 "@var{string}"} or @samp{test ! "@var{string}"}.
14941 It is common to find variations of the following idiom:
14943 @example
14944 test -n "`echo $ac_feature | sed 's/[-a-zA-Z0-9_]//g'`" &&
14945   @var{action}
14946 @end example
14948 @noindent
14949 to take an action when a token matches a given pattern.  Such constructs
14950 should be avoided by using:
14952 @example
14953 case $ac_feature in
14954   *[!-a-zA-Z0-9_]*) @var{action};;
14955 esac
14956 @end example
14958 If the pattern is a complicated regular expression that cannot be
14959 expressed as a shell pattern, use something like this instead:
14961 @example
14962 expr "X$ac_feature" : 'X.*[^-a-zA-Z0-9_]' >/dev/null &&
14963   @var{action}
14964 @end example
14966 @samp{expr "X@var{foo}" : "X@var{bar}"} is more robust than @samp{echo
14967 "X@var{foo}" | grep "^X@var{bar}"}, because it avoids problems when
14968 @samp{@var{foo}} contains backslashes.
14971 @item @command{trap}
14972 @c -----------------
14973 @prindex @command{trap}
14974 It is safe to trap at least the signals 1, 2, 13, and 15.  You can also
14975 trap 0, i.e., have the @command{trap} run when the script ends (either via an
14976 explicit @command{exit}, or the end of the script).  The trap for 0 should be
14977 installed outside of a shell function, or @acronym{AIX} 5.3 @command{/bin/sh}
14978 will invoke the trap at the end of this function.
14980 Posix says that @samp{trap - 1 2 13 15} resets the traps for the
14981 specified signals to their default values, but many common shells (e.g.,
14982 Solaris @command{/bin/sh}) misinterpret this and attempt to execute a
14983 ``command'' named @command{-} when the specified conditions arise.
14984 There is no portable workaround, except for @samp{trap - 0}, for which
14985 @samp{trap '' 0} is a portable substitute.
14987 Although Posix is not absolutely clear on this point, it is widely
14988 admitted that when entering the trap @samp{$?} should be set to the exit
14989 status of the last command run before the trap.  The ambiguity can be
14990 summarized as: ``when the trap is launched by an @command{exit}, what is
14991 the @emph{last} command run: that before @command{exit}, or
14992 @command{exit} itself?''
14994 Bash considers @command{exit} to be the last command, while Zsh and
14995 Solaris @command{/bin/sh} consider that when the trap is run it is
14996 @emph{still} in the @command{exit}, hence it is the previous exit status
14997 that the trap receives:
14999 @example
15000 $ @kbd{cat trap.sh}
15001 trap 'echo $?' 0
15002 (exit 42); exit 0
15003 $ @kbd{zsh trap.sh}
15005 $ @kbd{bash trap.sh}
15007 @end example
15009 The portable solution is then simple: when you want to @samp{exit 42},
15010 run @samp{(exit 42); exit 42}, the first @command{exit} being used to
15011 set the exit status to 42 for Zsh, and the second to trigger the trap
15012 and pass 42 as exit status for Bash.
15014 The shell in Free@acronym{BSD} 4.0 has the following bug: @samp{$?} is
15015 reset to 0 by empty lines if the code is inside @command{trap}.
15017 @example
15018 $ @kbd{trap 'false}
15020 echo $?' 0
15021 $ @kbd{exit}
15023 @end example
15025 @noindent
15026 Fortunately, this bug only affects @command{trap}.
15028 @item @command{true}
15029 @c -----------------
15030 @prindex @command{true}
15031 @c Info cannot handle `:' in index entries.
15032 @c @prindex @command{:}
15033 Don't worry: as far as we know @command{true} is portable.
15034 Nevertheless, it's not always a builtin (e.g., Bash 1.x), and the
15035 portable shell community tends to prefer using @command{:}.  This has a
15036 funny side effect: when asked whether @command{false} is more portable
15037 than @command{true} Alexandre Oliva answered:
15039 @quotation
15040 In a sense, yes, because if it doesn't exist, the shell will produce an
15041 exit status of failure, which is correct for @command{false}, but not
15042 for @command{true}.
15043 @end quotation
15046 @item @command{unset}
15047 @c ------------------
15048 @prindex @command{unset}
15049 In some nonconforming shells (e.g., Bash 2.05a), @code{unset FOO} fails
15050 when @code{FOO} is not set.  Also, Bash 2.01 mishandles @code{unset
15051 MAIL} in some cases and dumps core.
15053 A few ancient shells lack @command{unset} entirely.  Nevertheless, because
15054 it is extremely useful to disable embarrassing variables such as
15055 @code{PS1}, you can test for its existence and use
15056 it @emph{provided} you give a neutralizing value when @command{unset} is
15057 not supported:
15059 @smallexample
15060 # "|| exit" suppresses any "Segmentation fault" message.
15061 if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; then
15062   unset=unset
15063 else
15064   unset=false
15066 $unset PS1 || PS1='$ '
15067 @end smallexample
15069 @noindent
15070 @xref{Special Shell Variables}, for some neutralizing values.  Also, see
15071 @ref{Limitations of Builtins}, documentation of @command{export}, for
15072 the case of environment variables.
15073 @end table
15075 @node Limitations of Usual Tools
15076 @section Limitations of Usual Tools
15077 @cindex Limitations of usual tools
15079 The small set of tools you can expect to find on any machine can still
15080 include some limitations you should be aware of.
15082 @table @asis
15083 @item Awk
15084 @c ------
15085 @prindex Awk
15086 Don't leave white space before the opening parenthesis in a user function call.
15087 Posix does not allow this and @acronym{GNU} Awk rejects it:
15089 @example
15090 $ @kbd{gawk 'function die () @{ print "Aaaaarg!"  @}
15091         BEGIN @{ die () @}'}
15092 gawk: cmd. line:2:         BEGIN @{ die () @}
15093 gawk: cmd. line:2:                      ^ parse error
15094 $ @kbd{gawk 'function die () @{ print "Aaaaarg!"  @}
15095         BEGIN @{ die() @}'}
15096 Aaaaarg!
15097 @end example
15099 Posix says that if a program contains only @samp{BEGIN} actions, and
15100 contains no instances of @code{getline}, then the program merely
15101 executes the actions without reading input.  However, traditional Awk
15102 implementations (such as Solaris 10 @command{awk}) read and discard
15103 input in this case.  Portable scripts can redirect input from
15104 @file{/dev/null} to work around the problem.  For example:
15106 @example
15107 awk 'BEGIN @{print "hello world"@}' </dev/null
15108 @end example
15110 Posix says that in an @samp{END} action, @samp{$NF} (and presumably,
15111 @samp{$1}) retain their value from the last record read, if no
15112 intervening @samp{getline} occurred.  However, some implementations
15113 (such as Solaris 10 @samp{/usr/bin/awk}, @samp{nawk}, or Darwin
15114 @samp{awk}) reset these variables.  A workaround is to use an
15115 intermediate variable prior to the @samp{END} block.  For example:
15117 @example
15118 $ @kbd{cat end.awk}
15119 @{ tmp = $1 @}
15120 END @{ print "a", $1, $NF, "b", tmp @}
15121 $ @kbd{echo 1 | awk -f end.awk}
15122 a   b 1
15123 $ @kbd{echo 1 | gawk -f end.awk}
15124 a 1 1 b 1
15125 @end example
15127 If you want your program to be deterministic, don't depend on @code{for}
15128 on arrays:
15130 @example
15131 $ @kbd{cat for.awk}
15132 END @{
15133   arr["foo"] = 1
15134   arr["bar"] = 1
15135   for (i in arr)
15136     print i
15138 $ @kbd{gawk -f for.awk </dev/null}
15141 $ @kbd{nawk -f for.awk </dev/null}
15144 @end example
15146 Some Awk implementations, such as @acronym{HP-UX} 11.0's native one,
15147 mishandle anchors:
15149 @example
15150 $ @kbd{echo xfoo | $AWK '/foo|^bar/ @{ print @}'}
15151 $ @kbd{echo bar | $AWK '/foo|^bar/ @{ print @}'}
15153 $ @kbd{echo xfoo | $AWK '/^bar|foo/ @{ print @}'}
15154 xfoo
15155 $ @kbd{echo bar | $AWK '/^bar|foo/ @{ print @}'}
15157 @end example
15159 @noindent
15160 Either do not depend on such patterns (i.e., use @samp{/^(.*foo|bar)/},
15161 or use a simple test to reject such implementations.
15163 On @samp{ia64-hp-hpux11.23}, Awk mishandles @code{printf} conversions
15164 after @code{%u}:
15166 @example
15167 $ @kbd{awk 'BEGIN @{ printf "%u %d\n", 0, -1 @}'}
15168 0 0
15169 @end example
15171 @acronym{AIX} version 5.2 has an arbitrary limit of 399 on the
15172 length of regular expressions and literal strings in an Awk program.
15174 Traditional Awk implementations derived from Unix version 7, such as
15175 Solaris @command{/bin/awk}, have many limitations and do not
15176 conform to Posix.  Nowadays @code{AC_PROG_AWK} (@pxref{Particular
15177 Programs}) finds you an Awk that doesn't have these problems, but if
15178 for some reason you prefer not to use @code{AC_PROG_AWK} you may need to
15179 address them.
15181 Traditional Awk does not support multidimensional arrays or user-defined
15182 functions.
15184 Traditional Awk does not support the @option{-v} option.  You can use
15185 assignments after the program instead, e.g., @code{$AWK '@{print v
15186 $1@}' v=x}; however, don't forget that such assignments are not
15187 evaluated until they are encountered (e.g., after any @code{BEGIN}
15188 action).
15190 Traditional Awk does not support the keywords @code{delete} or @code{do}.
15192 Traditional Awk does not support the expressions
15193 @code{@var{a}?@var{b}:@var{c}}, @code{!@var{a}}, @code{@var{a}^@var{b}},
15194 or @code{@var{a}^=@var{b}}.
15196 Traditional Awk does not support the predefined @code{CONVFMT} variable.
15198 Traditional Awk supports only the predefined functions @code{exp}, @code{index},
15199 @code{int}, @code{length}, @code{log}, @code{split}, @code{sprintf},
15200 @code{sqrt}, and @code{substr}.
15202 Traditional Awk @code{getline} is not at all compatible with Posix;
15203 avoid it.
15205 Traditional Awk has @code{for (i in a) @dots{}} but no other uses of the
15206 @code{in} keyword.  For example, it lacks @code{if (i in a) @dots{}}.
15208 In code portable to both traditional and modern Awk, @code{FS} must be a
15209 string containing just one ordinary character, and similarly for the
15210 field-separator argument to @code{split}.
15212 Traditional Awk has a limit of 99 fields in a record.  Since some Awk
15213 implementations, like Tru64's, split the input even if you don't refer
15214 to any field in the script, to circumvent this problem, set @samp{FS}
15215 to an unusual character and use @code{split}.
15217 Traditional Awk has a limit of at most 99 bytes in a number formatted by
15218 @code{OFMT}; for example, @code{OFMT="%.300e"; print 0.1;} typically
15219 dumps core.
15221 The original version of Awk had a limit of at most 99 bytes per
15222 @code{split} field, 99 bytes per @code{substr} substring, and 99 bytes
15223 per run of non-special characters in a @code{printf} format, but these
15224 bugs have been fixed on all practical hosts that we know of.
15226 @item @command{basename}
15227 @c ---------------------
15228 @prindex @command{basename}
15229 Not all hosts have a working @command{basename}.
15230 You can use @command{expr} instead.
15232 @c AS_BASENAME is to be replaced by a better API.
15233 @ignore
15234 Not all hosts have a working @command{basename}, and you should instead
15235 use @code{AS_BASENAME} (@pxref{Programming in M4sh}), followed by
15236 @command{expr} if you need to strip a suffix.  For example:
15238 @example
15239 a=`basename "$aname"`       # This is not portable.
15240 a=`AS_BASENAME(["$aname"])` # This is more portable.
15242 # This is not portable.
15243 c=`basename "$cname" .c`
15245 # This is more portable.
15246 c=`AS_BASENAME(["$cname"])`
15247 case $c in
15248 ?*.c) c=`expr "X$c" : 'X\(.*\)\.c'`;;
15249 esac
15250 @end example
15251 @end ignore
15254 @item @command{cat}
15255 @c ----------------
15256 @prindex @command{cat}
15257 Don't rely on any option.
15260 @item @command{cc}
15261 @c ---------------
15262 @prindex @command{cc}
15263 The command @samp{cc -c foo.c} traditionally produces an object file
15264 named @file{foo.o}.  Most compilers allow @option{-c} to be combined
15265 with @option{-o} to specify a different object file name, but
15266 Posix does not require this combination and a few compilers
15267 lack support for it.  @xref{C Compiler}, for how @acronym{GNU} Make
15268 tests for this feature with @code{AC_PROG_CC_C_O}.
15270 When a compilation such as @samp{cc -o foo foo.c} fails, some compilers
15271 (such as @sc{cds} on Reliant Unix) leave a @file{foo.o}.
15273 @acronym{HP-UX} @command{cc} doesn't accept @file{.S} files to preprocess and
15274 assemble.  @samp{cc -c foo.S} appears to succeed, but in fact does
15275 nothing.
15277 The default executable, produced by @samp{cc foo.c}, can be
15279 @itemize
15280 @item @file{a.out} --- usual Posix convention.
15281 @item @file{b.out} --- i960 compilers (including @command{gcc}).
15282 @item @file{a.exe} --- @acronym{DJGPP} port of @command{gcc}.
15283 @item @file{a_out.exe} --- GNV @command{cc} wrapper for DEC C on OpenVMS.
15284 @item @file{foo.exe} --- various MS-DOS compilers.
15285 @end itemize
15287 The C compiler's traditional name is @command{cc}, but other names like
15288 @command{gcc} are common.  Posix 1003.1-2001 specifies the
15289 name @command{c99}, but older Posix editions specified
15290 @command{c89} and anyway these standard names are rarely used in
15291 practice.  Typically the C compiler is invoked from makefiles that use
15292 @samp{$(CC)}, so the value of the @samp{CC} make variable selects the
15293 compiler name.
15296 @item @command{chmod}
15297 @c ------------------
15298 @prindex @command{chmod}
15299 Avoid usages like @samp{chmod -w file}; use @samp{chmod a-w file}
15300 instead, for two reasons.  First, plain @option{-w} does not necessarily
15301 make the file unwritable, since it does not affect mode bits that
15302 correspond to bits in the file mode creation mask.  Second,
15303 Posix says that the @option{-w} might be interpreted as an
15304 implementation-specific option, not as a mode; Posix suggests
15305 using @samp{chmod -- -w file} to avoid this confusion, but unfortunately
15306 @samp{--} does not work on some older hosts.
15309 @item @command{cmp}
15310 @c ----------------
15311 @prindex @command{cmp}
15312 @command{cmp} performs a raw data comparison of two files, while
15313 @command{diff} compares two text files.  Therefore, if you might compare
15314 DOS files, even if only checking whether two files are different, use
15315 @command{diff} to avoid spurious differences due to differences of
15316 newline encoding.
15319 @item @command{cp}
15320 @c ---------------
15321 @prindex @command{cp}
15322 Avoid the @option{-r} option, since Posix 1003.1-2004 marks it as
15323 obsolescent and its behavior on special files is implementation-defined.
15324 Use @option{-R} instead.  On @acronym{GNU} hosts the two options
15325 are equivalent, but on Solaris hosts (for example) @code{cp -r}
15326 reads from pipes instead of replicating them.
15328 Some @command{cp} implementations (e.g., @acronym{BSD/OS} 4.2) do not allow
15329 trailing slashes at the end of nonexistent destination directories.  To
15330 avoid this problem, omit the trailing slashes.  For example, use
15331 @samp{cp -R source /tmp/newdir} rather than @samp{cp -R source
15332 /tmp/newdir/} if @file{/tmp/newdir} does not exist.
15334 @c This is thanks to Ian.
15335 The ancient SunOS 4 @command{cp} does not support @option{-f}, although
15336 its @command{mv} does.
15338 @cindex timestamp resolution
15339 Traditionally, file timestamps had 1-second resolution, and @samp{cp
15340 -p} copied the timestamps exactly.  However, many modern file systems
15341 have timestamps with 1-nanosecond resolution.  Unfortunately, @samp{cp
15342 -p} implementations truncate timestamps when copying files, so this
15343 can result in the destination file appearing to be older than the
15344 source.  The exact amount of truncation depends on the resolution of
15345 the system calls that @command{cp} uses; traditionally this was
15346 @code{utime}, which has 1-second resolution, but some newer
15347 @command{cp} implementations use @code{utimes}, which has
15348 1-microsecond resolution.  These newer implementations include @acronym{GNU}
15349 Core Utilities 5.0.91 or later, and Solaris 8 (sparc) patch 109933-02 or
15350 later.  Unfortunately as of January 2006 there is still no system
15351 call to set timestamps to the full nanosecond resolution.
15353 Bob Proulx notes that @samp{cp -p} always @emph{tries} to copy
15354 ownerships.  But whether it actually does copy ownerships or not is a
15355 system dependent policy decision implemented by the kernel.  If the
15356 kernel allows it then it happens.  If the kernel does not allow it then
15357 it does not happen.  It is not something @command{cp} itself has control
15358 over.
15360 In Unix System V any user can chown files to any other user, and System
15361 V also has a non-sticky @file{/tmp}.  That probably derives from the
15362 heritage of System V in a business environment without hostile users.
15363 @acronym{BSD} changed this
15364 to be a more secure model where only root can @command{chown} files and
15365 a sticky @file{/tmp} is used.  That undoubtedly derives from the heritage
15366 of @acronym{BSD} in a campus environment.
15368 @acronym{GNU}/Linux and Solaris by default follow @acronym{BSD}, but
15369 can be configured to allow a System V style @command{chown}.  On the
15370 other hand, @acronym{HP-UX} follows System V, but can
15371 be configured to use the modern security model and disallow
15372 @command{chown}.  Since it is an administrator-configurable parameter
15373 you can't use the name of the kernel as an indicator of the behavior.
15377 @item @command{date}
15378 @c -----------------
15379 @prindex @command{date}
15380 Some versions of @command{date} do not recognize special @samp{%} directives,
15381 and unfortunately, instead of complaining, they just pass them through,
15382 and exit with success:
15384 @example
15385 $ @kbd{uname -a}
15386 OSF1 medusa.sis.pasteur.fr V5.1 732 alpha
15387 $ @kbd{date "+%s"}
15389 @end example
15392 @item @command{diff}
15393 @c -----------------
15394 @prindex @command{diff}
15395 Option @option{-u} is nonportable.
15397 Some implementations, such as Tru64's, fail when comparing to
15398 @file{/dev/null}.  Use an empty file instead.
15401 @item @command{dirname}
15402 @c --------------------
15403 @prindex @command{dirname}
15404 Not all hosts have a working @command{dirname}, and you should instead
15405 use @code{AS_DIRNAME} (@pxref{Programming in M4sh}).  For example:
15407 @example
15408 dir=`dirname "$file"`       # This is not portable.
15409 dir=`AS_DIRNAME(["$file"])` # This is more portable.
15410 @end example
15413 @item @command{egrep}
15414 @c ------------------
15415 @prindex @command{egrep}
15416 Posix 1003.1-2001 no longer requires @command{egrep},
15417 but many hosts do not yet support the Posix
15418 replacement @code{grep -E}.  Also, some traditional implementations do
15419 not work on long input lines.  To work around these problems, invoke
15420 @code{AC_PROG_EGREP} and then use @code{$EGREP}.
15422 Portable extended regular expressions should use @samp{\} only to escape
15423 characters in the string @samp{$()*+.?[\^@{|}.  For example, @samp{\@}}
15424 is not portable, even though it typically matches @samp{@}}.
15426 The empty alternative is not portable.  Use @samp{?} instead.  For
15427 instance with Digital Unix v5.0:
15429 @example
15430 > printf "foo\n|foo\n" | $EGREP '^(|foo|bar)$'
15431 |foo
15432 > printf "bar\nbar|\n" | $EGREP '^(foo|bar|)$'
15433 bar|
15434 > printf "foo\nfoo|\n|bar\nbar\n" | $EGREP '^(foo||bar)$'
15436 |bar
15437 @end example
15439 @command{$EGREP} also suffers the limitations of @command{grep}.
15441 @item @command{expr}
15442 @c -----------------
15443 @prindex @command{expr}
15444 No @command{expr} keyword starts with @samp{X}, so use @samp{expr
15445 X"@var{word}" : 'X@var{regex}'} to keep @command{expr} from
15446 misinterpreting @var{word}.
15448 Don't use @code{length}, @code{substr}, @code{match} and @code{index}.
15450 @item @command{expr} (@samp{|})
15451 @prindex @command{expr} (@samp{|})
15452 You can use @samp{|}.  Although Posix does require that @samp{expr
15453 ''} return the empty string, it does not specify the result when you
15454 @samp{|} together the empty string (or zero) with the empty string.  For
15455 example:
15457 @example
15458 expr '' \| ''
15459 @end example
15461 Posix 1003.2-1992 returns the empty string
15462 for this case, but traditional Unix returns @samp{0} (Solaris is
15463 one such example).  In Posix 1003.1-2001, the specification was
15464 changed to match traditional Unix's behavior (which is
15465 bizarre, but it's too late to fix this).  Please note that the same
15466 problem does arise when the empty string results from a computation,
15467 as in:
15469 @example
15470 expr bar : foo \| foo : bar
15471 @end example
15473 @noindent
15474 Avoid this portability problem by avoiding the empty string.
15477 @item @command{expr} (@samp{:})
15478 @c ----------------------------
15479 @prindex @command{expr}
15480 Portable @command{expr} regular expressions should use @samp{\} to
15481 escape only characters in the string @samp{$()*.0123456789[\^n@{@}}.
15482 For example, alternation, @samp{\|}, is common but Posix does not
15483 require its support, so it should be avoided in portable scripts.
15484 Similarly, @samp{\+} and @samp{\?} should be avoided.
15486 Portable @command{expr} regular expressions should not begin with
15487 @samp{^}.  Patterns are automatically anchored so leading @samp{^} is
15488 not needed anyway.
15490 The Posix standard is ambiguous as to whether
15491 @samp{expr 'a' : '\(b\)'} outputs @samp{0} or the empty string.
15492 In practice, it outputs the empty string on most platforms, but portable
15493 scripts should not assume this.  For instance, the @acronym{QNX} 4.25 native
15494 @command{expr} returns @samp{0}.
15496 One might think that a way to get a uniform behavior would be to use
15497 the empty string as a default value:
15499 @example
15500 expr a : '\(b\)' \| ''
15501 @end example
15503 @noindent
15504 Unfortunately this behaves exactly as the original expression; see the
15505 @command{expr} (@samp{|}) entry for more information.
15507 Some ancient @command{expr} implementations (e.g., SunOS 4 @command{expr} and
15508 Solaris 8 @command{/usr/ucb/expr}) have a silly length limit that causes
15509 @command{expr} to fail if the matched substring is longer than 120
15510 bytes.  In this case, you might want to fall back on @samp{echo|sed} if
15511 @command{expr} fails.  Nowadays this is of practical importance only for
15512 the rare installer who mistakenly puts @file{/usr/ucb} before
15513 @file{/usr/bin} in @env{PATH}.
15515 On Mac OS X 10.4, @command{expr} mishandles the pattern @samp{[^-]} in
15516 some cases.  For example, the command
15517 @example
15518 expr Xpowerpc-apple-darwin8.1.0 : 'X[^-]*-[^-]*-\(.*\)'
15519 @end example
15521 @noindent
15522 outputs @samp{apple-darwin8.1.0} rather than the correct @samp{darwin8.1.0}.
15523 This particular case can be worked around by substituting @samp{[^--]}
15524 for @samp{[^-]}.
15526 Don't leave, there is some more!
15528 The @acronym{QNX} 4.25 @command{expr}, in addition of preferring @samp{0} to
15529 the empty string, has a funny behavior in its exit status: it's always 1
15530 when parentheses are used!
15532 @example
15533 $ @kbd{val=`expr 'a' : 'a'`; echo "$?: $val"}
15534 0: 1
15535 $ @kbd{val=`expr 'a' : 'b'`; echo "$?: $val"}
15536 1: 0
15538 $ @kbd{val=`expr 'a' : '\(a\)'`; echo "?: $val"}
15539 1: a
15540 $ @kbd{val=`expr 'a' : '\(b\)'`; echo "?: $val"}
15541 1: 0
15542 @end example
15544 @noindent
15545 In practice this can be a big problem if you are ready to catch failures
15546 of @command{expr} programs with some other method (such as using
15547 @command{sed}), since you may get twice the result.  For instance
15549 @example
15550 $ @kbd{expr 'a' : '\(a\)' || echo 'a' | sed 's/^\(a\)$/\1/'}
15551 @end example
15553 @noindent
15554 outputs @samp{a} on most hosts, but @samp{aa} on @acronym{QNX} 4.25.  A
15555 simple workaround consists of testing @command{expr} and using a variable
15556 set to @command{expr} or to @command{false} according to the result.
15558 Tru64 @command{expr} incorrectly treats the result as a number, if it
15559 can be interpreted that way:
15561 @example
15562 $ @kbd{expr 00001 : '.*\(...\)'}
15564 @end example
15567 @item @command{fgrep}
15568 @c ------------------
15569 @prindex @command{fgrep}
15570 Posix 1003.1-2001 no longer requires @command{fgrep},
15571 but many hosts do not yet support the Posix
15572 replacement @code{grep -F}.  Also, some traditional implementations do
15573 not work on long input lines.  To work around these problems, invoke
15574 @code{AC_PROG_FGREP} and then use @code{$FGREP}.
15577 @item @command{find}
15578 @c -----------------
15579 @prindex @command{find}
15580 The option @option{-maxdepth} seems to be @acronym{GNU} specific.
15581 Tru64 v5.1, Net@acronym{BSD} 1.5 and Solaris @command{find}
15582 commands do not understand it.
15584 The replacement of @samp{@{@}} is guaranteed only if the argument is
15585 exactly @emph{@{@}}, not if it's only a part of an argument.  For
15586 instance on DU, and @acronym{HP-UX} 10.20 and @acronym{HP-UX} 11:
15588 @example
15589 $ @kbd{touch foo}
15590 $ @kbd{find . -name foo -exec echo "@{@}-@{@}" \;}
15591 @{@}-@{@}
15592 @end example
15594 @noindent
15595 while @acronym{GNU} @command{find} reports @samp{./foo-./foo}.
15598 @item @command{grep}
15599 @c -----------------
15600 @prindex @command{grep}
15601 Portable scripts can rely on the @command{grep} options @option{-c},
15602 @option{-l}, @option{-n}, and @option{-v}, but should avoid other
15603 options.  For example, don't use @option{-w}, as Posix does not require
15604 it and Irix 6.5.16m's @command{grep} does not support it.  Also,
15605 portable scripts should not combine @option{-c} with @option{-l},
15606 as Posix does not allow this.
15608 Some of the options required by Posix are not portable in practice.
15609 Don't use @samp{grep -q} to suppress output, because many @command{grep}
15610 implementations (e.g., Solaris) do not support @option{-q}.
15611 Don't use @samp{grep -s} to suppress output either, because Posix
15612 says @option{-s} does not suppress output, only some error messages;
15613 also, the @option{-s} option of traditional @command{grep} behaved
15614 like @option{-q} does in most modern implementations.  Instead,
15615 redirect the standard output and standard error (in case the file
15616 doesn't exist) of @code{grep} to @file{/dev/null}.  Check the exit
15617 status of @code{grep} to determine whether it found a match.
15619 Some traditional @command{grep} implementations do not work on long
15620 input lines.  On AIX the default @code{grep} silently truncates long
15621 lines on the input before matching.
15623 Also, many implementations do not support multiple regexps
15624 with @option{-e}: they either reject @option{-e} entirely (e.g., Solaris)
15625 or honor only the last pattern (e.g., @acronym{IRIX} 6.5 and NeXT).  To
15626 work around these problems, invoke @code{AC_PROG_GREP} and then use
15627 @code{$GREP}.
15629 Another possible workaround for the multiple @option{-e} problem is to
15630 separate the patterns by newlines, for example:
15632 @example
15633 grep 'foo
15634 bar' in.txt
15635 @end example
15637 @noindent
15638 except that this fails with traditional @command{grep}
15639 implementations and with Open@acronym{BSD} 3.8 @command{grep}.
15641 Traditional @command{grep} implementations (e.g., Solaris) do not
15642 support the @option{-E} or @option{-F} options.  To work around these
15643 problems, invoke @code{AC_PROG_EGREP} and then use @code{$EGREP}, and
15644 similarly for @code{AC_PROG_FGREP} and @code{$FGREP}.  Even if you are
15645 willing to require support for Posix @command{grep}, your script should
15646 not use both @option{-E} and @option{-F}, since Posix does not allow
15647 this combination.
15649 Portable @command{grep} regular expressions should use @samp{\} only to
15650 escape characters in the string @samp{$()*.0123456789[\^@{@}}.  For example,
15651 alternation, @samp{\|}, is common but Posix does not require its
15652 support in basic regular expressions, so it should be avoided in
15653 portable scripts.  Solaris and HP-UX @command{grep} do not support it.
15654 Similarly, the following escape sequences should also be avoided:
15655 @samp{\<}, @samp{\>}, @samp{\+}, @samp{\?}, @samp{\`}, @samp{\'},
15656 @samp{\B}, @samp{\b}, @samp{\S}, @samp{\s}, @samp{\W}, and @samp{\w}.
15658 Posix does not specify the behavior of @command{grep} on binary files.
15659 An example where this matters is using @acronym{BSD} @command{grep} to
15660 search text that includes embedded @acronym{ANSI} escape sequences for
15661 colored output to terminals (@samp{\033[m} is the sequence to restore
15662 normal output); the behavior depends on whether input is seekable:
15664 @example
15665 $ @kbd{printf 'esc\033[mape\n' > sample}
15666 $ @kbd{grep . sample}
15667 Binary file sample matches
15668 $ @kbd{cat sample | grep .}
15669 escape
15670 @end example
15673 @item @command{join}
15674 @c -----------------
15675 @prindex @command{join}
15676 Solaris 8 @command{join} has bugs when the second operand is standard
15677 input, and when standard input is a pipe.  For example, the following
15678 shell script causes Solaris 8 @command{join} to loop forever:
15680 @example
15681 cat >file <<'EOF'
15682 1 x
15683 2 y
15685 cat file | join file -
15686 @end example
15688 Use @samp{join - file} instead.
15691 @item @command{ln}
15692 @c ---------------
15693 @prindex @command{ln}
15694 @cindex Symbolic links
15695 Don't rely on @command{ln} having a @option{-f} option.  Symbolic links
15696 are not available on old systems; use @samp{$(LN_S)} as a portable substitute.
15698 For versions of the @acronym{DJGPP} before 2.04,
15699 @command{ln} emulates symbolic links
15700 to executables by generating a stub that in turn calls the real
15701 program.  This feature also works with nonexistent files like in the
15702 Posix spec.  So @samp{ln -s file link} generates @file{link.exe},
15703 which attempts to call @file{file.exe} if run.  But this feature only
15704 works for executables, so @samp{cp -p} is used instead for these
15705 systems.  @acronym{DJGPP} versions 2.04 and later have full support
15706 for symbolic links.
15709 @item @command{ls}
15710 @c ---------------
15711 @prindex @command{ls}
15712 @cindex Listing directories
15713 The portable options are @option{-acdilrtu}.  Current practice is for
15714 @option{-l} to output both owner and group, even though ancient versions
15715 of @command{ls} omitted the group.
15717 On ancient hosts, @samp{ls foo} sent the diagnostic @samp{foo not found}
15718 to standard output if @file{foo} did not exist.  Hence a shell command
15719 like @samp{sources=`ls *.c 2>/dev/null`} did not always work, since it
15720 was equivalent to @samp{sources='*.c not found'} in the absence of
15721 @samp{.c} files.  This is no longer a practical problem, since current
15722 @command{ls} implementations send diagnostics to standard error.
15724 @item @command{mkdir}
15725 @c ------------------
15726 @prindex @command{mkdir}
15727 @cindex Making directories
15728 No @command{mkdir} option is portable to older systems.  Instead of
15729 @samp{mkdir -p @var{file-name}}, you should use
15730 @code{AS_MKDIR_P(@var{file-name})} (@pxref{Programming in M4sh})
15731 or @code{AC_PROG_MKDIR_P} (@pxref{Particular Programs}).
15733 Combining the @option{-m} and @option{-p} options, as in @samp{mkdir -m
15734 go-w -p @var{dir}}, often leads to trouble.  Free@acronym{BSD}
15735 @command{mkdir} incorrectly attempts to change the permissions of
15736 @var{dir} even if it already exists.  @acronym{HP-UX} 11.23 and
15737 @acronym{IRIX} 6.5 @command{mkdir} often assign the wrong permissions to
15738 any newly-created parents of @var{dir}.
15740 Posix does not clearly specify whether @samp{mkdir -p foo}
15741 should succeed when @file{foo} is a symbolic link to an already-existing
15742 directory.  The @acronym{GNU} Core Utilities 5.1.0 @command{mkdir}
15743 succeeds, but Solaris @command{mkdir} fails.
15745 Traditional @code{mkdir -p} implementations suffer from race conditions.
15746 For example, if you invoke @code{mkdir -p a/b} and @code{mkdir -p a/c}
15747 at the same time, both processes might detect that @file{a} is missing,
15748 one might create @file{a}, then the other might try to create @file{a}
15749 and fail with a @code{File exists} diagnostic.  The @acronym{GNU} Core
15750 Utilities (@samp{fileutils} version 4.1), Free@acronym{BSD} 5.0,
15751 Net@acronym{BSD} 2.0.2, and Open@acronym{BSD} 2.4 are known to be
15752 race-free when two processes invoke @code{mkdir -p} simultaneously, but
15753 earlier versions are vulnerable.  Solaris @command{mkdir} is still
15754 vulnerable as of Solaris 10, and other traditional Unix systems are
15755 probably vulnerable too.  This possible race is harmful in parallel
15756 builds when several Make rules call @code{mkdir -p} to
15757 construct directories.  You may use
15758 @code{install-sh -d} as a safe replacement, provided this script is
15759 recent enough; the copy shipped with Autoconf 2.60 and Automake 1.10 is
15760 OK, but copies from older versions are vulnerable.
15763 @item @command{mktemp}
15764 @c -------------------
15765 @prindex @command{mktemp}
15766 @cindex Creating temporary files
15767 Shell scripts can use temporary files safely with @command{mktemp}, but
15768 it does not exist on all systems.  A portable way to create a safe
15769 temporary file name is to create a temporary directory with mode 700 and
15770 use a file inside this directory.  Both methods prevent attackers from
15771 gaining control, though @command{mktemp} is far less likely to fail
15772 gratuitously under attack.
15774 Here is sample code to create a new temporary directory safely:
15776 @example
15777 # Create a temporary directory $tmp in $TMPDIR (default /tmp).
15778 # Use mktemp if possible; otherwise fall back on mkdir,
15779 # with $RANDOM to make collisions less likely.
15780 : $@{TMPDIR=/tmp@}
15782   tmp=`
15783     (umask 077 && mktemp -d "$TMPDIR/fooXXXXXX") 2>/dev/null
15784   ` &&
15785   test -n "$tmp" && test -d "$tmp"
15786 @} || @{
15787   tmp=$TMPDIR/foo$$-$RANDOM
15788   (umask 077 && mkdir "$tmp")
15789 @} || exit $?
15790 @end example
15793 @item @command{mv}
15794 @c ---------------
15795 @prindex @command{mv}
15796 @cindex Moving open files
15797 The only portable options are @option{-f} and @option{-i}.
15799 Moving individual files between file systems is portable (it was in Unix
15800 version 6),
15801 but it is not always atomic: when doing @samp{mv new existing}, there's
15802 a critical section where neither the old nor the new version of
15803 @file{existing} actually exists.
15805 On some systems moving files from @file{/tmp} can sometimes cause
15806 undesirable (but perfectly valid) warnings, even if you created these
15807 files.  This is because @file{/tmp} belongs to a group that ordinary
15808 users are not members of, and files created in @file{/tmp} inherit
15809 the group of @file{/tmp}.  When the file is copied, @command{mv} issues
15810 a diagnostic without failing:
15812 @smallexample
15813 $ @kbd{touch /tmp/foo}
15814 $ @kbd{mv /tmp/foo .}
15815 @error{}mv: ./foo: set owner/group (was: 100/0): Operation not permitted
15816 $ @kbd{echo $?}
15818 $ @kbd{ls foo}
15820 @end smallexample
15822 @noindent
15823 This annoying behavior conforms to Posix, unfortunately.
15825 Moving directories across mount points is not portable, use @command{cp}
15826 and @command{rm}.
15828 @acronym{DOS} variants cannot rename or remove open files, and do not
15829 support commands like @samp{mv foo bar >foo}, even though this is
15830 perfectly portable among Posix hosts.
15833 @item @command{od}
15834 @c ---------------
15835 @prindex @command{od}
15837 In Mac OS X 10.3, @command{od} does not support the
15838 standard Posix options @option{-A}, @option{-j}, @option{-N}, or
15839 @option{-t}, or the @acronym{XSI} option @option{-s}.  The only
15840 supported Posix option is @option{-v}, and the only supported
15841 @acronym{XSI} options are those in @option{-bcdox}.  The @acronym{BSD}
15842 @command{hexdump} program can be used instead.
15844 This problem no longer exists in Mac OS X 10.4.3.
15847 @item @command{rm}
15848 @c ---------------
15849 @prindex @command{rm}
15850 The @option{-f} and @option{-r} options are portable.
15852 It is not portable to invoke @command{rm} without operands.  For
15853 example, on many systems @samp{rm -f -r} (with no other arguments)
15854 silently succeeds without doing anything, but it fails with a diagnostic
15855 on Net@acronym{BSD} 2.0.2.
15857 A file might not be removed even if its parent directory is writable
15858 and searchable.  Many Posix hosts cannot remove a mount point, a named
15859 stream, a working directory, or a last link to a file that is being
15860 executed.
15862 @acronym{DOS} variants cannot rename or remove open files, and do not
15863 support commands like @samp{rm foo >foo}, even though this is
15864 perfectly portable among Posix hosts.
15867 @item @command{sed}
15868 @c ----------------
15869 @prindex @command{sed}
15870 Patterns should not include the separator (unless escaped), even as part
15871 of a character class.  In conformance with Posix, the Cray
15872 @command{sed} rejects @samp{s/[^/]*$//}: use @samp{s,[^/]*$,,}.
15874 Avoid empty patterns within parentheses (i.e., @samp{\(\)}).  Posix does
15875 not require support for empty patterns, and Unicos 9 @command{sed} rejects
15876 them.
15878 Unicos 9 @command{sed} loops endlessly on patterns like @samp{.*\n.*}.
15880 Sed scripts should not use branch labels longer than 7 characters and
15881 should not contain comments.  @acronym{HP-UX} sed has a limit of 99 commands
15882 (not counting @samp{:} commands) and
15883 48 labels, which can not be circumvented by using more than one script
15884 file.  It can execute up to 19 reads with the @samp{r} command per cycle.
15885 Solaris @command{/usr/ucb/sed} rejects usages that exceed an limit of
15886 about 6000 bytes for the internal representation of commands.
15888 Avoid redundant @samp{;}, as some @command{sed} implementations, such as
15889 Net@acronym{BSD} 1.4.2's, incorrectly try to interpret the second
15890 @samp{;} as a command:
15892 @example
15893 $ @kbd{echo a | sed 's/x/x/;;s/x/x/'}
15894 sed: 1: "s/x/x/;;s/x/x/": invalid command code ;
15895 @end example
15897 Input should not have unreasonably long lines, since some @command{sed}
15898 implementations have an input buffer limited to 4000 bytes.  Likewise,
15899 not all @command{sed} implementations can handle embedded @code{NUL} or
15900 a missing trailing newline.
15902 Portable @command{sed} regular expressions should use @samp{\} only to escape
15903 characters in the string @samp{$()*.0123456789[\^n@{@}}.  For example,
15904 alternation, @samp{\|}, is common but Posix does not require its
15905 support, so it should be avoided in portable scripts.  Solaris
15906 @command{sed} does not support alternation; e.g., @samp{sed '/a\|b/d'}
15907 deletes only lines that contain the literal string @samp{a|b}.
15908 Similarly, @samp{\+} and @samp{\?} should be avoided.
15910 Anchors (@samp{^} and @samp{$}) inside groups are not portable.
15912 Nested parentheses in patterns (e.g., @samp{\(\(a*\)b*)\)}) are
15913 quite portable to current hosts, but was not supported by some ancient
15914 @command{sed} implementations like SVR3.
15916 Some @command{sed} implementations, e.g., Solaris,
15917 restrict the special role of the asterisk to one-character regular expressions.
15918 This may lead to unexpected behavior:
15920 @example
15921 $ @kbd{echo '1*23*4' | /usr/bin/sed 's/\(.\)*/x/g'}
15922 x2x4
15923 $ @kbd{echo '1*23*4' | /usr/xpg4/bin/sed 's/\(.\)*/x/g'}
15925 @end example
15927 The @option{-e} option is mostly portable.
15928 However, its argument
15929 cannot start with @samp{a}, @samp{c}, or @samp{i},
15930 as this runs afoul of a Tru64 5.1 bug.
15931 Also, its argument cannot be empty, as this fails on @acronym{AIX} 5.3.
15932 Some people prefer to use @samp{-e}:
15934 @example
15935 sed -e '@var{command-1}' \
15936     -e '@var{command-2}'
15937 @end example
15939 @noindent
15940 as opposed to the equivalent:
15942 @example
15943 sed '
15944   @var{command-1}
15945   @var{command-2}
15947 @end example
15949 @noindent
15950 The following usage is sometimes equivalent:
15952 @example
15953 sed '@var{command-1};@var{command-2}'
15954 @end example
15956 but Posix says that this use of a semicolon has undefined effect if
15957 @var{command-1}'s verb is @samp{@{}, @samp{a}, @samp{b}, @samp{c},
15958 @samp{i}, @samp{r}, @samp{t}, @samp{w}, @samp{:}, or @samp{#}, so you
15959 should use semicolon only with simple scripts that do not use these
15960 verbs.
15962 Commands inside @{ @} brackets are further restricted.  Posix says that
15963 they cannot be preceded by addresses, @samp{!}, or @samp{;}, and that
15964 each command must be followed immediately by a newline, without any
15965 intervening blanks or semicolons.  The closing bracket must be alone on
15966 a line, other than white space preceding or following it.
15968 Contrary to yet another urban legend, you may portably use @samp{&} in
15969 the replacement part of the @code{s} command to mean ``what was
15970 matched''.  All descendants of Unix version 7 @command{sed}
15971 (at least; we
15972 don't have first hand experience with older @command{sed} implementations) have
15973 supported it.
15975 Posix requires that you must not have any white space between
15976 @samp{!} and the following command.  It is OK to have blanks between
15977 the address and the @samp{!}.  For instance, on Solaris:
15979 @example
15980 $ @kbd{echo "foo" | sed -n '/bar/ ! p'}
15981 @error{}Unrecognized command: /bar/ ! p
15982 $ @kbd{echo "foo" | sed -n '/bar/! p'}
15983 @error{}Unrecognized command: /bar/! p
15984 $ @kbd{echo "foo" | sed -n '/bar/ !p'}
15986 @end example
15988 Posix also says that you should not combine @samp{!} and @samp{;}.  If
15989 you use @samp{!}, it is best to put it on a command that is delimited by
15990 newlines rather than @samp{;}.
15992 Also note that Posix requires that the @samp{b}, @samp{t}, @samp{r}, and
15993 @samp{w} commands be followed by exactly one space before their argument.
15994 On the other hand, no white space is allowed between @samp{:} and the
15995 subsequent label name.
15997 If a sed script is specified on the command line and ends in an
15998 @samp{a}, @samp{c}, or @samp{i} command, the last line of inserted text
15999 should be followed by a newline.  Otherwise some @command{sed}
16000 implementations (e.g., Open@acronym{BSD} 3.9) do not append a newline to the
16001 inserted text.
16003 Many @command{sed} implementations (e.g., MacOS X 10.4,
16004 Open@acronym{BSD} 3.9, Solaris 10
16005 @command{/usr/ucb/sed}) strip leading white space from the text of
16006 @samp{a}, @samp{c}, and @samp{i} commands.  Prepend a backslash to
16007 work around this incompatibility with Posix:
16009 @example
16010 $ @kbd{echo flushleft | sed 'a\}
16011 > @kbd{   indented}
16012 > @kbd{'}
16013 flushleft
16014 indented
16015 $ @kbd{echo foo | sed 'a\}
16016 > @kbd{\   indented}
16017 > @kbd{'}
16018 flushleft
16019    indented
16020 @end example
16022 Posix requires that with an empty regular expression, the last non-empty
16023 regular expression from either an address specification or substitution
16024 command is applied.  However, busybox 1.6.1 complains when using a
16025 substitution command with a replacement containing a back-reference to
16026 an empty regular expression; the workaround is repeating the regular
16027 expression.
16029 @example
16030 $ @kbd{echo abc | busybox sed '/a\(b\)c/ s//\1/'}
16031 sed: No previous regexp.
16032 $ @kbd{echo abc | busybox sed '/a\(b\)c/ s/a\(b\)c/\1/'}
16034 @end example
16037 @item @command{sed} (@samp{t})
16038 @c ---------------------------
16039 @prindex @command{sed} (@samp{t})
16040 Some old systems have @command{sed} that ``forget'' to reset their
16041 @samp{t} flag when starting a new cycle.  For instance on @acronym{MIPS
16042 RISC/OS}, and on @sc{irix} 5.3, if you run the following @command{sed}
16043 script (the line numbers are not actual part of the texts):
16045 @example
16046 s/keep me/kept/g  # a
16047 t end             # b
16048 s/.*/deleted/g    # c
16049 :end              # d
16050 @end example
16052 @noindent
16055 @example
16056 delete me         # 1
16057 delete me         # 2
16058 keep me           # 3
16059 delete me         # 4
16060 @end example
16062 @noindent
16063 you get
16065 @example
16066 deleted
16067 delete me
16068 kept
16069 deleted
16070 @end example
16072 @noindent
16073 instead of
16075 @example
16076 deleted
16077 deleted
16078 kept
16079 deleted
16080 @end example
16082 Why?  When processing line 1, (c) matches, therefore sets the @samp{t}
16083 flag, and the output is produced.  When processing
16084 line 2, the @samp{t} flag is still set (this is the bug).  Command (a)
16085 fails to match, but @command{sed} is not supposed to clear the @samp{t}
16086 flag when a substitution fails.  Command (b) sees that the flag is set,
16087 therefore it clears it, and jumps to (d), hence you get @samp{delete me}
16088 instead of @samp{deleted}.  When processing line (3), @samp{t} is clear,
16089 (a) matches, so the flag is set, hence (b) clears the flags and jumps.
16090 Finally, since the flag is clear, line 4 is processed properly.
16092 There are two things one should remember about @samp{t} in @command{sed}.
16093 Firstly, always remember that @samp{t} jumps if @emph{some} substitution
16094 succeeded, not only the immediately preceding substitution.  Therefore,
16095 always use a fake @samp{t clear} followed by a @samp{:clear} on the next
16096 line, to reset the @samp{t} flag where needed.
16098 Secondly, you cannot rely on @command{sed} to clear the flag at each new
16099 cycle.
16101 One portable implementation of the script above is:
16103 @example
16104 t clear
16105 :clear
16106 s/keep me/kept/g
16107 t end
16108 s/.*/deleted/g
16109 :end
16110 @end example
16112 @item @command{touch}
16113 @c ------------------
16114 @prindex @command{touch}
16115 @cindex timestamp resolution
16116 If you specify the desired timestamp (e.g., with the @option{-r}
16117 option), @command{touch} typically uses the @code{utime} or
16118 @code{utimes} system call, which can result in the same kind of
16119 timestamp truncation problems that @samp{cp -p} has.
16121 On ancient @acronym{BSD} systems, @command{touch} or any command that
16122 results in an empty file does not update the timestamps, so use a
16123 command like @command{echo} as a workaround.
16124 Also,
16125 @acronym{GNU} @command{touch} 3.16r (and presumably all before that)
16126 fails to work on SunOS 4.1.3 when the empty file is on an
16127 @acronym{NFS}-mounted 4.2 volume.
16128 However, these problems are no longer of practical concern.
16130 @item @command{tr}
16131 @c ---------------
16132 @prindex @command{tr}
16133 @cindex carriage return, deleting
16134 @cindex deleting carriage return
16135 Not all versions of @command{tr} handle all backslash character escapes.
16136 For example, Solaris 10 @command{/usr/ucb/tr} falls over, even though
16137 Solaris contains more modern @command{tr} in other locations.
16138 Therefore, it is more portable to use octal escapes, even though this
16139 ties the result to @acronym{ASCII}, when using @command{tr} to delete
16140 newlines or carriage returns.
16142 @example
16143 $ @kbd{@{ echo moon; echo light; @} | /usr/ucb/tr -d '\n' ; echo}
16145 light
16146 $ @kbd{@{ echo moon; echo light; @} | /usr/bin/tr -d '\n' ; echo}
16147 moonlight
16148 $ @kbd{@{ echo moon; echo light; @} | /usr/ucb/tr -d '\012' ; echo}
16149 moonlight
16150 @end example
16152 Posix requires @command{tr} to operate on binary files.  But at least
16153 Solaris @command{/usr/ucb/tr} still fails to handle @samp{\0} as the
16154 octal escape for @code{NUL}.  On Solaris, when using @command{tr} to
16155 neutralize a binary file by converting @code{NUL} to a different
16156 character, it is necessary to use @command{/usr/xpg4/bin/tr} instead.
16158 @example
16159 $ @kbd{printf 'a\0b\n' | /usr/ucb/tr '\0' '~' | wc -c}
16161 $ @kbd{printf 'a\0b\n' | /usr/xpg4/bin/tr '\0' '~' | wc -c}
16163 @end example
16165 @end table
16168 @node Portable Make
16169 @chapter Portable Make Programming
16170 @prindex @command{make}
16171 @cindex Limitations of @command{make}
16173 Writing portable makefiles is an art.  Since a makefile's commands are
16174 executed by the shell, you must consider the shell portability issues
16175 already mentioned.  However, other issues are specific to @command{make}
16176 itself.
16178 @menu
16179 * $< in Ordinary Make Rules::   $< in ordinary rules
16180 * Failure in Make Rules::       Failing portably in rules
16181 * Special Chars in Names::      Special Characters in Macro Names
16182 * Backslash-Newline-Newline::   Empty last lines in macro definitions
16183 * Backslash-Newline Comments::  Spanning comments across line boundaries
16184 * Long Lines in Makefiles::     Line length limitations
16185 * Macros and Submakes::         @code{make macro=value} and submakes
16186 * The Make Macro MAKEFLAGS::    @code{$(MAKEFLAGS)} portability issues
16187 * The Make Macro SHELL::        @code{$(SHELL)} portability issues
16188 * Comments in Make Rules::      Other problems with Make comments
16189 * obj/ and Make::               Don't name a subdirectory @file{obj}
16190 * make -k Status::              Exit status of @samp{make -k}
16191 * VPATH and Make::              @code{VPATH} woes
16192 * Single Suffix Rules::         Single suffix rules and separated dependencies
16193 * Timestamps and Make::         Subsecond timestamp resolution
16194 @end menu
16196 @node $< in Ordinary Make Rules
16197 @section @code{$<} in Ordinary Make Rules
16199 Posix says that the @samp{$<} construct in makefiles can be
16200 used only in inference rules and in the @samp{.DEFAULT} rule; its
16201 meaning in ordinary rules is unspecified.  Solaris @command{make}
16202 for instance replaces it with the empty string.  Open@acronym{BSD} (3.0 and
16203 later) @command{make} diagnoses these uses and errors out.
16205 @node Failure in Make Rules
16206 @section Failure in Make Rules
16208 Since 1992 Posix has required that @command{make} must invoke
16209 each command with the equivalent of a @samp{sh -c} subshell.  However,
16210 many @command{make} implementations, including @acronym{BSD} make through 2004,
16211 use @samp{sh -e -c} instead, and the @option{-e} option causes the
16212 subshell to exit immediately if a subsidiary simple-command fails.  For
16213 example, the command @samp{touch T; rm -f U} always attempts to
16214 remove @file{U} with Posix make, but incompatible
16215 @command{make} implementations skip the @command{rm} if the
16216 @command{touch} fails.  One way to work around this is to reword the
16217 affected simple-commands so that they always succeed, e.g., @samp{touch
16218 T || :; rm -f U}.
16219 However, even this approach can run into common bugs in @acronym{BSD}
16220 implementations of the @option{-e} option of @command{sh} and
16221 @command{set} (@pxref{Limitations of Builtins}), so if you are worried
16222 about porting to buggy @acronym{BSD} shells it may be simpler to migrate
16223 complicated @command{make} actions into separate scripts.
16225 @node Special Chars in Names
16226 @section Special Characters in Make Macro Names
16228 Posix limits macro names to nonempty strings containing only
16229 @acronym{ASCII} letters and digits, @samp{.}, and @samp{_}.  Many
16230 @command{make} implementations allow a wider variety of characters, but
16231 portable makefiles should avoid them.  It is portable to start a name
16232 with a special character, e.g., @samp{$(.FOO)}.
16234 Some ancient @command{make} implementations don't support leading
16235 underscores in macro names.  An example is @acronym{NEWS-OS} 4.2R.
16237 @example
16238 $ @kbd{cat Makefile}
16239 _am_include = #
16240 _am_quote =
16241 all:; @@echo this is test
16242 $ @kbd{make}
16243 Make: Must be a separator on rules line 2.  Stop.
16244 $ @kbd{cat Makefile2}
16245 am_include = #
16246 am_quote =
16247 all:; @@echo this is test
16248 $ @kbd{make -f Makefile2}
16249 this is test
16250 @end example
16252 @noindent
16253 However, this problem is no longer of practical concern.
16255 @node Backslash-Newline-Newline
16256 @section Backslash-Newline-Newline in Make Macro Values
16258 @c  This has been seen on ia64 hpux 11.20, and on one hppa hpux 10.20,
16259 @c  but another hppa hpux 10.20 didn't have it.  Bob Proulx
16260 @c  <bob@proulx.com> thinks it was in hpux 8.0 too.
16261 On some versions of @acronym{HP-UX}, @command{make} reads multiple newlines
16262 following a backslash, continuing to the next non-empty line.  For
16263 example,
16265 @example
16266 FOO = one \
16268 BAR = two
16270 test:
16271         : FOO is "$(FOO)"
16272         : BAR is "$(BAR)"
16273 @end example
16275 @noindent
16276 shows @code{FOO} equal to @code{one BAR = two}.  Other implementations
16277 sensibly let a backslash continue only to the immediately following
16278 line.
16280 @node Backslash-Newline Comments
16281 @section Backslash-Newline in Make Comments
16283 According to Posix, Make comments start with @code{#}
16284 and continue until an unescaped newline is reached.
16286 @example
16287 $ @kbd{cat Makefile}
16288 # A = foo \
16289       bar \
16290       baz
16292 all:
16293         @@echo ok
16294 $ @kbd{make}   # GNU make
16296 @end example
16298 @noindent
16299 However this is not always the case.  Some implementations
16300 discard everything from @code{#} through the end of the line, ignoring any
16301 trailing backslash.
16303 @example
16304 $ @kbd{pmake}  # BSD make
16305 "Makefile", line 3: Need an operator
16306 Fatal errors encountered -- cannot continue
16307 @end example
16309 @noindent
16310 Therefore, if you want to comment out a multi-line definition, prefix each
16311 line with @code{#}, not only the first.
16313 @example
16314 # A = foo \
16315 #     bar \
16316 #     baz
16317 @end example
16319 @node Long Lines in Makefiles
16320 @section Long Lines in Makefiles
16322 Tru64 5.1's @command{make} has been reported to crash when given a
16323 makefile with lines longer than around 20 kB.  Earlier versions are
16324 reported to exit with @code{Line too long} diagnostics.
16326 @node Macros and Submakes
16327 @section @code{make macro=value} and Submakes
16329 A command-line variable definition such as @code{foo=bar} overrides any
16330 definition of @code{foo} in a makefile.  Some @command{make}
16331 implementations (such as @acronym{GNU} @command{make}) propagate this
16332 override to subsidiary invocations of @command{make}.  Some other
16333 implementations do not pass the substitution along to submakes.
16335 @example
16336 $ @kbd{cat Makefile}
16337 foo = foo
16338 one:
16339         @@echo $(foo)
16340         $(MAKE) two
16341 two:
16342         @@echo $(foo)
16343 $ @kbd{make foo=bar}            # GNU make 3.79.1
16345 make two
16346 make[1]: Entering directory `/home/adl'
16348 make[1]: Leaving directory `/home/adl'
16349 $ @kbd{pmake foo=bar}           # BSD make
16351 pmake two
16353 @end example
16355 You have a few possibilities if you do want the @code{foo=bar} override
16356 to propagate to submakes.  One is to use the @option{-e}
16357 option, which causes all environment variables to have precedence over
16358 the makefile macro definitions, and declare foo as an environment
16359 variable:
16361 @example
16362 $ @kbd{env foo=bar make -e}
16363 @end example
16365 The @option{-e} option is propagated to submakes automatically,
16366 and since the environment is inherited between @command{make}
16367 invocations, the @code{foo} macro is overridden in
16368 submakes as expected.
16370 This syntax (@code{foo=bar make -e}) is portable only when used
16371 outside of a makefile, for instance from a script or from the
16372 command line.  When run inside a @command{make} rule, @acronym{GNU}
16373 @command{make} 3.80 and prior versions forget to propagate the
16374 @option{-e} option to submakes.
16376 Moreover, using @option{-e} could have unexpected side effects if your
16377 environment contains some other macros usually defined by the
16378 makefile.  (See also the note about @code{make -e} and @code{SHELL}
16379 below.)
16381 Another way to propagate overrides to submakes is to do it
16382 manually, from your makefile:
16384 @example
16385 foo = foo
16386 one:
16387         @@echo $(foo)
16388         $(MAKE) foo=$(foo) two
16389 two:
16390         @@echo $(foo)
16391 @end example
16393 You need to foresee all macros that a user might want to override if
16394 you do that.
16396 @node The Make Macro MAKEFLAGS
16397 @section The Make Macro MAKEFLAGS
16398 @cindex @code{MAKEFLAGS} and @command{make}
16399 @cindex @command{make} and @code{MAKEFLAGS}
16401 Posix requires @command{make} to use @code{MAKEFLAGS} to affect the
16402 current and recursive invocations of make, but allows implementations
16403 several formats for the variable.  It is tricky to parse
16404 @code{$MAKEFLAGS} to determine whether @option{-s} for silent execution
16405 or @option{-k} for continued execution are in effect.  For example, you
16406 cannot assume that the first space-separated word in @code{$MAKEFLAGS}
16407 contains single-letter options, since in the Cygwin version of
16408 @acronym{GNU} @command{make} it is either @option{--unix} or
16409 @option{--win32} with the second word containing single-letter options.
16411 @example
16412 $ @kbd{cat Makefile}
16413 all:
16414         @@echo MAKEFLAGS = $(MAKEFLAGS)
16415 $ @kbd{make}
16416 MAKEFLAGS = --unix
16417 $ @kbd{make -k}
16418 MAKEFLAGS = --unix -k
16419 @end example
16421 @node The Make Macro SHELL
16422 @section The Make Macro @code{SHELL}
16423 @cindex @code{SHELL} and @command{make}
16424 @cindex @command{make} and @code{SHELL}
16426 Posix-compliant @command{make} internally uses the @code{$(SHELL)}
16427 macro to spawn shell processes and execute Make rules.  This
16428 is a builtin macro supplied by @command{make}, but it can be modified
16429 by a makefile or by a command-line argument.
16431 Not all @command{make} implementations define this @code{SHELL} macro.
16432 Tru64
16433 @command{make} is an example; this implementation always uses
16434 @code{/bin/sh}.  So it's a good idea to always define @code{SHELL} in
16435 your makefiles.  If you use Autoconf, do
16437 @example
16438 SHELL = @@SHELL@@
16439 @end example
16441 @noindent
16442 If you use Automake, this is done for you.
16444 Do not force @code{SHELL = /bin/sh} because that is not correct
16445 everywhere.  Remember, @file{/bin/sh} is not Posix compliant on many
16446 systems, such as FreeBSD 4, NetBSD 3, AIX 3, Solaris 10, or Tru64.
16447 Additionally, @acronym{DJGPP} lacks @code{/bin/sh}, and when its
16448 @acronym{GNU} @command{make} port sees such a setting it enters a
16449 special emulation mode where features like pipes and redirections are
16450 emulated on top of DOS's @command{command.com}.  Unfortunately this
16451 emulation is incomplete; for instance it does not handle command
16452 substitutions.  Using @code{@@SHELL@@} means that your makefile will
16453 benefit from the same improved shell, such as @command{bash} or
16454 @command{ksh}, that was discovered during @command{configure}, so that
16455 you aren't fighting two different sets of shell bugs between the two
16456 contexts.
16458 Posix-compliant @command{make} should never acquire the value of
16459 $(SHELL) from the environment, even when @code{make -e} is used
16460 (otherwise, think about what would happen to your rules if
16461 @code{SHELL=/bin/tcsh}).
16463 However not all @command{make} implementations have this exception.
16464 For instance it's not surprising that Tru64 @command{make} doesn't
16465 protect @code{SHELL}, since it doesn't use it.
16467 @example
16468 $ @kbd{cat Makefile}
16469 SHELL = /bin/sh
16470 FOO = foo
16471 all:
16472         @@echo $(SHELL)
16473         @@echo $(FOO)
16474 $ @kbd{env SHELL=/bin/tcsh FOO=bar make -e}   # Tru64 Make
16475 /bin/tcsh
16477 $ @kbd{env SHELL=/bin/tcsh FOO=bar gmake -e}  # GNU make
16478 /bin/sh
16480 @end example
16482 Conversely, @command{make} is not supposed to export any changes to the
16483 macro @code{SHELL} to child processes.  Again, many implementations
16484 break this rule:
16486 @example
16487 $ @kbd{cat Makefile}
16488 all:
16489         @@echo $(SHELL)
16490         @@printenv SHELL
16491 $ @kbd{env SHELL=sh make -e SHELL=/bin/ksh}   # BSD Make, GNU make 3.80
16492 /bin/ksh
16493 /bin/ksh
16494 $ @kbd{env SHELL=sh gmake -e SHELL=/bin/ksh}  # GNU make 3.81
16495 /bin/ksh
16497 @end example
16499 @node Comments in Make Rules
16500 @section Comments in Make Rules
16501 @cindex Comments in @file{Makefile} rules
16502 @cindex @file{Makefile} rules and comments
16504 Never put comments in a rule.
16506 Some @command{make} treat anything starting with a tab as a command for
16507 the current rule, even if the tab is immediately followed by a @code{#}.
16508 The @command{make} from Tru64 Unix V5.1 is one of them.  The following
16509 makefile runs @code{# foo} through the shell.
16511 @example
16512 all:
16513         # foo
16514 @end example
16516 @node obj/ and Make
16517 @section The @file{obj/} Subdirectory and Make
16518 @cindex @file{obj/}, subdirectory
16519 @cindex @acronym{BSD} @command{make} and @file{obj/}
16521 Never name one of your subdirectories @file{obj/} if you don't like
16522 surprises.
16524 If an @file{obj/} directory exists, @acronym{BSD} @command{make} enters it
16525 before reading the makefile.  Hence the makefile in the
16526 current directory is not read.
16528 @example
16529 $ @kbd{cat Makefile}
16530 all:
16531         echo Hello
16532 $ @kbd{cat obj/Makefile}
16533 all:
16534         echo World
16535 $ @kbd{make}      # GNU make
16536 echo Hello
16537 Hello
16538 $ @kbd{pmake}     # BSD make
16539 echo World
16540 World
16541 @end example
16543 @node make -k Status
16544 @section Exit Status of @code{make -k}
16545 @cindex @code{make -k}
16547 Do not rely on the exit status of @code{make -k}.  Some implementations
16548 reflect whether they encountered an error in their exit status; other
16549 implementations always succeed.
16551 @example
16552 $ @kbd{cat Makefile}
16553 all:
16554         false
16555 $ @kbd{make -k; echo exit status: $?}    # GNU make
16556 false
16557 make: *** [all] Error 1
16558 exit status: 2
16559 $ @kbd{pmake -k; echo exit status: $?}   # BSD make
16560 false
16561 *** Error code 1 (continuing)
16562 exit status: 0
16563 @end example
16565 @node VPATH and Make
16566 @section @code{VPATH} and Make
16567 @cindex @code{VPATH}
16569 Posix does not specify the semantics of @code{VPATH}.  Typically,
16570 @command{make} supports @code{VPATH}, but its implementation is not
16571 consistent.
16573 Autoconf and Automake support makefiles whose usages of @code{VPATH} are
16574 portable to recent-enough popular implementations of @command{make}, but
16575 to keep the resulting makefiles portable, a package's makefile
16576 prototypes must take the following issues into account.  These issues
16577 are complicated and are often poorly understood, and installers who use
16578 @code{VPATH} should expect to find many bugs in this area.  If you use
16579 @code{VPATH}, the simplest way to avoid these portability bugs is to
16580 stick with @acronym{GNU} @command{make}, since it is the most
16581 commonly-used @command{make} among Autoconf users.
16583 Here are some known issues with some @code{VPATH}
16584 implementations.
16586 @menu
16587 * VPATH and Double-colon::      Problems with @samp{::} on ancient hosts
16588 * $< in Explicit Rules::        @code{$<} does not work in ordinary rules
16589 * Automatic Rule Rewriting::    @code{VPATH} goes wild on Solaris
16590 * Tru64 Directory Magic::       @command{mkdir} goes wild on Tru64
16591 * Make Target Lookup::          More details about @code{VPATH} lookup
16592 @end menu
16594 @node VPATH and Double-colon
16595 @subsection @code{VPATH} and Double-colon Rules
16596 @cindex @code{VPATH} and double-colon rules
16597 @cindex double-colon rules and @code{VPATH}
16599 With ancient versions of Sun @command{make},
16600 any assignment to @code{VPATH} causes @command{make} to execute only
16601 the first set of double-colon rules.
16602 However, this problem is no longer of practical concern.
16604 @node $< in Explicit Rules
16605 @subsection @code{$<} Not Supported in Explicit Rules
16606 @cindex explicit rules, @code{$<}, and @code{VPATH}
16607 @cindex @code{$<}, explicit rules, and @code{VPATH}
16608 @cindex @code{VPATH}, explicit rules, and @code{$<}
16610 Using @code{$<} in explicit rules is not portable.
16611 The prerequisite file must be named explicitly in the rule.  If you want
16612 to find the prerequisite via a @code{VPATH} search, you have to code the
16613 whole thing manually.  @xref{Build Directories}.
16615 @node Automatic Rule Rewriting
16616 @subsection Automatic Rule Rewriting
16617 @cindex @code{VPATH} and automatic rule rewriting
16618 @cindex automatic rule rewriting and @code{VPATH}
16620 Some @command{make} implementations, such as Solaris and Tru64,
16621 search for prerequisites in @code{VPATH} and
16622 then rewrite each occurrence as a plain word in the rule.
16623 For instance:
16625 @example
16626 # This isn't portable to GNU make.
16627 VPATH = ../pkg/src
16628 f.c: if.c
16629         cp if.c f.c
16630 @end example
16632 @noindent
16633 executes @code{cp ../pkg/src/if.c f.c} if @file{if.c} is
16634 found in @file{../pkg/src}.
16636 However, this rule leads to real problems in practice.  For example, if
16637 the source directory contains an ordinary file named @file{test} that is
16638 used in a dependency, Solaris @command{make} rewrites commands like
16639 @samp{if test -r foo; @dots{}} to @samp{if ../pkg/src/test -r foo;
16640 @dots{}}, which is typically undesirable.  To avoid this problem,
16641 portable makefiles should never mention a source file whose name is that
16642 of a shell keyword like @file{until} or a shell command like
16643 @command{cat} or @command{gcc} or @command{test}.
16645 Because of these problems @acronym{GNU} @command{make} and many other
16646 @command{make} implementations do not rewrite commands, so portable
16647 makefiles should
16648 search @code{VPATH} manually.  It is tempting to write this:
16650 @smallexample
16651 # This isn't portable to Solaris make.
16652 VPATH = ../pkg/src
16653 f.c: if.c
16654         cp `test -f if.c || echo $(VPATH)/`if.c f.c
16655 @end smallexample
16657 @noindent
16658 However, the ``prerequisite rewriting'' still applies here.  So if
16659 @file{if.c} is in @file{../pkg/src}, Solaris and Tru64 @command{make}
16660 execute
16662 @smallexample
16663 cp `test -f ../pkg/src/if.c || echo ../pkg/src/`if.c f.c
16664 @end smallexample
16666 @noindent
16667 which reduces to
16669 @example
16670 cp if.c f.c
16671 @end example
16673 @noindent
16674 and thus fails.  Oops.
16676 A simple workaround, and good practice anyway, is to use @samp{$?} and
16677 @samp{$@@} when possible:
16679 @smallexample
16680 VPATH = ../pkg/src
16681 f.c: if.c
16682         cp $? $@@
16683 @end smallexample
16685 @noindent
16686 but this does not generalize well to commands with multiple
16687 prerequisites.  A more general workaround is to rewrite the rule so that
16688 the prerequisite @file{if.c} never appears as a plain word.  For
16689 example, these three rules would be safe, assuming @file{if.c} is in
16690 @file{../pkg/src} and the other files are in the working directory:
16692 @smallexample
16693 VPATH = ../pkg/src
16694 f.c: if.c f1.c
16695         cat `test -f ./if.c || echo $(VPATH)/`if.c f1.c >$@@
16696 g.c: if.c g1.c
16697         cat `test -f 'if.c' || echo $(VPATH)/`if.c g1.c >$@@
16698 h.c: if.c h1.c
16699         cat `test -f "if.c" || echo $(VPATH)/`if.c h1.c >$@@
16700 @end smallexample
16702 Things get worse when your prerequisites are in a macro.
16704 @example
16705 VPATH = ../pkg/src
16706 HEADERS = f.h g.h h.h
16707 install-HEADERS: $(HEADERS)
16708         for i in $(HEADERS); do \
16709           $(INSTALL) -m 644 \
16710             `test -f $$i || echo $(VPATH)/`$$i \
16711             $(DESTDIR)$(includedir)/$$i; \
16712         done
16713 @end example
16715 The above @code{install-HEADERS} rule is not Solaris-proof because @code{for
16716 i in $(HEADERS);} is expanded to @code{for i in f.h g.h h.h;}
16717 where @code{f.h} and @code{g.h} are plain words and are hence
16718 subject to @code{VPATH} adjustments.
16720 If the three files are in @file{../pkg/src}, the rule is run as:
16722 @example
16723 for i in ../pkg/src/f.h ../pkg/src/g.h h.h; do \
16724   install -m 644 \
16725      `test -f $i || echo ../pkg/src/`$i \
16726      /usr/local/include/$i; \
16727 done
16728 @end example
16730 where the two first @command{install} calls fail.  For instance,
16731 consider the @code{f.h} installation:
16733 @example
16734 install -m 644 \
16735   `test -f ../pkg/src/f.h || \
16736     echo ../pkg/src/ \
16737   `../pkg/src/f.h \
16738   /usr/local/include/../pkg/src/f.h;
16739 @end example
16741 @noindent
16742 It reduces to:
16744 @example
16745 install -m 644 \
16746   ../pkg/src/f.h \
16747   /usr/local/include/../pkg/src/f.h;
16748 @end example
16750 Note that the manual @code{VPATH} search did not cause any problems here;
16751 however this command installs @file{f.h} in an incorrect directory.
16753 Trying to quote @code{$(HEADERS)} in some way, as we did for
16754 @code{foo.c} a few makefiles ago, does not help:
16756 @example
16757 install-HEADERS: $(HEADERS)
16758         headers='$(HEADERS)'; \
16759         for i in $$headers; do \
16760           $(INSTALL) -m 644 \
16761             `test -f $$i || echo $(VPATH)/`$$i \
16762             $(DESTDIR)$(includedir)/$$i; \
16763         done
16764 @end example
16766 Now, @code{headers='$(HEADERS)'} macro-expands to:
16768 @example
16769 headers='f.h g.h h.h'
16770 @end example
16772 @noindent
16773 but @code{g.h} is still a plain word.  (As an aside, the idiom
16774 @code{headers='$(HEADERS)'; for i in $$headers;} is a good
16775 idea if @code{$(HEADERS)} can be empty, because some shells diagnose a
16776 syntax error on @code{for i in;}.)
16778 One workaround is to strip this unwanted @file{../pkg/src/} prefix manually:
16780 @example
16781 VPATH = ../pkg/src
16782 HEADERS = f.h g.h h.h
16783 install-HEADERS: $(HEADERS)
16784         headers='$(HEADERS)'; \
16785         for i in $$headers; do \
16786           i=`expr "$$i" : '$(VPATH)/\(.*\)'`;
16787           $(INSTALL) -m 644 \
16788             `test -f $$i || echo $(VPATH)/`$$i \
16789             $(DESTDIR)$(includedir)/$$i; \
16790         done
16791 @end example
16793 Automake does something similar.  However the above hack works only if
16794 the files listed in @code{HEADERS} are in the current directory or a
16795 subdirectory; they should not be in an enclosing directory.  If we had
16796 @code{HEADERS = ../f.h}, the above fragment would fail in a VPATH
16797 build with Tru64 @command{make}.  The reason is that not only does
16798 Tru64 @command{make} rewrite dependencies, but it also simplifies
16799 them.  Hence @code{../f.h} becomes @code{../pkg/f.h} instead of
16800 @code{../pkg/src/../f.h}.  This obviously defeats any attempt to strip
16801 a leading @file{../pkg/src/} component.
16803 The following example makes the behavior of Tru64 @command{make}
16804 more apparent.
16806 @example
16807 $ @kbd{cat Makefile}
16808 VPATH = sub
16809 all: ../foo
16810         echo ../foo
16811 $ @kbd{ls}
16812 Makefile foo
16813 $ @kbd{make}
16814 echo foo
16816 @end example
16818 @noindent
16819 Dependency @file{../foo} was found in @file{sub/../foo}, but Tru64
16820 @command{make} simplified it as @file{foo}.  (Note that the @file{sub/}
16821 directory does not even exist, this just means that the simplification
16822 occurred before the file was checked for.)
16824 For the record here is how SunOS 4 @command{make} behaves on this
16825 example.
16827 @smallexample
16828 $ @kbd{make}
16829 make: Fatal error: Don't know how to make target `../foo'
16830 $ @kbd{mkdir sub}
16831 $ @kbd{make}
16832 echo sub/../foo
16833 sub/../foo
16834 @end smallexample
16837 @node Tru64 Directory Magic
16838 @subsection Tru64 @command{make} Creates Prerequisite Directories Magically
16839 @cindex @code{VPATH} and prerequisite directories
16840 @cindex prerequisite directories and @code{VPATH}
16842 When a prerequisite is a subdirectory of @code{VPATH}, Tru64
16843 @command{make} creates it in the current directory.
16845 @example
16846 $ @kbd{mkdir -p foo/bar build}
16847 $ @kbd{cd build}
16848 $ @kbd{cat >Makefile <<END
16849 VPATH = ..
16850 all: foo/bar
16851 END}
16852 $ @kbd{make}
16853 mkdir foo
16854 mkdir foo/bar
16855 @end example
16857 This can yield unexpected results if a rule uses a manual @code{VPATH}
16858 search as presented before.
16860 @example
16861 VPATH = ..
16862 all : foo/bar
16863         command `test -d foo/bar || echo ../`foo/bar
16864 @end example
16866 The above @command{command} is run on the empty @file{foo/bar}
16867 directory that was created in the current directory.
16869 @node Make Target Lookup
16870 @subsection Make Target Lookup
16871 @cindex @code{VPATH}, resolving target pathnames
16873 @acronym{GNU} @command{make} uses a complex algorithm to decide when it
16874 should use files found via a @code{VPATH} search.  @xref{Search
16875 Algorithm, , How Directory Searches are Performed, make, The @acronym{GNU} Make
16876 Manual}.
16878 If a target needs to be rebuilt, @acronym{GNU} @command{make} discards the
16879 file name found during the @code{VPATH} search for this target, and
16880 builds the file locally using the file name given in the makefile.
16881 If a target does not need to be rebuilt, @acronym{GNU} @command{make} uses the
16882 file name found during the @code{VPATH} search.
16884 Other @command{make} implementations, like Net@acronym{BSD} @command{make}, are
16885 easier to describe: the file name found during the @code{VPATH} search
16886 is used whether the target needs to be rebuilt or not.  Therefore
16887 new files are created locally, but existing files are updated at their
16888 @code{VPATH} location.
16890 Open@acronym{BSD} and Free@acronym{BSD} @command{make}, however,
16891 never perform a
16892 @code{VPATH} search for a dependency that has an explicit rule.
16893 This is extremely annoying.
16895 When attempting a @code{VPATH} build for an autoconfiscated package
16896 (e.g., @code{mkdir build && cd build && ../configure}), this means
16897 @acronym{GNU}
16898 @command{make} builds everything locally in the @file{build}
16899 directory, while @acronym{BSD} @command{make} builds new files locally and
16900 updates existing files in the source directory.
16902 @example
16903 $ @kbd{cat Makefile}
16904 VPATH = ..
16905 all: foo.x bar.x
16906 foo.x bar.x: newer.x
16907         @@echo Building $@@
16908 $ @kbd{touch ../bar.x}
16909 $ @kbd{touch ../newer.x}
16910 $ @kbd{make}        # GNU make
16911 Building foo.x
16912 Building bar.x
16913 $ @kbd{pmake}       # NetBSD make
16914 Building foo.x
16915 Building ../bar.x
16916 $ @kbd{fmake}       # FreeBSD make, OpenBSD make
16917 Building foo.x
16918 Building bar.x
16919 $ @kbd{tmake}       # Tru64 make
16920 Building foo.x
16921 Building bar.x
16922 $ @kbd{touch ../bar.x}
16923 $ @kbd{make}        # GNU make
16924 Building foo.x
16925 $ @kbd{pmake}       # NetBSD make
16926 Building foo.x
16927 $ @kbd{fmake}       # FreeBSD make, OpenBSD make
16928 Building foo.x
16929 Building bar.x
16930 $ @kbd{tmake}       # Tru64 make
16931 Building foo.x
16932 Building bar.x
16933 @end example
16935 Note how Net@acronym{BSD} @command{make} updates @file{../bar.x} in its
16936 VPATH location, and how Free@acronym{BSD}, Open@acronym{BSD}, and Tru64
16937 @command{make} always
16938 update @file{bar.x}, even when @file{../bar.x} is up to date.
16940 Another point worth mentioning is that once @acronym{GNU} @command{make} has
16941 decided to ignore a @code{VPATH} file name (e.g., it ignored
16942 @file{../bar.x} in the above example) it continues to ignore it when
16943 the target occurs as a prerequisite of another rule.
16945 The following example shows that @acronym{GNU} @command{make} does not look up
16946 @file{bar.x} in @code{VPATH} before performing the @code{.x.y} rule,
16947 because it ignored the @code{VPATH} result of @file{bar.x} while running
16948 the @code{bar.x: newer.x} rule.
16950 @example
16951 $ @kbd{cat Makefile}
16952 VPATH = ..
16953 all: bar.y
16954 bar.x: newer.x
16955         @@echo Building $@@
16956 .SUFFIXES: .x .y
16957 .x.y:
16958         cp $< $@@
16959 $ @kbd{touch ../bar.x}
16960 $ @kbd{touch ../newer.x}
16961 $ @kbd{make}        # GNU make
16962 Building bar.x
16963 cp bar.x bar.y
16964 cp: cannot stat `bar.x': No such file or directory
16965 make: *** [bar.y] Error 1
16966 $ @kbd{pmake}       # NetBSD make
16967 Building ../bar.x
16968 cp ../bar.x bar.y
16969 $ @kbd{rm bar.y}
16970 $ @kbd{fmake}       # FreeBSD make, OpenBSD make
16971 echo Building bar.x
16972 cp bar.x bar.y
16973 cp: cannot stat `bar.x': No such file or directory
16974 *** Error code 1
16975 $ @kbd{tmake}       # Tru64 make
16976 Building bar.x
16977 cp: bar.x: No such file or directory
16978 *** Exit 1
16979 @end example
16981 Note that if you drop away the command from the @code{bar.x: newer.x}
16982 rule, @acronym{GNU} @command{make} magically starts to work: it
16983 knows that @code{bar.x} hasn't been updated, therefore it doesn't
16984 discard the result from @code{VPATH} (@file{../bar.x}) in succeeding
16985 uses.  Tru64 also works, but Free@acronym{BSD} and Open@acronym{BSD}
16986 still don't.
16988 @example
16989 $ @kbd{cat Makefile}
16990 VPATH = ..
16991 all: bar.y
16992 bar.x: newer.x
16993 .SUFFIXES: .x .y
16994 .x.y:
16995         cp $< $@@
16996 $ @kbd{touch ../bar.x}
16997 $ @kbd{touch ../newer.x}
16998 $ @kbd{make}        # GNU make
16999 cp ../bar.x bar.y
17000 $ @kbd{rm bar.y}
17001 $ @kbd{pmake}       # NetBSD make
17002 cp ../bar.x bar.y
17003 $ @kbd{rm bar.y}
17004 $ @kbd{fmake}       # FreeBSD make, OpenBSD make
17005 cp bar.x bar.y
17006 cp: cannot stat `bar.x': No such file or directory
17007 *** Error code 1
17008 $ @kbd{tmake}       # Tru64 make
17009 cp ../bar.x bar.y
17010 @end example
17012 It seems the sole solution that would please every @command{make}
17013 implementation is to never rely on @code{VPATH} searches for targets.
17014 In other words, @code{VPATH} should be reserved to unbuilt sources.
17017 @node Single Suffix Rules
17018 @section Single Suffix Rules and Separated Dependencies
17019 @cindex Single Suffix Inference Rule
17020 @cindex Rule, Single Suffix Inference
17021 A @dfn{Single Suffix Rule} is basically a usual suffix (inference) rule
17022 (@samp{.from.to:}), but which @emph{destination} suffix is empty
17023 (@samp{.from:}).
17025 @cindex Separated Dependencies
17026 @dfn{Separated dependencies} simply refers to listing the prerequisite
17027 of a target, without defining a rule.  Usually one can list on the one
17028 hand side, the rules, and on the other hand side, the dependencies.
17030 Solaris @command{make} does not support separated dependencies for
17031 targets defined by single suffix rules:
17033 @example
17034 $ @kbd{cat Makefile}
17035 .SUFFIXES: .in
17036 foo: foo.in
17037 .in:
17038         cp $< $@@
17039 $ @kbd{touch foo.in}
17040 $ @kbd{make}
17041 $ @kbd{ls}
17042 Makefile  foo.in
17043 @end example
17045 @noindent
17046 while @acronym{GNU} Make does:
17048 @example
17049 $ @kbd{gmake}
17050 cp foo.in foo
17051 $ @kbd{ls}
17052 Makefile  foo       foo.in
17053 @end example
17055 Note it works without the @samp{foo: foo.in} dependency.
17057 @example
17058 $ @kbd{cat Makefile}
17059 .SUFFIXES: .in
17060 .in:
17061         cp $< $@@
17062 $ @kbd{make foo}
17063 cp foo.in foo
17064 @end example
17066 @noindent
17067 and it works with double suffix inference rules:
17069 @example
17070 $ @kbd{cat Makefile}
17071 foo.out: foo.in
17072 .SUFFIXES: .in .out
17073 .in.out:
17074         cp $< $@@
17075 $ @kbd{make}
17076 cp foo.in foo.out
17077 @end example
17079 As a result, in such a case, you have to write target rules.
17081 @node Timestamps and Make
17082 @section Timestamp Resolution and Make
17083 @cindex timestamp resolution
17084 Traditionally, file timestamps had 1-second resolution, and
17085 @command{make} used those timestamps to determine whether one file was
17086 newer than the other.  However, many modern file systems have
17087 timestamps with 1-nanosecond resolution.  Some @command{make}
17088 implementations look at the entire timestamp; others ignore the
17089 fractional part, which can lead to incorrect results.  Normally this
17090 is not a problem, but in some extreme cases you may need to use tricks
17091 like @samp{sleep 1} to work around timestamp truncation bugs.
17093 Commands like @samp{cp -p} and @samp{touch -r} typically do not copy
17094 file timestamps to their full resolutions (@pxref{Limitations of Usual
17095 Tools}).  Hence you should be wary of rules like this:
17097 @example
17098 dest: src
17099         cp -p src dest
17100 @end example
17102 as @file{dest} often appears to be older than @file{src} after the
17103 timestamp is truncated, and this can cause @command{make} to do
17104 needless rework the next time it is invoked.  To work around this
17105 problem, you can use a timestamp file, e.g.:
17107 @example
17108 dest-stamp: src
17109         cp -p src dest
17110         date >dest-stamp
17111 @end example
17116 @c ======================================== Portable C and C++ Programming
17118 @node Portable C and C++
17119 @chapter Portable C and C++ Programming
17120 @cindex Portable C and C++ programming
17122 C and C++ programs often use low-level features of the underlying
17123 system, and therefore are often more difficult to make portable to other
17124 platforms.
17126 Several standards have been developed to help make your programs more
17127 portable.  If you write programs with these standards in mind, you can
17128 have greater confidence that your programs work on a wide variety
17129 of systems.  @xref{Standards, , Language Standards Supported by
17130 @acronym{GCC}, gcc, Using the @acronym{GNU} Compiler Collection
17131 (@acronym{GCC})}, for a list of C-related
17132 standards.  Many programs also assume the
17133 @uref{http://@/www.opengroup.org/@/susv3, Posix standard}.
17135 Some old code is written to be portable to K&R C, which predates any C
17136 standard.  K&R C compilers are no longer of practical interest, though,
17137 and the rest of section assumes at least C89, the first C standard.
17139 Program portability is a huge topic, and this section can only briefly
17140 introduce common pitfalls.  @xref{System Portability, , Portability
17141 between System Types, standards, @acronym{GNU} Coding Standards}, for
17142 more information.
17144 @menu
17145 * Varieties of Unportability::  How to make your programs unportable
17146 * Integer Overflow::            When integers get too large
17147 * Preprocessor Arithmetic::     @code{#if} expression problems
17148 * Null Pointers::               Properties of null pointers
17149 * Buffer Overruns::             Subscript errors and the like
17150 * Volatile Objects::            @code{volatile} and signals
17151 * Floating Point Portability::  Portable floating-point arithmetic
17152 * Exiting Portably::            Exiting and the exit status
17153 @end menu
17155 @node Varieties of Unportability
17156 @section Varieties of Unportability
17157 @cindex portability
17159 Autoconf tests and ordinary programs often need to test what is allowed
17160 on a system, and therefore they may need to deliberately exceed the
17161 boundaries of what the standards allow, if only to see whether an
17162 optional feature is present.  When you write such a program, you should
17163 keep in mind the difference between constraints, unspecified behavior,
17164 and undefined behavior.
17166 In C, a @dfn{constraint} is a rule that the compiler must enforce.  An
17167 example constraint is that C programs must not declare a bit-field with
17168 negative width.  Tests can therefore reliably assume that programs with
17169 negative-width bit-fields are rejected by a compiler that conforms
17170 to the standard.
17172 @dfn{Unspecified behavior} is valid behavior, where the standard allows
17173 multiple possibilities.  For example, the order of evaluation of
17174 function arguments is unspecified.  Some unspecified behavior is
17175 @dfn{implementation-defined}, i.e., documented by the implementation,
17176 but since Autoconf tests cannot read the documentation they cannot
17177 distinguish between implementation-defined and other unspecified
17178 behavior.  It is common for Autoconf tests to probe implementations to
17179 determine otherwise-unspecified behavior.
17181 @dfn{Undefined behavior} is invalid behavior, where the standard allows
17182 the implementation to do anything it pleases.  For example,
17183 dereferencing a null pointer leads to undefined behavior.  If possible,
17184 test programs should avoid undefined behavior, since a program with
17185 undefined behavior might succeed on a test that should fail.
17187 The above rules apply to programs that are intended to conform to the
17188 standard.  However, strictly-conforming programs are quite rare, since
17189 the standards are so limiting.  A major goal of Autoconf is to support
17190 programs that use implementation features not described by the standard,
17191 and it is fairly common for test programs to violate the above rules, if
17192 the programs work well enough in practice.
17194 @node Integer Overflow
17195 @section Integer Overflow
17196 @cindex integer overflow
17197 @cindex overflow, signed integer
17198 @cindex signed integer overflow
17199 @cindex wraparound arithmetic
17201 In practice many portable C programs assume that signed integer overflow wraps
17202 around reliably using two's complement arithmetic.  Yet the C standard
17203 says that program behavior is undefined on overflow, and in a few cases
17204 C programs do not work on some modern implementations because their
17205 overflows do not wrap around as their authors expected.  Conversely, in
17206 signed integer remainder, the C standard requires overflow
17207 behavior that is commonly not implemented.
17209 @menu
17210 * Integer Overflow Basics::      Why integer overflow is a problem
17211 * Signed Overflow Examples::     Examples of code assuming wraparound
17212 * Optimization and Wraparound::  Optimizations that break uses of wraparound
17213 * Signed Overflow Advice::       Practical advice for signed overflow issues
17214 * Signed Integer Division::      @code{INT_MIN / -1} and @code{INT_MIN % -1}
17215 @end menu
17217 @node Integer Overflow Basics
17218 @subsection Basics of Integer Overflow
17219 @cindex integer overflow
17220 @cindex overflow, signed integer
17221 @cindex signed integer overflow
17222 @cindex wraparound arithmetic
17224 In languages like C, unsigned integer overflow reliably wraps around;
17225 e.g., @code{UINT_MAX + 1} yields zero.
17226 This is guaranteed by the C standard and is
17227 portable in practice, unless you specify aggressive,
17228 nonstandard optimization options
17229 suitable only for special applications.
17231 In contrast, the C standard says that signed integer overflow leads to
17232 undefined behavior where a program can do anything, including dumping
17233 core or overrunning a buffer.  The misbehavior can even precede the
17234 overflow.  Such an overflow can occur during addition, subtraction,
17235 multiplication, division, and left shift.
17237 Despite this requirement of the standard, many C programs and Autoconf
17238 tests assume that signed integer overflow silently wraps around modulo a
17239 power of two, using two's complement arithmetic, so long as you cast the
17240 resulting value to a signed integer type or store it into a signed
17241 integer variable.  If you use conservative optimization flags, such
17242 programs are generally portable to the vast majority of modern
17243 platforms, with a few exceptions discussed later.
17245 For historical reasons the C standard also allows implementations with
17246 ones' complement or signed magnitude arithmetic, but it is safe to
17247 assume two's complement nowadays.
17249 Also, overflow can occur when converting an out-of-range value to a
17250 signed integer type.  Here a standard implementation must define what
17251 happens, but this might include raising an exception.  In practice all
17252 known implementations support silent wraparound in this case, so you need
17253 not worry about other possibilities.
17255 @node Signed Overflow Examples
17256 @subsection Examples of Code Assuming Wraparound Overflow
17257 @cindex integer overflow
17258 @cindex overflow, signed integer
17259 @cindex signed integer overflow
17260 @cindex wraparound arithmetic
17262 There has long been a tension between what the C standard requires for
17263 signed integer overflow, and what C programs commonly assume.  The
17264 standard allows aggressive optimizations based on assumptions that
17265 overflow never occurs, but many practical C programs rely on overflow
17266 wrapping around.  These programs do not conform to the standard, but
17267 they commonly work in practice because compiler writers are
17268 understandably reluctant to implement optimizations that would break
17269 many programs, unless perhaps a user specifies aggressive optimization.
17271 The C Standard says that if a program has signed integer overflow its
17272 behavior is undefined, and the undefined behavior can even precede the
17273 overflow.  To take an extreme example:
17275 @c Inspired by Robert Dewar's example in
17276 @c <http://gcc.gnu.org/ml/gcc/2007-01/msg00038.html> (2007-01-01).
17277 @example
17278 if (password == expected_password)
17279   allow_superuser_privileges ();
17280 else if (counter++ == INT_MAX)
17281   abort ();
17282 else
17283   printf ("%d password mismatches\n", counter);
17284 @end example
17286 @noindent
17287 If the @code{int} variable @code{counter} equals @code{INT_MAX},
17288 @code{counter++} must overflow and the behavior is undefined, so the C
17289 standard allows the compiler to optimize away the test against
17290 @code{INT_MAX} and the @code{abort} call.
17291 Worse, if an earlier bug in the program lets the compiler deduce that
17292 @code{counter == INT_MAX} or that @code{counter} previously overflowed,
17293 the C standard allows the compiler to optimize away the password test
17294 and generate code that allows superuser privileges unconditionally.
17296 Despite this requirement by the standard, it has long been common for C
17297 code to assume wraparound arithmetic after signed overflow, and all
17298 known practical C implementations support some C idioms that assume
17299 wraparound signed arithmetic, even if the idioms do not conform
17300 strictly to the standard.  If your code looks like the following
17301 examples it will almost surely work with real-world compilers.
17303 Here is an example derived from the 7th Edition Unix implementation of
17304 @code{atoi} (1979-01-10):
17306 @example
17307 char *p;
17308 int f, n;
17309 @dots{}
17310 while (*p >= '0' && *p <= '9')
17311   n = n * 10 + *p++ - '0';
17312 return (f ? -n : n);
17313 @end example
17315 @noindent
17316 Even if the input string is in range, on most modern machines this has
17317 signed overflow when computing the most negative integer (the @code{-n}
17318 overflows) or a value near an extreme integer (the first @code{+}
17319 overflows).
17321 Here is another example, derived from the 7th Edition implementation of
17322 @code{rand} (1979-01-10).  Here the programmer expects both
17323 multiplication and addition to wrap on overflow:
17325 @example
17326 static long int randx = 1;
17327 @dots{}
17328 randx = randx * 1103515245 + 12345;
17329 return (randx >> 16) & 077777;
17330 @end example
17332 In the following example, derived from the @acronym{GNU} C Library 2.5
17333 implementation of @code{mktime} (2006-09-09), the code assumes
17334 wraparound arithmetic in @code{+} to detect signed overflow:
17336 @example
17337 time_t t, t1, t2;
17338 int sec_requested, sec_adjustment;
17339 @dots{}
17340 t1 = t + sec_requested;
17341 t2 = t1 + sec_adjustment;
17342 if (((t1 < t) != (sec_requested < 0))
17343     | ((t2 < t1) != (sec_adjustment < 0)))
17344   return -1;
17345 @end example
17347 If your code looks like these examples, it is probably safe even though
17348 it does not strictly conform to the C standard.  This might lead one to
17349 believe that one can generally assume wraparound on overflow, but that
17350 is not always true, as can be seen in the next section.
17352 @node Optimization and Wraparound
17353 @subsection Optimizations That Break Wraparound Arithmetic
17354 @cindex loop induction
17356 Compilers sometimes generate code that is incompatible with wraparound
17357 integer arithmetic.  A simple example is an algebraic simplification: a
17358 compiler might translate @code{(i * 2000) / 1000} to @code{i * 2}
17359 because it assumes that @code{i * 2000} does not overflow.  The
17360 translation is not equivalent to the original when overflow occurs:
17361 e.g., in the typical case of 32-bit signed two's complement wraparound
17362 @code{int}, if @code{i} has type @code{int} and value @code{1073742},
17363 the original expression returns @minus{}2147483 but the optimized
17364 version returns the mathematically correct value 2147484.
17366 More subtly, loop induction optimizations often exploit the undefined
17367 behavior of signed overflow.  Consider the following contrived function
17368 @code{sumc}:
17370 @example
17372 sumc (int lo, int hi)
17374   int sum = 0;
17375   int i;
17376   for (i = lo; i <= hi; i++)
17377     sum ^= i * 53;
17378   return sum;
17380 @end example
17382 @noindent
17383 To avoid multiplying by 53 each time through the loop, an optimizing
17384 compiler might internally transform @code{sumc} to the equivalent of the
17385 following:
17387 @example
17389 transformed_sumc (int lo, int hi)
17391   int sum = 0;
17392   int hic = hi * 53;
17393   int ic;
17394   for (ic = lo * 53; ic <= hic; ic += 53)
17395     sum ^= ic;
17396   return sum;
17398 @end example
17400 @noindent
17401 This transformation is allowed by the C standard, but it is invalid for
17402 wraparound arithmetic when @code{INT_MAX / 53 < hi}, because then the
17403 overflow in computing expressions like @code{hi * 53} can cause the
17404 expression @code{i <= hi} to yield a different value from the
17405 transformed expression @code{ic <= hic}.
17407 For this reason, compilers that use loop induction and similar
17408 techniques often do not support reliable wraparound arithmetic when a
17409 loop induction variable like @code{ic} is involved.  Since loop
17410 induction variables are generated by the compiler, and are not visible
17411 in the source code, it is not always trivial to say whether the problem
17412 affects your code.
17414 Hardly any code actually depends on wraparound arithmetic in cases like
17415 these, so in practice these loop induction optimizations are almost
17416 always useful.  However, edge cases in this area can cause problems.
17417 For example:
17419 @example
17420 int j;
17421 for (j = 1; 0 < j; j *= 2)
17422   test (j);
17423 @end example
17425 @noindent
17426 Here, the loop attempts to iterate through all powers of 2 that
17427 @code{int} can represent, but the C standard allows a compiler to
17428 optimize away the comparison and generate an infinite loop,
17429 under the argument that behavior is undefined on overflow.  As of this
17430 writing this optimization is not done by any production version of
17431 @acronym{GCC} with @option{-O2}, but it might be performed by other
17432 compilers, or by more aggressive @acronym{GCC} optimization options,
17433 and the @acronym{GCC} developers have not decided whether it will
17434 continue to work with @acronym{GCC} and @option{-O2}.
17436 @node Signed Overflow Advice
17437 @subsection Practical Advice for Signed Overflow Issues
17438 @cindex integer overflow
17439 @cindex overflow, signed integer
17440 @cindex signed integer overflow
17441 @cindex wraparound arithmetic
17443 Ideally the safest approach is to avoid signed integer overflow
17444 entirely.  For example, instead of multiplying two signed integers, you
17445 can convert them to unsigned integers, multiply the unsigned values,
17446 then test whether the result is in signed range.
17448 Rewriting code in this way will be inconvenient, though, particularly if
17449 the signed values might be negative.  Also, it may hurt
17450 performance.  Using unsigned arithmetic to check for overflow is
17451 particularly painful to do portably and efficiently when dealing with an
17452 integer type like @code{uid_t} whose width and signedness vary from
17453 platform to platform.
17455 Furthermore, many C applications pervasively assume wraparound behavior
17456 and typically it is not easy to find and remove all these assumptions.
17457 Hence it is often useful to maintain nonstandard code that assumes
17458 wraparound on overflow, instead of rewriting the code.  The rest of this
17459 section attempts to give practical advice for this situation.
17461 If your code wants to detect signed integer overflow in @code{sum = a +
17462 b}, it is generally safe to use an expression like @code{(sum < a) != (b
17463 < 0)}.
17465 If your code uses a signed loop index, make sure that the index cannot
17466 overflow, along with all signed expressions derived from the index.
17467 Here is a contrived example of problematic code with two instances of
17468 overflow.
17470 @example
17471 for (i = INT_MAX - 10; i <= INT_MAX; i++)
17472   if (i + 1 < 0)
17473     @{
17474       report_overflow ();
17475       break;
17476     @}
17477 @end example
17479 @noindent
17480 Because of the two overflows, a compiler might optimize away or
17481 transform the two comparisons in a way that is incompatible with the
17482 wraparound assumption.
17484 If your code uses an expression like @code{(i * 2000) / 1000} and you
17485 actually want the multiplication to wrap around on overflow, use
17486 unsigned arithmetic
17487 to do it, e.g., @code{((int) (i * 2000u)) / 1000}.
17489 If your code assumes wraparound behavior and you want to insulate it
17490 against any @acronym{GCC} optimizations that would fail to support that
17491 behavior, you should use @acronym{GCC}'s @option{-fwrapv} option, which
17492 causes signed overflow to wrap around reliably (except for division and
17493 remainder, as discussed in the next section).
17495 If you need to port to platforms where signed integer overflow does not
17496 reliably wrap around (e.g., due to hardware overflow checking, or to
17497 highly aggressive optimizations), you should consider debugging with
17498 @acronym{GCC}'s @option{-ftrapv} option, which causes signed overflow to
17499 raise an exception.
17501 @node Signed Integer Division
17502 @subsection Signed Integer Division and Integer Overflow
17503 @cindex division, integer
17505 Overflow in signed
17506 integer division is not always harmless: for example, on CPUs of the
17507 i386 family, dividing @code{INT_MIN} by @code{-1} yields a SIGFPE signal
17508 which by default terminates the program.  Worse, taking the remainder
17509 of these two values typically yields the same signal on these CPUs,
17510 even though the C standard requires @code{INT_MIN % -1} to yield zero
17511 because the expression does not overflow.
17513 @node Preprocessor Arithmetic
17514 @section Preprocessor Arithmetic
17515 @cindex preprocessor arithmetic
17517 In C99, preprocessor arithmetic, used for @code{#if} expressions, must
17518 be evaluated as if all signed values are of type @code{intmax_t} and all
17519 unsigned values of type @code{uintmax_t}.  Many compilers are buggy in
17520 this area, though.  For example, as of 2007, Sun C mishandles @code{#if
17521 LLONG_MIN < 0} on a platform with 32-bit @code{long int} and 64-bit
17522 @code{long long int}.  Also, some older preprocessors mishandle
17523 constants ending in @code{LL}.  To work around these problems, you can
17524 compute the value of expressions like @code{LONG_MAX < LLONG_MAX} at
17525 @code{configure}-time rather than at @code{#if}-time.
17527 @node Null Pointers
17528 @section Properties of Null Pointers
17529 @cindex null pointers
17531 Most modern hosts reliably fail when you attempt to dereference a null
17532 pointer.
17534 On almost all modern hosts, null pointers use an all-bits-zero internal
17535 representation, so you can reliably use @code{memset} with 0 to set all
17536 the pointers in an array to null values.
17538 If @code{p} is a null pointer to an object type, the C expression
17539 @code{p + 0} always evaluates to @code{p} on modern hosts, even though
17540 the standard says that it has undefined behavior.
17542 @node Buffer Overruns
17543 @section Buffer Overruns and Subscript Errors
17544 @cindex buffer overruns
17546 Buffer overruns and subscript errors are the most common dangerous
17547 errors in C programs.  They result in undefined behavior because storing
17548 outside an array typically modifies storage that is used by some other
17549 object, and most modern systems lack runtime checks to catch these
17550 errors.  Programs should not rely on buffer overruns being caught.
17552 There is one exception to the usual rule that a portable program cannot
17553 address outside an array.  In C, it is valid to compute the address just
17554 past an object, e.g., @code{&a[N]} where @code{a} has @code{N} elements,
17555 so long as you do not dereference the resulting pointer.  But it is not
17556 valid to compute the address just before an object, e.g., @code{&a[-1]};
17557 nor is it valid to compute two past the end, e.g., @code{&a[N+1]}.  On
17558 most platforms @code{&a[-1] < &a[0] && &a[N] < &a[N+1]}, but this is not
17559 reliable in general, and it is usually easy enough to avoid the
17560 potential portability problem, e.g., by allocating an extra unused array
17561 element at the start or end.
17563 @uref{http://@/valgrind.org/, Valgrind} can catch many overruns.
17564 @acronym{GCC}
17565 users might also consider using the @option{-fmudflap} option to catch
17566 overruns.
17568 Buffer overruns are usually caused by off-by-one errors, but there are
17569 more subtle ways to get them.
17571 Using @code{int} values to index into an array or compute array sizes
17572 causes problems on typical 64-bit hosts where an array index might
17573 be @math{2^31} or larger.  Index values of type @code{size_t} avoid this
17574 problem, but cannot be negative.  Index values of type @code{ptrdiff_t}
17575 are signed, and are wide enough in practice.
17577 If you add or multiply two numbers to calculate an array size, e.g.,
17578 @code{malloc (x * sizeof y + z)}, havoc ensues if the addition or
17579 multiplication overflows.
17581 Many implementations of the @code{alloca} function silently misbehave
17582 and can generate buffer overflows if given sizes that are too large.
17583 The size limits are implementation dependent, but are at least 4000
17584 bytes on all platforms that we know about.
17586 The standard functions @code{asctime}, @code{asctime_r}, @code{ctime},
17587 @code{ctime_r}, and @code{gets} are prone to buffer overflows, and
17588 portable code should not use them unless the inputs are known to be
17589 within certain limits.  The time-related functions can overflow their
17590 buffers if given timestamps out of range (e.g., a year less than -999
17591 or greater than 9999).  Time-related buffer overflows cannot happen with
17592 recent-enough versions of the @acronym{GNU} C library, but are possible
17593 with other
17594 implementations.  The @code{gets} function is the worst, since it almost
17595 invariably overflows its buffer when presented with an input line larger
17596 than the buffer.
17598 @node Volatile Objects
17599 @section Volatile Objects
17600 @cindex volatile objects
17602 The keyword @code{volatile} is often misunderstood in portable code.
17603 Its use inhibits some memory-access optimizations, but programmers often
17604 wish that it had a different meaning than it actually does.
17606 @code{volatile} was designed for code that accesses special objects like
17607 memory-mapped device registers whose contents spontaneously change.
17608 Such code is inherently low-level, and it is difficult to specify
17609 portably what @code{volatile} means in these cases.  The C standard
17610 says, ``What constitutes an access to an object that has
17611 volatile-qualified type is implementation-defined,'' so in theory each
17612 implementation is supposed to fill in the gap by documenting what
17613 @code{volatile} means for that implementation.  In practice, though,
17614 this documentation is usually absent or incomplete.
17616 One area of confusion is the distinction between objects defined with
17617 volatile types, and volatile lvalues.  From the C standard's point of
17618 view, an object defined with a volatile type has externally visible
17619 behavior.  You can think of such objects as having little oscilloscope
17620 probes attached to them, so that the user can observe some properties of
17621 accesses to them, just as the user can observe data written to output
17622 files.  However, the standard does not make it clear whether users can
17623 observe accesses by volatile lvalues to ordinary objects.  For example:
17625 @example
17626 /* Declare and access a volatile object.
17627    Accesses to X are "visible" to users.  */
17628 static int volatile x;
17629 x = 1;
17631 /* Access two ordinary objects via a volatile lvalue.
17632    It's not clear whether accesses to *P are "visible".  */
17633 int y;
17634 int *z = malloc (sizeof (int));
17635 int volatile *p;
17636 p = &y;
17637 *p = 1;
17638 p = z;
17639 *p = 1;
17640 @end example
17642 Programmers often wish that @code{volatile} meant ``Perform the memory
17643 access here and now, without merging several memory accesses, without
17644 changing the memory word size, and without reordering.''  But the C
17645 standard does not require this.  For objects defined with a volatile
17646 type, accesses must be done before the next sequence point; but
17647 otherwise merging, reordering, and word-size change is allowed.  Worse,
17648 it is not clear from the standard whether volatile lvalues provide more
17649 guarantees in general than nonvolatile lvalues, if the underlying
17650 objects are ordinary.
17652 Even when accessing objects defined with a volatile type,
17653 the C standard allows only
17654 extremely limited signal handlers: the behavior is undefined if a signal
17655 handler reads any nonlocal object, or writes to any nonlocal object
17656 whose type is not @code{sig_atomic_t volatile}, or calls any standard
17657 library function other than @code{abort}, @code{signal}, and (if C99)
17658 @code{_Exit}.  Hence C compilers need not worry about a signal handler
17659 disturbing ordinary computation, unless the computation accesses a
17660 @code{sig_atomic_t volatile} lvalue that is not a local variable.
17661 (There is an obscure exception for accesses via a pointer to a volatile
17662 character, since it may point into part of a @code{sig_atomic_t
17663 volatile} object.)  Posix
17664 adds to the list of library functions callable from a portable signal
17665 handler, but otherwise is like the C standard in this area.
17667 Some C implementations allow memory-access optimizations within each
17668 translation unit, such that actual behavior agrees with the behavior
17669 required by the standard only when calling a function in some other
17670 translation unit, and a signal handler acts like it was called from a
17671 different translation unit.  The C standard hints that in these
17672 implementations, objects referred to by signal handlers ``would require
17673 explicit specification of @code{volatile} storage, as well as other
17674 implementation-defined restrictions.''  But unfortunately even for this
17675 special case these other restrictions are often not documented well.
17676 @xref{Volatiles, , When is a Volatile Object Accessed?, gcc, Using the
17677 @acronym{GNU} Compiler Collection (@acronym{GCC})}, for some
17678 restrictions imposed by @acronym{GCC}.  @xref{Defining Handlers, ,
17679 Defining Signal Handlers, libc, The @acronym{GNU} C Library}, for some
17680 restrictions imposed by the @acronym{GNU} C library.  Restrictions
17681 differ on other platforms.
17683 If possible, it is best to use a signal handler that fits within the
17684 limits imposed by the C and Posix standards.
17686 If this is not practical, you can try the following rules of thumb.  A
17687 signal handler should access only volatile lvalues, preferably lvalues
17688 that refer to objects defined with a volatile type, and should not
17689 assume that the accessed objects have an internally consistent state
17690 if they are larger than a machine word.  Furthermore, installers
17691 should employ compilers and compiler options that are commonly used
17692 for building operating system kernels, because kernels often need more
17693 from @code{volatile} than the C Standard requires, and installers who
17694 compile an application in a similar environment can sometimes benefit
17695 from the extra constraints imposed by kernels on compilers.
17696 Admittedly we are handwaving somewhat here, as there are few
17697 guarantees in this area; the rules of thumb may help to fix some bugs
17698 but there is a good chance that they will not fix them all.
17700 For @code{volatile}, C++ has the same problems that C does.
17701 Multithreaded applications have even more problems with @code{volatile},
17702 but they are beyond the scope of this section.
17704 The bottom line is that using @code{volatile} typically hurts
17705 performance but should not hurt correctness.  In some cases its use
17706 does help correctness, but these cases are often so poorly understood
17707 that all too often adding @code{volatile} to a data structure merely
17708 alleviates some symptoms of a bug while not fixing the bug in general.
17710 @node Floating Point Portability
17711 @section Floating Point Portability
17712 @cindex floating point
17714 Almost all modern systems use IEEE-754 floating point, and it is safe to
17715 assume IEEE-754 in most portable code these days.  For more information,
17716 please see David Goldberg's classic paper
17717 @uref{http://@/www.validlab.com/@/goldberg/@/paper.pdf, What Every Computer
17718 Scientist Should Know About Floating-Point Arithmetic}.
17720 @node Exiting Portably
17721 @section Exiting Portably
17722 @cindex exiting portably
17724 A C or C++ program can exit with status @var{N} by returning
17725 @var{N} from the @code{main} function.  Portable programs are supposed
17726 to exit either with status 0 or @code{EXIT_SUCCESS} to succeed, or with
17727 status @code{EXIT_FAILURE} to fail, but in practice it is portable to
17728 fail by exiting with status 1, and test programs that assume Posix can
17729 fail by exiting with status values from 1 through 255.  Programs on
17730 SunOS 2.0 (1985) through 3.5.2 (1988) incorrectly exited with zero
17731 status when @code{main} returned nonzero, but ancient systems like these
17732 are no longer of practical concern.
17734 A program can also exit with status @var{N} by passing @var{N} to the
17735 @code{exit} function, and a program can fail by calling the @code{abort}
17736 function.  If a program is specialized to just some platforms, it can fail
17737 by calling functions specific to those platforms, e.g., @code{_exit}
17738 (Posix) and @code{_Exit} (C99).  However, like other functions, an exit
17739 function should be declared, typically by including a header.  For
17740 example, if a C program calls @code{exit}, it should include @file{stdlib.h}
17741 either directly or via the default includes (@pxref{Default Includes}).
17743 A program can fail due to undefined behavior such as dereferencing a null
17744 pointer, but this is not recommended as undefined behavior allows an
17745 implementation to do whatever it pleases and this includes exiting
17746 successfully.
17749 @c ================================================== Manual Configuration
17751 @node Manual Configuration
17752 @chapter Manual Configuration
17754 A few kinds of features can't be guessed automatically by running test
17755 programs.  For example, the details of the object-file format, or
17756 special options that need to be passed to the compiler or linker.  You
17757 can check for such features using ad-hoc means, such as having
17758 @command{configure} check the output of the @code{uname} program, or
17759 looking for libraries that are unique to particular systems.  However,
17760 Autoconf provides a uniform method for handling unguessable features.
17762 @menu
17763 * Specifying Names::            Specifying the system type
17764 * Canonicalizing::              Getting the canonical system type
17765 * Using System Type::           What to do with the system type
17766 @end menu
17768 @node Specifying Names
17769 @section Specifying the System Type
17770 @cindex System type
17772 Autoconf-generated
17773 @command{configure} scripts can make decisions based on a canonical name
17774 for the system type, which has the form:
17775 @samp{@var{cpu}-@var{vendor}-@var{os}}, where @var{os} can be
17776 @samp{@var{system}} or @samp{@var{kernel}-@var{system}}
17778 @command{configure} can usually guess the canonical name for the type of
17779 system it's running on.  To do so it runs a script called
17780 @command{config.guess}, which infers the name using the @code{uname}
17781 command or symbols predefined by the C preprocessor.
17783 Alternately, the user can specify the system type with command line
17784 arguments to @command{configure}.  Doing so is necessary when
17785 cross-compiling.  In the most complex case of cross-compiling, three
17786 system types are involved.  The options to specify them are:
17788 @table @option
17789 @item --build=@var{build-type}
17790 the type of system on which the package is being configured and
17791 compiled.  It defaults to the result of running @command{config.guess}.
17793 @item --host=@var{host-type}
17794 the type of system on which the package runs.  By default it is the
17795 same as the build machine.  Specifying it enables the cross-compilation
17796 mode.
17798 @item --target=@var{target-type}
17799 the type of system for which any compiler tools in the package
17800 produce code (rarely needed).  By default, it is the same as host.
17801 @end table
17803 If you mean to override the result of @command{config.guess}, use
17804 @option{--build}, not @option{--host}, since the latter enables
17805 cross-compilation.  For historical reasons,
17806 whenever you specify @option{--host},
17807 be sure to specify @option{--build} too; this will be fixed in the
17808 future.  So, to enter cross-compilation mode, use a command like this
17810 @example
17811 ./configure --build=i686-pc-linux-gnu --host=m68k-coff
17812 @end example
17814 @noindent
17815 Note that if you do not specify @option{--host}, @command{configure}
17816 fails if it can't run the code generated by the specified compiler.  For
17817 example, configuring as follows fails:
17819 @example
17820 ./configure CC=m68k-coff-gcc
17821 @end example
17823 When cross-compiling, @command{configure} will warn about any tools
17824 (compilers, linkers, assemblers) whose name is not prefixed with the
17825 host type.  This is an aid to users performing cross-compilation.
17826 Continuing the example above, if a cross-compiler named @command{cc} is
17827 used with a native @command{pkg-config}, then libraries found by
17828 @command{pkg-config} will likely cause subtle build failures; but using
17829 the names @command{m68k-coff-cc} and @command{m68k-coff-pkg-config}
17830 avoids any confusion.  Avoiding the warning is as simple as creating the
17831 correct symlinks naming the cross tools.
17833 @cindex @command{config.sub}
17834 @command{configure} recognizes short aliases for many system types; for
17835 example, @samp{decstation} can be used instead of
17836 @samp{mips-dec-ultrix4.2}.  @command{configure} runs a script called
17837 @command{config.sub} to canonicalize system type aliases.
17839 This section deliberately omits the description of the obsolete
17840 interface; see @ref{Hosts and Cross-Compilation}.
17843 @node Canonicalizing
17844 @section Getting the Canonical System Type
17845 @cindex System type
17846 @cindex Canonical system type
17848 The following macros make the system type available to @command{configure}
17849 scripts.
17851 @ovindex build_alias
17852 @ovindex host_alias
17853 @ovindex target_alias
17855 The variables @samp{build_alias}, @samp{host_alias}, and
17856 @samp{target_alias} are always exactly the arguments of @option{--build},
17857 @option{--host}, and @option{--target}; in particular, they are left empty
17858 if the user did not use them, even if the corresponding
17859 @code{AC_CANONICAL} macro was run.  Any configure script may use these
17860 variables anywhere.  These are the variables that should be used when in
17861 interaction with the user.
17863 If you need to recognize some special environments based on their system
17864 type, run the following macros to get canonical system names.  These
17865 variables are not set before the macro call.
17867 If you use these macros, you must distribute @command{config.guess} and
17868 @command{config.sub} along with your source code.  @xref{Output}, for
17869 information about the @code{AC_CONFIG_AUX_DIR} macro which you can use
17870 to control in which directory @command{configure} looks for those scripts.
17873 @defmac AC_CANONICAL_BUILD
17874 @acindex{CANONICAL_BUILD}
17875 @ovindex build
17876 @ovindex build_cpu
17877 @ovindex build_vendor
17878 @ovindex build_os
17879 Compute the canonical build-system type variable, @code{build}, and its
17880 three individual parts @code{build_cpu}, @code{build_vendor}, and
17881 @code{build_os}.
17883 If @option{--build} was specified, then @code{build} is the
17884 canonicalization of @code{build_alias} by @command{config.sub},
17885 otherwise it is determined by the shell script @command{config.guess}.
17886 @end defmac
17888 @defmac AC_CANONICAL_HOST
17889 @acindex{CANONICAL_HOST}
17890 @ovindex host
17891 @ovindex host_cpu
17892 @ovindex host_vendor
17893 @ovindex host_os
17894 Compute the canonical host-system type variable, @code{host}, and its
17895 three individual parts @code{host_cpu}, @code{host_vendor}, and
17896 @code{host_os}.
17898 If @option{--host} was specified, then @code{host} is the
17899 canonicalization of @code{host_alias} by @command{config.sub},
17900 otherwise it defaults to @code{build}.
17901 @end defmac
17903 @defmac AC_CANONICAL_TARGET
17904 @acindex{CANONICAL_TARGET}
17905 @ovindex target
17906 @ovindex target_cpu
17907 @ovindex target_vendor
17908 @ovindex target_os
17909 Compute the canonical target-system type variable, @code{target}, and its
17910 three individual parts @code{target_cpu}, @code{target_vendor}, and
17911 @code{target_os}.
17913 If @option{--target} was specified, then @code{target} is the
17914 canonicalization of @code{target_alias} by @command{config.sub},
17915 otherwise it defaults to @code{host}.
17916 @end defmac
17918 Note that there can be artifacts due to the backward compatibility
17919 code.  See @xref{Hosts and Cross-Compilation}, for more.
17921 @node Using System Type
17922 @section Using the System Type
17924 In @file{configure.ac} the system type is generally used by one or more
17925 @code{case} statements to select system-specifics.  Shell wildcards can
17926 be used to match a group of system types.
17928 For example, an extra assembler code object file could be chosen, giving
17929 access to a CPU cycle counter register.  @code{$(CYCLE_OBJ)} in the
17930 following would be used in a makefile to add the object to a
17931 program or library.
17933 @example
17934 case $host in
17935   alpha*-*-*) CYCLE_OBJ=rpcc.o ;;
17936   i?86-*-*)   CYCLE_OBJ=rdtsc.o ;;
17937   *)          CYCLE_OBJ= ;;
17938 esac
17939 AC_SUBST([CYCLE_OBJ])
17940 @end example
17942 @code{AC_CONFIG_LINKS} (@pxref{Configuration Links}) is another good way
17943 to select variant source files, for example optimized code for some
17944 CPUs.  The configured CPU type doesn't always indicate exact CPU types,
17945 so some runtime capability checks may be necessary too.
17947 @example
17948 case $host in
17949   alpha*-*-*)   AC_CONFIG_LINKS([dither.c:alpha/dither.c]) ;;
17950   powerpc*-*-*) AC_CONFIG_LINKS([dither.c:powerpc/dither.c]) ;;
17951   *-*-*)        AC_CONFIG_LINKS([dither.c:generic/dither.c]) ;;
17952 esac
17953 @end example
17955 The host system type can also be used to find cross-compilation tools
17956 with @code{AC_CHECK_TOOL} (@pxref{Generic Programs}).
17958 The above examples all show @samp{$host}, since this is where the code
17959 is going to run.  Only rarely is it necessary to test @samp{$build}
17960 (which is where the build is being done).
17962 Whenever you're tempted to use @samp{$host} it's worth considering
17963 whether some sort of probe would be better.  New system types come along
17964 periodically or previously missing features are added.  Well-written
17965 probes can adapt themselves to such things, but hard-coded lists of
17966 names can't.  Here are some guidelines,
17968 @itemize @bullet
17969 @item
17970 Availability of libraries and library functions should always be checked
17971 by probing.
17972 @item
17973 Variant behavior of system calls is best identified with runtime tests
17974 if possible, but bug workarounds or obscure difficulties might have to
17975 be driven from @samp{$host}.
17976 @item
17977 Assembler code is inevitably highly CPU-specific and is best selected
17978 according to @samp{$host_cpu}.
17979 @item
17980 Assembler variations like underscore prefix on globals or ELF versus
17981 COFF type directives are however best determined by probing, perhaps
17982 even examining the compiler output.
17983 @end itemize
17985 @samp{$target} is for use by a package creating a compiler or similar.
17986 For ordinary packages it's meaningless and should not be used.  It
17987 indicates what the created compiler should generate code for, if it can
17988 cross-compile.  @samp{$target} generally selects various hard-coded CPU
17989 and system conventions, since usually the compiler or tools under
17990 construction themselves determine how the target works.
17993 @c ===================================================== Site Configuration.
17995 @node Site Configuration
17996 @chapter Site Configuration
17998 @command{configure} scripts support several kinds of local configuration
17999 decisions.  There are ways for users to specify where external software
18000 packages are, include or exclude optional features, install programs
18001 under modified names, and set default values for @command{configure}
18002 options.
18004 @menu
18005 * Help Formatting::             Customizing @samp{configure --help}
18006 * External Software::           Working with other optional software
18007 * Package Options::             Selecting optional features
18008 * Pretty Help Strings::         Formatting help string
18009 * Option Checking::             Controlling checking of @command{configure} options
18010 * Site Details::                Configuring site details
18011 * Transforming Names::          Changing program names when installing
18012 * Site Defaults::               Giving @command{configure} local defaults
18013 @end menu
18015 @node Help Formatting
18016 @section Controlling Help Output
18018 Users consult @samp{configure --help} to learn of configuration
18019 decisions specific to your package.  By default, @command{configure}
18020 breaks this output into sections for each type of option; within each
18021 section, help strings appear in the order @file{configure.ac} defines
18022 them:
18024 @example
18025 Optional Features:
18026   @dots{}
18027   --enable-bar            include bar
18029 Optional Packages:
18030   @dots{}
18031   --with-foo              use foo
18032 @end example
18034 @defmac AC_PRESERVE_HELP_ORDER
18035 @acindex{PRESERVE_HELP_ORDER}
18037 Request an alternate @option{--help} format, in which options of all
18038 types appear together, in the order defined.  Call this macro before any
18039 @code{AC_ARG_ENABLE} or @code{AC_ARG_WITH}.
18041 @example
18042 Optional Features and Packages:
18043   @dots{}
18044   --enable-bar            include bar
18045   --with-foo              use foo
18046 @end example
18048 @end defmac
18050 @node External Software
18051 @section Working With External Software
18052 @cindex External software
18054 Some packages require, or can optionally use, other software packages
18055 that are already installed.  The user can give @command{configure}
18056 command line options to specify which such external software to use.
18057 The options have one of these forms:
18059 @c FIXME: Can't use @ovar here, Texinfo 4.0 goes lunatic and emits something
18060 @c awful.
18061 @example
18062 --with-@var{package}[=@var{arg}]
18063 --without-@var{package}
18064 @end example
18066 For example, @option{--with-gnu-ld} means work with the @acronym{GNU} linker
18067 instead of some other linker.  @option{--with-x} means work with The X
18068 Window System.
18070 The user can give an argument by following the package name with
18071 @samp{=} and the argument.  Giving an argument of @samp{no} is for
18072 packages that are used by default; it says to @emph{not} use the
18073 package.  An argument that is neither @samp{yes} nor @samp{no} could
18074 include a name or number of a version of the other package, to specify
18075 more precisely which other package this program is supposed to work
18076 with.  If no argument is given, it defaults to @samp{yes}.
18077 @option{--without-@var{package}} is equivalent to
18078 @option{--with-@var{package}=no}.
18080 Normally @command{configure} scripts complain about
18081 @option{--with-@var{package}} options that they do not support.
18082 @xref{Option Checking}, for details, and for how to override the
18083 defaults.
18085 For each external software package that may be used, @file{configure.ac}
18086 should call @code{AC_ARG_WITH} to detect whether the @command{configure}
18087 user asked to use it.  Whether each package is used or not by default,
18088 and which arguments are valid, is up to you.
18090 @anchor{AC_ARG_WITH}
18091 @defmac AC_ARG_WITH (@var{package}, @var{help-string}, @
18092   @ovar{action-if-given}, @ovar{action-if-not-given})
18093 @acindex{ARG_WITH}
18094 If the user gave @command{configure} the option @option{--with-@var{package}}
18095 or @option{--without-@var{package}}, run shell commands
18096 @var{action-if-given}.  If neither option was given, run shell commands
18097 @var{action-if-not-given}.  The name @var{package} indicates another
18098 software package that this program should work with.  It should consist
18099 only of alphanumeric characters, dashes, and dots.
18101 The option's argument is available to the shell commands
18102 @var{action-if-given} in the shell variable @code{withval}, which is
18103 actually just the value of the shell variable named
18104 @code{with_@var{package}}, with any non-alphanumeric characters in
18105 @var{package} changed into @samp{_}.  You may use that variable instead,
18106 if you wish.
18108 The argument @var{help-string} is a description of the option that
18109 looks like this:
18110 @example
18111   --with-readline         support fancy command line editing
18112 @end example
18114 @noindent
18115 @var{help-string} may be more than one line long, if more detail is
18116 needed.  Just make sure the columns line up in @samp{configure
18117 --help}.  Avoid tabs in the help string.  You'll need to enclose the
18118 help string in @samp{[} and @samp{]} in order to produce the leading
18119 blanks.
18121 You should format your @var{help-string} with the macro
18122 @code{AS_HELP_STRING} (@pxref{Pretty Help Strings}).
18124 The following example shows how to use the @code{AC_ARG_WITH} macro in
18125 a common situation.  You want to let the user decide whether to enable
18126 support for an external library (e.g., the readline library); if the user
18127 specified neither @option{--with-readline} nor @option{--without-readline},
18128 you want to enable support for readline only if the library is available
18129 on the system.
18131 @c FIXME: Remove AS_IF when the problem of AC_REQUIRE within `if' is solved.
18132 @example
18133 AC_ARG_WITH([readline],
18134   [AS_HELP_STRING([--with-readline],
18135     [support fancy command line editing @@<:@@default=check@@:>@@])],
18136   [],
18137   [with_readline=check])
18139 LIBREADLINE=
18140 AS_IF([test "x$with_readline" != xno],
18141   [AC_CHECK_LIB([readline], [main],
18142     [AC_SUBST([LIBREADLINE], ["-lreadline -lncurses"])
18143      AC_DEFINE([HAVE_LIBREADLINE], [1],
18144                [Define if you have libreadline])
18145     ],
18146     [if test "x$with_readline" != xcheck; then
18147        AC_MSG_FAILURE(
18148          [--with-readline was given, but test for readline failed])
18149      fi
18150     ], -lncurses)])
18151 @end example
18153 The next example shows how to use @code{AC_ARG_WITH} to give the user the
18154 possibility to enable support for the readline library, in case it is still
18155 experimental and not well tested, and is therefore disabled by default.
18157 @c FIXME: Remove AS_IF when the problem of AC_REQUIRE within `if' is solved.
18158 @example
18159 AC_ARG_WITH([readline],
18160   [AS_HELP_STRING([--with-readline],
18161     [enable experimental support for readline])],
18162   [],
18163   [with_readline=no])
18165 LIBREADLINE=
18166 AS_IF([test "x$with_readline" != xno],
18167   [AC_CHECK_LIB([readline], [main],
18168     [AC_SUBST([LIBREADLINE], ["-lreadline -lncurses"])
18169      AC_DEFINE([HAVE_LIBREADLINE], [1],
18170                [Define if you have libreadline])
18171     ],
18172     [AC_MSG_FAILURE(
18173        [--with-readline was given, but test for readline failed])],
18174     [-lncurses])])
18175 @end example
18177 The last example shows how to use @code{AC_ARG_WITH} to give the user the
18178 possibility to disable support for the readline library, given that it is
18179 an important feature and that it should be enabled by default.
18181 @c FIXME: Remove AS_IF when the problem of AC_REQUIRE within `if' is solved.
18182 @example
18183 AC_ARG_WITH([readline],
18184   [AS_HELP_STRING([--without-readline],
18185     [disable support for readline])],
18186   [],
18187   [with_readline=yes])
18189 LIBREADLINE=
18190 AS_IF([test "x$with_readline" != xno],
18191   [AC_CHECK_LIB([readline], [main],
18192     [AC_SUBST([LIBREADLINE], ["-lreadline -lncurses"])
18193      AC_DEFINE([HAVE_LIBREADLINE], [1],
18194                [Define if you have libreadline])
18195     ],
18196     [AC_MSG_FAILURE(
18197        [readline test failed (--without-readline to disable)])],
18198     [-lncurses])])
18199 @end example
18201 These three examples can be easily adapted to the case where
18202 @code{AC_ARG_ENABLE} should be preferred to @code{AC_ARG_WITH} (see
18203 @ref{Package Options}).
18204 @end defmac
18206 @node Package Options
18207 @section Choosing Package Options
18208 @cindex Package options
18209 @cindex Options, package
18211 If a software package has optional compile-time features, the user can
18212 give @command{configure} command line options to specify whether to
18213 compile them.  The options have one of these forms:
18215 @c FIXME: Can't use @ovar here, Texinfo 4.0 goes lunatic and emits something
18216 @c awful.
18217 @example
18218 --enable-@var{feature}[=@var{arg}]
18219 --disable-@var{feature}
18220 @end example
18222 These options allow users to choose which optional features to build and
18223 install.  @option{--enable-@var{feature}} options should never make a
18224 feature behave differently or cause one feature to replace another.
18225 They should only cause parts of the program to be built rather than left
18226 out.
18228 The user can give an argument by following the feature name with
18229 @samp{=} and the argument.  Giving an argument of @samp{no} requests
18230 that the feature @emph{not} be made available.  A feature with an
18231 argument looks like @option{--enable-debug=stabs}.  If no argument is
18232 given, it defaults to @samp{yes}.  @option{--disable-@var{feature}} is
18233 equivalent to @option{--enable-@var{feature}=no}.
18235 Normally @command{configure} scripts complain about
18236 @option{--enable-@var{package}} options that they do not support.
18237 @xref{Option Checking}, for details, and for how to override the
18238 defaults.
18240 For each optional feature, @file{configure.ac} should call
18241 @code{AC_ARG_ENABLE} to detect whether the @command{configure} user asked
18242 to include it.  Whether each feature is included or not by default, and
18243 which arguments are valid, is up to you.
18245 @anchor{AC_ARG_ENABLE}
18246 @defmac AC_ARG_ENABLE (@var{feature}, @var{help-string}, @
18247   @ovar{action-if-given}, @ovar{action-if-not-given})
18248 @acindex{ARG_ENABLE}
18249 If the user gave @command{configure} the option
18250 @option{--enable-@var{feature}} or @option{--disable-@var{feature}}, run
18251 shell commands @var{action-if-given}.  If neither option was given, run
18252 shell commands @var{action-if-not-given}.  The name @var{feature}
18253 indicates an optional user-level facility.  It should consist only of
18254 alphanumeric characters, dashes, and dots.
18256 The option's argument is available to the shell commands
18257 @var{action-if-given} in the shell variable @code{enableval}, which is
18258 actually just the value of the shell variable named
18259 @code{enable_@var{feature}}, with any non-alphanumeric characters in
18260 @var{feature} changed into @samp{_}.  You may use that variable instead,
18261 if you wish.  The @var{help-string} argument is like that of
18262 @code{AC_ARG_WITH} (@pxref{External Software}).
18264 You should format your @var{help-string} with the macro
18265 @code{AS_HELP_STRING} (@pxref{Pretty Help Strings}).
18267 See the examples suggested with the definition of @code{AC_ARG_WITH}
18268 (@pxref{External Software}) to get an idea of possible applications of
18269 @code{AC_ARG_ENABLE}.
18270 @end defmac
18272 @node Pretty Help Strings
18273 @section Making Your Help Strings Look Pretty
18274 @cindex Help strings
18276 Properly formatting the @samp{help strings} which are used in
18277 @code{AC_ARG_WITH} (@pxref{External Software}) and @code{AC_ARG_ENABLE}
18278 (@pxref{Package Options}) can be challenging.  Specifically, you want
18279 your own @samp{help strings} to line up in the appropriate columns of
18280 @samp{configure --help} just like the standard Autoconf @samp{help
18281 strings} do.  This is the purpose of the @code{AS_HELP_STRING} macro.
18283 @anchor{AS_HELP_STRING}
18284 @defmac AS_HELP_STRING (@var{left-hand-side}, @var{right-hand-side} @
18285   @dvar{indent-column, 26}, @dvar{wrap-column, 79})
18286 @asindex{HELP_STRING}
18288 Expands into an help string that looks pretty when the user executes
18289 @samp{configure --help}.  It is typically used in @code{AC_ARG_WITH}
18290 (@pxref{External Software}) or @code{AC_ARG_ENABLE} (@pxref{Package
18291 Options}).  The following example makes this clearer.
18293 @example
18294 AC_ARG_WITH([foo],
18295   [AS_HELP_STRING([--with-foo],
18296      [use foo (default is no)])],
18297   [use_foo=$withval],
18298   [use_foo=no])
18299 @end example
18301 Then the last few lines of @samp{configure --help} appear like
18302 this:
18304 @example
18305 --enable and --with options recognized:
18306   --with-foo              use foo (default is no)
18307 @end example
18309 Macro expansion is performed on the first argument.  However, the second
18310 argument of @code{AS_HELP_STRING} is treated as a whitespace separated
18311 list of text to be reformatted, and is not subject to macro expansion.
18312 Since it is not expanded, it should not be double quoted.
18313 @xref{Autoconf Language}, for a more detailed explanation.
18315 The @code{AS_HELP_STRING} macro is particularly helpful when the
18316 @var{left-hand-side} and/or @var{right-hand-side} are composed of macro
18317 arguments, as shown in the following example.  Be aware that
18318 @var{left-hand-side} may not expand to unbalanced quotes,
18319 although quadrigraphs can be used.
18321 @example
18322 AC_DEFUN([MY_ARG_WITH],
18323   [AC_ARG_WITH(m4_translit([[$1]], [_], [-]),
18324      [AS_HELP_STRING([--with-m4_translit([$1], [_], [-])],
18325                      [use $1 (default is $2)])],
18326      [use_[]$1=$withval],
18327      [use_[]$1=$2])])
18328 MY_ARG_WITH([a_b], [no])
18329 @end example
18330 @noindent
18331 Here, the last few lines of @samp{configure --help} will include:
18333 @example
18334 --enable and --with options recognized:
18335   --with-a-b              use a_b (default is no)
18336 @end example
18338 The parameters @var{indent-column} and @var{wrap-column} were introduced
18339 in Autoconf 2.62.  Generally, they should not be specified; they exist
18340 for fine-tuning of the wrapping.
18341 @example
18342 AS_HELP_STRING([--option], [description of option])
18343 @result{}  --option                description of option
18344 AS_HELP_STRING([--option], [description of option], [15], [30])
18345 @result{}  --option     description of
18346 @result{}               option
18347 @end example
18348 @end defmac
18351 @node Option Checking
18352 @section Controlling Checking of @command{configure} Options
18353 @cindex Options, Package
18355 The @command{configure} script checks its command-line options against a
18356 list of known options, like @option{--help} or @option{--config-cache}.
18357 An unknown option ordinarily indicates a mistake by the user and
18358 @command{configure} halts with an error.  However, by default unknown
18359 @option{--with-@var{package}} and @option{--enable-@var{feature}}
18360 options elicit only a warning, to support configuring entire source
18361 trees.
18363 Source trees often contain multiple packages with a top-level
18364 @command{configure} script that uses the @code{AC_CONFIG_SUBDIRS} macro
18365 (@pxref{Subdirectories}).  Because the packages generally support
18366 different @option{--with-@var{package}} and
18367 @option{--enable-@var{feature}} options, the @acronym{GNU} Coding
18368 Standards say they must accept unrecognized options without halting.
18369 Even a warning message is undesirable here, so @code{AC_CONFIG_SUBDIRS}
18370 automatically disables the warnings.
18372 This default behavior may be modified in two ways.  First, the installer
18373 can invoke @code{configure --disable-option-checking} to disable
18374 these warnings, or invoke @code{configure --enable-option-checking=fatal}
18375 options to turn them into fatal errors, respectively.  Second, the
18376 maintainer can use @code{AC_DISABLE_OPTION_CHECKING}.
18378 @defmac AC_DISABLE_OPTION_CHECKING
18379 @acindex{DISABLE_OPTION_CHECKING}
18381 By default, disable warnings related to any unrecognized
18382 @option{--with-@var{package}} or @option{--enable-@var{feature}}
18383 options.  This is implied by @code{AC_CONFIG_SUBDIRS}.
18385 The installer can override this behavior by passing
18386 @option{--enable-option-checking} (enable warnings) or
18387 @option{--enable-option-checking=fatal} (enable errors) to
18388 @command{configure}.
18389 @end defmac
18392 @node Site Details
18393 @section Configuring Site Details
18394 @cindex Site details
18396 Some software packages require complex site-specific information.  Some
18397 examples are host names to use for certain services, company names, and
18398 email addresses to contact.  Since some configuration scripts generated
18399 by Metaconfig ask for such information interactively, people sometimes
18400 wonder how to get that information in Autoconf-generated configuration
18401 scripts, which aren't interactive.
18403 Such site configuration information should be put in a file that is
18404 edited @emph{only by users}, not by programs.  The location of the file
18405 can either be based on the @code{prefix} variable, or be a standard
18406 location such as the user's home directory.  It could even be specified
18407 by an environment variable.  The programs should examine that file at
18408 runtime, rather than at compile time.  Runtime configuration is more
18409 convenient for users and makes the configuration process simpler than
18410 getting the information while configuring.  @xref{Directory Variables, ,
18411 Variables for Installation Directories, standards, @acronym{GNU} Coding
18412 Standards}, for more information on where to put data files.
18414 @node Transforming Names
18415 @section Transforming Program Names When Installing
18416 @cindex Transforming program names
18417 @cindex Program names, transforming
18419 Autoconf supports changing the names of programs when installing them.
18420 In order to use these transformations, @file{configure.ac} must call the
18421 macro @code{AC_ARG_PROGRAM}.
18423 @defmac AC_ARG_PROGRAM
18424 @acindex{ARG_PROGRAM}
18425 @ovindex program_transform_name
18426 Place in output variable @code{program_transform_name} a sequence of
18427 @code{sed} commands for changing the names of installed programs.
18429 If any of the options described below are given to @command{configure},
18430 program names are transformed accordingly.  Otherwise, if
18431 @code{AC_CANONICAL_TARGET} has been called and a @option{--target} value
18432 is given, the target type followed by a dash is used as a prefix.
18433 Otherwise, no program name transformation is done.
18434 @end defmac
18436 @menu
18437 * Transformation Options::      @command{configure} options to transform names
18438 * Transformation Examples::     Sample uses of transforming names
18439 * Transformation Rules::        Makefile uses of transforming names
18440 @end menu
18442 @node Transformation Options
18443 @subsection Transformation Options
18445 You can specify name transformations by giving @command{configure} these
18446 command line options:
18448 @table @option
18449 @item --program-prefix=@var{prefix}
18450 prepend @var{prefix} to the names;
18452 @item --program-suffix=@var{suffix}
18453 append @var{suffix} to the names;
18455 @item --program-transform-name=@var{expression}
18456 perform @code{sed} substitution @var{expression} on the names.
18457 @end table
18459 @node Transformation Examples
18460 @subsection Transformation Examples
18462 These transformations are useful with programs that can be part of a
18463 cross-compilation development environment.  For example, a
18464 cross-assembler running on a Sun 4 configured with
18465 @option{--target=i960-vxworks} is normally installed as
18466 @file{i960-vxworks-as}, rather than @file{as}, which could be confused
18467 with a native Sun 4 assembler.
18469 You can force a program name to begin with @file{g}, if you don't want
18470 @acronym{GNU} programs installed on your system to shadow other programs with
18471 the same name.  For example, if you configure @acronym{GNU} @code{diff} with
18472 @option{--program-prefix=g}, then when you run @samp{make install} it is
18473 installed as @file{/usr/local/bin/gdiff}.
18475 As a more sophisticated example, you could use
18477 @example
18478 --program-transform-name='s/^/g/; s/^gg/g/; s/^gless/less/'
18479 @end example
18480 @noindent
18482 to prepend @samp{g} to most of the program names in a source tree,
18483 excepting those like @code{gdb} that already have one and those like
18484 @code{less} and @code{lesskey} that aren't @acronym{GNU} programs.  (That is
18485 assuming that you have a source tree containing those programs that is
18486 set up to use this feature.)
18488 One way to install multiple versions of some programs simultaneously is
18489 to append a version number to the name of one or both.  For example, if
18490 you want to keep Autoconf version 1 around for awhile, you can configure
18491 Autoconf version 2 using @option{--program-suffix=2} to install the
18492 programs as @file{/usr/local/bin/autoconf2},
18493 @file{/usr/local/bin/autoheader2}, etc.  Nevertheless, pay attention
18494 that only the binaries are renamed, therefore you'd have problems with
18495 the library files which might overlap.
18497 @node Transformation Rules
18498 @subsection Transformation Rules
18500 Here is how to use the variable @code{program_transform_name} in a
18501 @file{Makefile.in}:
18503 @example
18504 PROGRAMS = cp ls rm
18505 transform = @@program_transform_name@@
18506 install:
18507         for p in $(PROGRAMS); do \
18508           $(INSTALL_PROGRAM) $$p $(DESTDIR)$(bindir)/`echo $$p | \
18509                                               sed '$(transform)'`; \
18510         done
18512 uninstall:
18513         for p in $(PROGRAMS); do \
18514           rm -f $(DESTDIR)$(bindir)/`echo $$p | sed '$(transform)'`; \
18515         done
18516 @end example
18518 It is guaranteed that @code{program_transform_name} is never empty, and
18519 that there are no useless separators.  Therefore you may safely embed
18520 @code{program_transform_name} within a sed program using @samp{;}:
18522 @example
18523 transform = @@program_transform_name@@
18524 transform_exe = s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/
18525 @end example
18527 Whether to do the transformations on documentation files (Texinfo or
18528 @code{man}) is a tricky question; there seems to be no perfect answer,
18529 due to the several reasons for name transforming.  Documentation is not
18530 usually particular to a specific architecture, and Texinfo files do not
18531 conflict with system documentation.  But they might conflict with
18532 earlier versions of the same files, and @code{man} pages sometimes do
18533 conflict with system documentation.  As a compromise, it is probably
18534 best to do name transformations on @code{man} pages but not on Texinfo
18535 manuals.
18537 @node Site Defaults
18538 @section Setting Site Defaults
18539 @cindex Site defaults
18541 Autoconf-generated @command{configure} scripts allow your site to provide
18542 default values for some configuration values.  You do this by creating
18543 site- and system-wide initialization files.
18545 @evindex CONFIG_SITE
18546 If the environment variable @code{CONFIG_SITE} is set, @command{configure}
18547 uses its value as the name of a shell script to read.  Otherwise, it
18548 reads the shell script @file{@var{prefix}/share/config.site} if it exists,
18549 then @file{@var{prefix}/etc/config.site} if it exists.  Thus,
18550 settings in machine-specific files override those in machine-independent
18551 ones in case of conflict.
18553 Site files can be arbitrary shell scripts, but only certain kinds of
18554 code are really appropriate to be in them.  Because @command{configure}
18555 reads any cache file after it has read any site files, a site file can
18556 define a default cache file to be shared between all Autoconf-generated
18557 @command{configure} scripts run on that system (@pxref{Cache Files}).  If
18558 you set a default cache file in a site file, it is a good idea to also
18559 set the output variable @code{CC} in that site file, because the cache
18560 file is only valid for a particular compiler, but many systems have
18561 several available.
18563 You can examine or override the value set by a command line option to
18564 @command{configure} in a site file; options set shell variables that have
18565 the same names as the options, with any dashes turned into underscores.
18566 The exceptions are that @option{--without-} and @option{--disable-} options
18567 are like giving the corresponding @option{--with-} or @option{--enable-}
18568 option and the value @samp{no}.  Thus, @option{--cache-file=localcache}
18569 sets the variable @code{cache_file} to the value @samp{localcache};
18570 @option{--enable-warnings=no} or @option{--disable-warnings} sets the variable
18571 @code{enable_warnings} to the value @samp{no}; @option{--prefix=/usr} sets the
18572 variable @code{prefix} to the value @samp{/usr}; etc.
18574 Site files are also good places to set default values for other output
18575 variables, such as @code{CFLAGS}, if you need to give them non-default
18576 values: anything you would normally do, repetitively, on the command
18577 line.  If you use non-default values for @var{prefix} or
18578 @var{exec_prefix} (wherever you locate the site file), you can set them
18579 in the site file if you specify it with the @code{CONFIG_SITE}
18580 environment variable.
18582 You can set some cache values in the site file itself.  Doing this is
18583 useful if you are cross-compiling, where it is impossible to check features
18584 that require running a test program.  You could ``prime the cache'' by
18585 setting those values correctly for that system in
18586 @file{@var{prefix}/etc/config.site}.  To find out the names of the cache
18587 variables you need to set, look for shell variables with @samp{_cv_} in
18588 their names in the affected @command{configure} scripts, or in the Autoconf
18589 M4 source code for those macros.
18591 The cache file is careful to not override any variables set in the site
18592 files.  Similarly, you should not override command-line options in the
18593 site files.  Your code should check that variables such as @code{prefix}
18594 and @code{cache_file} have their default values (as set near the top of
18595 @command{configure}) before changing them.
18597 Here is a sample file @file{/usr/share/local/gnu/share/config.site}.  The
18598 command @samp{configure --prefix=/usr/share/local/gnu} would read this
18599 file (if @code{CONFIG_SITE} is not set to a different file).
18601 @example
18602 # config.site for configure
18604 # Change some defaults.
18605 test "$prefix" = NONE && prefix=/usr/share/local/gnu
18606 test "$exec_prefix" = NONE && exec_prefix=/usr/local/gnu
18607 test "$sharedstatedir" = '$@{prefix@}/com' && sharedstatedir=/var
18608 test "$localstatedir" = '$@{prefix@}/var' && localstatedir=/var
18610 # Give Autoconf 2.x generated configure scripts a shared default
18611 # cache file for feature test results, architecture-specific.
18612 if test "$cache_file" = /dev/null; then
18613   cache_file="$prefix/var/config.cache"
18614   # A cache file is only valid for one C compiler.
18615   CC=gcc
18617 @end example
18619 @cindex Filesystem Hierarchy Standard
18620 @cindex FHS
18622 Another use of @file{config.site} is for priming the directory variables
18623 in a manner consistent with the Filesystem Hierarchy Standard
18624 (@acronym{FHS}).  Once the following file is installed at
18625 @file{/usr/share/config.site}, a user can execute simply
18626 @code{./configure --prefix=/usr} to get all the directories chosen in
18627 the locations recommended by @acronym{FHS}.
18629 @example
18630 # /usr/local/config.site for FHS defaults when installing below /usr,
18631 # and the respective settings were not changed on the command line.
18632 if test "$prefix" = /usr; then
18633   test "$sysconfdir" = '$@{prefix@}/etc' && sysconfdir=/etc
18634   test "$sharedstatedir" = '$@{prefix@}/com' && sharedstatedir=/var
18635   test "$localstatedir" = '$@{prefix@}/var' && localstatedir=/var
18637 @end example
18640 @c ============================================== Running configure Scripts.
18642 @node Running configure Scripts
18643 @chapter Running @command{configure} Scripts
18644 @cindex @command{configure}
18646 Below are instructions on how to configure a package that uses a
18647 @command{configure} script, suitable for inclusion as an @file{INSTALL}
18648 file in the package.  A plain-text version of @file{INSTALL} which you
18649 may use comes with Autoconf.
18651 @menu
18652 * Basic Installation::          Instructions for typical cases
18653 * Compilers and Options::       Selecting compilers and optimization
18654 * Multiple Architectures::      Compiling for multiple architectures at once
18655 * Installation Names::          Installing in different directories
18656 * Optional Features::           Selecting optional features
18657 * Particular Systems::          Particular systems
18658 * System Type::                 Specifying the system type
18659 * Sharing Defaults::            Setting site-wide defaults for @command{configure}
18660 * Defining Variables::          Specifying the compiler etc.
18661 * configure Invocation::        Changing how @command{configure} runs
18662 @end menu
18664 @set autoconf
18665 @include install.texi
18668 @c ============================================== config.status Invocation
18670 @node config.status Invocation
18671 @chapter config.status Invocation
18672 @cindex @command{config.status}
18674 The @command{configure} script creates a file named @file{config.status},
18675 which actually configures, @dfn{instantiates}, the template files.  It
18676 also records the configuration options that were specified when the
18677 package was last configured in case reconfiguring is needed.
18679 Synopsis:
18680 @example
18681 ./config.status @var{option}@dots{} [@var{file}@dots{}]
18682 @end example
18684 It configures the @var{files}; if none are specified, all the templates
18685 are instantiated.  The files must be specified without their
18686 dependencies, as in
18688 @example
18689 ./config.status foobar
18690 @end example
18692 @noindent
18695 @example
18696 ./config.status foobar:foo.in:bar.in
18697 @end example
18699 The supported options are:
18701 @table @option
18702 @item --help
18703 @itemx -h
18704 Print a summary of the command line options, the list of the template
18705 files, and exit.
18707 @item --version
18708 @itemx -V
18709 Print the version number of Autoconf and the configuration settings,
18710 and exit.
18712 @item --silent
18713 @itemx --quiet
18714 @itemx -q
18715 Do not print progress messages.
18717 @item --debug
18718 @itemx -d
18719 Don't remove the temporary files.
18721 @item --file=@var{file}[:@var{template}]
18722 Require that @var{file} be instantiated as if
18723 @samp{AC_CONFIG_FILES(@var{file}:@var{template})} was used.  Both
18724 @var{file} and @var{template} may be @samp{-} in which case the standard
18725 output and/or standard input, respectively, is used.  If a
18726 @var{template} file name is relative, it is first looked for in the build
18727 tree, and then in the source tree.  @xref{Configuration Actions}, for
18728 more details.
18730 This option and the following ones provide one way for separately
18731 distributed packages to share the values computed by @command{configure}.
18732 Doing so can be useful if some of the packages need a superset of the
18733 features that one of them, perhaps a common library, does.  These
18734 options allow a @file{config.status} file to create files other than the
18735 ones that its @file{configure.ac} specifies, so it can be used for a
18736 different package.
18738 @item --header=@var{file}[:@var{template}]
18739 Same as @option{--file} above, but with @samp{AC_CONFIG_HEADERS}.
18741 @item --recheck
18742 Ask @file{config.status} to update itself and exit (no instantiation).
18743 This option is useful if you change @command{configure}, so that the
18744 results of some tests might be different from the previous run.  The
18745 @option{--recheck} option reruns @command{configure} with the same arguments
18746 you used before, plus the @option{--no-create} option, which prevents
18747 @command{configure} from running @file{config.status} and creating
18748 @file{Makefile} and other files, and the @option{--no-recursion} option,
18749 which prevents @command{configure} from running other @command{configure}
18750 scripts in subdirectories.  (This is so other Make rules can
18751 run @file{config.status} when it changes; @pxref{Automatic Remaking},
18752 for an example).
18753 @end table
18755 @file{config.status} checks several optional environment variables that
18756 can alter its behavior:
18758 @defvar CONFIG_SHELL
18759 @evindex CONFIG_SHELL
18760 The shell with which to run @command{configure} for the @option{--recheck}
18761 option.  It must be Bourne-compatible.  The default is a shell that
18762 supports @code{LINENO} if available, and @file{/bin/sh} otherwise.
18763 Invoking @command{configure} by hand bypasses this setting, so you may
18764 need to use a command like @samp{CONFIG_SHELL=/bin/bash /bin/bash ./configure}
18765 to insure that the same shell is used everywhere.  The absolute name of the
18766 shell should be passed.
18767 @end defvar
18769 @defvar CONFIG_STATUS
18770 @evindex CONFIG_STATUS
18771 The file name to use for the shell script that records the
18772 configuration.  The default is @file{./config.status}.  This variable is
18773 useful when one package uses parts of another and the @command{configure}
18774 scripts shouldn't be merged because they are maintained separately.
18775 @end defvar
18777 You can use @file{./config.status} in your makefiles.  For example, in
18778 the dependencies given above (@pxref{Automatic Remaking}),
18779 @file{config.status} is run twice when @file{configure.ac} has changed.
18780 If that bothers you, you can make each run only regenerate the files for
18781 that rule:
18782 @example
18783 @group
18784 config.h: stamp-h
18785 stamp-h: config.h.in config.status
18786         ./config.status config.h
18787         echo > stamp-h
18789 Makefile: Makefile.in config.status
18790         ./config.status Makefile
18791 @end group
18792 @end example
18794 The calling convention of @file{config.status} has changed; see
18795 @ref{Obsolete config.status Use}, for details.
18798 @c =================================================== Obsolete Constructs
18800 @node Obsolete Constructs
18801 @chapter Obsolete Constructs
18802 @cindex Obsolete constructs
18804 Autoconf changes, and throughout the years some constructs have been
18805 obsoleted.  Most of the changes involve the macros, but in some cases
18806 the tools themselves, or even some concepts, are now considered
18807 obsolete.
18809 You may completely skip this chapter if you are new to Autoconf.  Its
18810 intention is mainly to help maintainers updating their packages by
18811 understanding how to move to more modern constructs.
18813 @menu
18814 * Obsolete config.status Use::  Obsolete convention for @command{config.status}
18815 * acconfig Header::             Additional entries in @file{config.h.in}
18816 * autoupdate Invocation::       Automatic update of @file{configure.ac}
18817 * Obsolete Macros::             Backward compatibility macros
18818 * Autoconf 1::                  Tips for upgrading your files
18819 * Autoconf 2.13::               Some fresher tips
18820 @end menu
18822 @node Obsolete config.status Use
18823 @section Obsolete @file{config.status} Invocation
18825 @file{config.status} now supports arguments to specify the files to
18826 instantiate; see @ref{config.status Invocation}, for more details.
18827 Before, environment variables had to be used.
18829 @defvar CONFIG_COMMANDS
18830 @evindex CONFIG_COMMANDS
18831 The tags of the commands to execute.  The default is the arguments given
18832 to @code{AC_OUTPUT} and @code{AC_CONFIG_COMMANDS} in
18833 @file{configure.ac}.
18834 @end defvar
18836 @defvar CONFIG_FILES
18837 @evindex CONFIG_FILES
18838 The files in which to perform @samp{@@@var{variable}@@} substitutions.
18839 The default is the arguments given to @code{AC_OUTPUT} and
18840 @code{AC_CONFIG_FILES} in @file{configure.ac}.
18841 @end defvar
18843 @defvar CONFIG_HEADERS
18844 @evindex CONFIG_HEADERS
18845 The files in which to substitute C @code{#define} statements.  The
18846 default is the arguments given to @code{AC_CONFIG_HEADERS}; if that
18847 macro was not called, @file{config.status} ignores this variable.
18848 @end defvar
18850 @defvar CONFIG_LINKS
18851 @evindex CONFIG_LINKS
18852 The symbolic links to establish.  The default is the arguments given to
18853 @code{AC_CONFIG_LINKS}; if that macro was not called,
18854 @file{config.status} ignores this variable.
18855 @end defvar
18857 In @ref{config.status Invocation}, using this old interface, the example
18858 would be:
18860 @example
18861 @group
18862 config.h: stamp-h
18863 stamp-h: config.h.in config.status
18864         CONFIG_COMMANDS= CONFIG_LINKS= CONFIG_FILES= \
18865           CONFIG_HEADERS=config.h ./config.status
18866         echo > stamp-h
18868 Makefile: Makefile.in config.status
18869         CONFIG_COMMANDS= CONFIG_LINKS= CONFIG_HEADERS= \
18870           CONFIG_FILES=Makefile ./config.status
18871 @end group
18872 @end example
18874 @noindent
18875 (If @file{configure.ac} does not call @code{AC_CONFIG_HEADERS}, there is
18876 no need to set @code{CONFIG_HEADERS} in the @command{make} rules.  Equally
18877 for @code{CONFIG_COMMANDS}, etc.)
18880 @node acconfig Header
18881 @section @file{acconfig.h}
18883 @cindex @file{acconfig.h}
18884 @cindex @file{config.h.top}
18885 @cindex @file{config.h.bot}
18887 In order to produce @file{config.h.in}, @command{autoheader} needs to
18888 build or to find templates for each symbol.  Modern releases of Autoconf
18889 use @code{AH_VERBATIM} and @code{AH_TEMPLATE} (@pxref{Autoheader
18890 Macros}), but in older releases a file, @file{acconfig.h}, contained the
18891 list of needed templates.  @command{autoheader} copied comments and
18892 @code{#define} and @code{#undef} statements from @file{acconfig.h} in
18893 the current directory, if present.  This file used to be mandatory if
18894 you @code{AC_DEFINE} any additional symbols.
18896 Modern releases of Autoconf also provide @code{AH_TOP} and
18897 @code{AH_BOTTOM} if you need to prepend/append some information to
18898 @file{config.h.in}.  Ancient versions of Autoconf had a similar feature:
18899 if @file{./acconfig.h} contains the string @samp{@@TOP@@},
18900 @command{autoheader} copies the lines before the line containing
18901 @samp{@@TOP@@} into the top of the file that it generates.  Similarly,
18902 if @file{./acconfig.h} contains the string @samp{@@BOTTOM@@},
18903 @command{autoheader} copies the lines after that line to the end of the
18904 file it generates.  Either or both of those strings may be omitted.  An
18905 even older alternate way to produce the same effect in ancient versions
18906 of Autoconf is to create the files @file{@var{file}.top} (typically
18907 @file{config.h.top}) and/or @file{@var{file}.bot} in the current
18908 directory.  If they exist, @command{autoheader} copies them to the
18909 beginning and end, respectively, of its output.
18911 In former versions of Autoconf, the files used in preparing a software
18912 package for distribution were:
18913 @example
18914 @group
18915 configure.ac --.   .------> autoconf* -----> configure
18916                +---+
18917 [aclocal.m4] --+   `---.
18918 [acsite.m4] ---'       |
18919                        +--> [autoheader*] -> [config.h.in]
18920 [acconfig.h] ----.     |
18921                  +-----'
18922 [config.h.top] --+
18923 [config.h.bot] --'
18924 @end group
18925 @end example
18927 Using only the @code{AH_} macros, @file{configure.ac} should be
18928 self-contained, and should not depend upon @file{acconfig.h} etc.
18931 @node autoupdate Invocation
18932 @section Using @command{autoupdate} to Modernize @file{configure.ac}
18933 @cindex @command{autoupdate}
18935 The @command{autoupdate} program updates a @file{configure.ac} file that
18936 calls Autoconf macros by their old names to use the current macro names.
18937 In version 2 of Autoconf, most of the macros were renamed to use a more
18938 uniform and descriptive naming scheme.  @xref{Macro Names}, for a
18939 description of the new scheme.  Although the old names still work
18940 (@pxref{Obsolete Macros}, for a list of the old macros and the corresponding
18941 new names), you can make your @file{configure.ac} files more readable
18942 and make it easier to use the current Autoconf documentation if you
18943 update them to use the new macro names.
18945 @evindex SIMPLE_BACKUP_SUFFIX
18946 If given no arguments, @command{autoupdate} updates @file{configure.ac},
18947 backing up the original version with the suffix @file{~} (or the value
18948 of the environment variable @code{SIMPLE_BACKUP_SUFFIX}, if that is
18949 set).  If you give @command{autoupdate} an argument, it reads that file
18950 instead of @file{configure.ac} and writes the updated file to the
18951 standard output.
18953 @noindent
18954 @command{autoupdate} accepts the following options:
18956 @table @option
18957 @item --help
18958 @itemx -h
18959 Print a summary of the command line options and exit.
18961 @item --version
18962 @itemx -V
18963 Print the version number of Autoconf and exit.
18965 @item --verbose
18966 @itemx -v
18967 Report processing steps.
18969 @item --debug
18970 @itemx -d
18971 Don't remove the temporary files.
18973 @item --force
18974 @itemx -f
18975 Force the update even if the file has not changed.  Disregard the cache.
18977 @item --include=@var{dir}
18978 @itemx -I @var{dir}
18979 Also look for input files in @var{dir}.  Multiple invocations accumulate.
18980 Directories are browsed from last to first.
18982 @item --prepend-include=@var{dir}
18983 @itemx -B @var{dir}
18984 Prepend directory @var{dir} to the search path.  This is used to include
18985 the language-specific files before any third-party macros.
18986 @end table
18988 @node Obsolete Macros
18989 @section Obsolete Macros
18991 Several macros are obsoleted in Autoconf, for various reasons (typically
18992 they failed to quote properly, couldn't be extended for more recent
18993 issues, etc.).  They are still supported, but deprecated: their use
18994 should be avoided.
18996 During the jump from Autoconf version 1 to version 2, most of the
18997 macros were renamed to use a more uniform and descriptive naming scheme,
18998 but their signature did not change.  @xref{Macro Names}, for a
18999 description of the new naming scheme.  Below, if there is just the mapping
19000 from old names to new names for these macros, the reader is invited to
19001 refer to the definition of the new macro for the signature and the
19002 description.
19004 @defmac AC_AIX
19005 @acindex{AIX}
19006 @cvindex _ALL_SOURCE
19007 This macro is a platform-specific subset of
19008 @code{AC_USE_SYSTEM_EXTENSIONS} (@pxref{AC_USE_SYSTEM_EXTENSIONS}).
19009 @end defmac
19011 @defmac AC_ALLOCA
19012 @acindex{ALLOCA}
19013 Replaced by @code{AC_FUNC_ALLOCA} (@pxref{AC_FUNC_ALLOCA}).
19014 @end defmac
19016 @defmac AC_ARG_ARRAY
19017 @acindex{ARG_ARRAY}
19018 Removed because of limited usefulness.
19019 @end defmac
19021 @defmac AC_C_CROSS
19022 @acindex{C_CROSS}
19023 This macro is obsolete; it does nothing.
19024 @end defmac
19026 @defmac AC_C_LONG_DOUBLE
19027 @acindex{C_LONG_DOUBLE}
19028 @cvindex HAVE_LONG_DOUBLE
19029 If the C compiler supports a working @code{long double} type with more
19030 range or precision than the @code{double} type, define
19031 @code{HAVE_LONG_DOUBLE}.
19033 You should use @code{AC_TYPE_LONG_DOUBLE} or
19034 @code{AC_TYPE_LONG_DOUBLE_WIDER} instead.  @xref{Particular Types}.
19035 @end defmac
19037 @defmac AC_CANONICAL_SYSTEM
19038 @acindex{CANONICAL_SYSTEM}
19039 Determine the system type and set output variables to the names of the
19040 canonical system types.  @xref{Canonicalizing}, for details about the
19041 variables this macro sets.
19043 The user is encouraged to use either @code{AC_CANONICAL_BUILD}, or
19044 @code{AC_CANONICAL_HOST}, or @code{AC_CANONICAL_TARGET}, depending on
19045 the needs.  Using @code{AC_CANONICAL_TARGET} is enough to run the two
19046 other macros (@pxref{Canonicalizing}).
19047 @end defmac
19049 @defmac AC_CHAR_UNSIGNED
19050 @acindex{CHAR_UNSIGNED}
19051 Replaced by @code{AC_C_CHAR_UNSIGNED} (@pxref{AC_C_CHAR_UNSIGNED}).
19052 @end defmac
19054 @defmac AC_CHECK_TYPE (@var{type}, @var{default})
19055 @acindex{CHECK_TYPE}
19056 Autoconf, up to 2.13, used to provide this version of
19057 @code{AC_CHECK_TYPE}, deprecated because of its flaws.  First, although
19058 it is a member of the @code{CHECK} clan, it does
19059 more than just checking.  Secondly, missing types are defined
19060 using @code{#define}, not @code{typedef}, and this can lead to
19061 problems in the case of pointer types.
19063 This use of @code{AC_CHECK_TYPE} is obsolete and discouraged; see
19064 @ref{Generic Types}, for the description of the current macro.
19066 If the type @var{type} is not defined, define it to be the C (or C++)
19067 builtin type @var{default}, e.g., @samp{short int} or @samp{unsigned int}.
19069 This macro is equivalent to:
19071 @example
19072 AC_CHECK_TYPE([@var{type}], [],
19073   [AC_DEFINE_UNQUOTED([@var{type}], [@var{default}],
19074      [Define to `@var{default}'
19075       if <sys/types.h> does not define.])])
19076 @end example
19078 In order to keep backward compatibility, the two versions of
19079 @code{AC_CHECK_TYPE} are implemented, selected using these heuristics:
19081 @enumerate
19082 @item
19083 If there are three or four arguments, the modern version is used.
19085 @item
19086 If the second argument appears to be a C or C++ type, then the
19087 obsolete version is used.  This happens if the argument is a C or C++
19088 @emph{builtin} type or a C identifier ending in @samp{_t}, optionally
19089 followed by one of @samp{[(* } and then by a string of zero or more
19090 characters taken from the set @samp{[]()* _a-zA-Z0-9}.
19092 @item
19093 If the second argument is spelled with the alphabet of valid C and C++
19094 types, the user is warned and the modern version is used.
19096 @item
19097 Otherwise, the modern version is used.
19098 @end enumerate
19100 @noindent
19101 You are encouraged either to use a valid builtin type, or to use the
19102 equivalent modern code (see above), or better yet, to use
19103 @code{AC_CHECK_TYPES} together with
19105 @example
19106 #ifndef HAVE_LOFF_T
19107 typedef loff_t off_t;
19108 #endif
19109 @end example
19110 @end defmac
19111 @c end of AC_CHECK_TYPE
19113 @defmac AC_CHECKING (@var{feature-description})
19114 @acindex{CHECKING}
19115 Same as
19117 @example
19118 AC_MSG_NOTICE([checking @var{feature-description}@dots{}]
19119 @end example
19121 @noindent
19122 @xref{AC_MSG_NOTICE}.
19123 @end defmac
19125 @defmac AC_COMPILE_CHECK (@var{echo-text}, @var{includes}, @
19126   @var{function-body}, @var{action-if-true}, @ovar{action-if-false})
19127 @acindex{COMPILE_CHECK}
19128 This is an obsolete version of @code{AC_TRY_COMPILE} itself replaced by
19129 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}), with the
19130 addition that it prints @samp{checking for @var{echo-text}} to the
19131 standard output first, if @var{echo-text} is non-empty.  Use
19132 @code{AC_MSG_CHECKING} and @code{AC_MSG_RESULT} instead to print
19133 messages (@pxref{Printing Messages}).
19134 @end defmac
19136 @defmac AC_CONST
19137 @acindex{CONST}
19138 Replaced by @code{AC_C_CONST} (@pxref{AC_C_CONST}).
19139 @end defmac
19141 @defmac AC_CROSS_CHECK
19142 @acindex{CROSS_CHECK}
19143 Same as @code{AC_C_CROSS}, which is obsolete too, and does nothing
19144 @code{:-)}.
19145 @end defmac
19147 @defmac AC_CYGWIN
19148 @acindex{CYGWIN}
19149 @evindex CYGWIN
19150 Check for the Cygwin environment in which case the shell variable
19151 @code{CYGWIN} is set to @samp{yes}.  Don't use this macro, the dignified
19152 means to check the nature of the host is using @code{AC_CANONICAL_HOST}
19153 (@pxref{Canonicalizing}).  As a matter of fact this macro is defined as:
19155 @example
19156 AC_REQUIRE([AC_CANONICAL_HOST])[]dnl
19157 case $host_os in
19158   *cygwin* ) CYGWIN=yes;;
19159          * ) CYGWIN=no;;
19160 esac
19161 @end example
19163 Beware that the variable @env{CYGWIN} has a special meaning when
19164 running Cygwin, and should not be changed.  That's yet another reason
19165 not to use this macro.
19166 @end defmac
19168 @defmac AC_DECL_SYS_SIGLIST
19169 @acindex{DECL_SYS_SIGLIST}
19170 @cvindex SYS_SIGLIST_DECLARED
19171 Same as:
19173 @example
19174 AC_CHECK_DECLS([sys_siglist], [], [],
19175 [#include <signal.h>
19176 /* NetBSD declares sys_siglist in unistd.h.  */
19177 #ifdef HAVE_UNISTD_H
19178 # include <unistd.h>
19179 #endif
19181 @end example
19183 @noindent
19184 @xref{AC_CHECK_DECLS}.
19185 @end defmac
19187 @defmac AC_DECL_YYTEXT
19188 @acindex{DECL_YYTEXT}
19189 Does nothing, now integrated in @code{AC_PROG_LEX} (@pxref{AC_PROG_LEX}).
19190 @end defmac
19192 @defmac AC_DIR_HEADER
19193 @acindex{DIR_HEADER}
19194 @cvindex DIRENT
19195 @cvindex SYSNDIR
19196 @cvindex SYSDIR
19197 @cvindex NDIR
19198 Like calling @code{AC_FUNC_CLOSEDIR_VOID}
19199 (@pxref{AC_FUNC_CLOSEDIR_VOID}) and @code{AC_HEADER_DIRENT}
19200 (@pxref{AC_HEADER_DIRENT}),
19201 but defines a different set of C preprocessor macros to indicate which
19202 header file is found:
19204 @multitable {@file{sys/ndir.h}} {Old Symbol} {@code{HAVE_SYS_NDIR_H}}
19205 @item Header            @tab Old Symbol     @tab New Symbol
19206 @item @file{dirent.h}   @tab @code{DIRENT}  @tab @code{HAVE_DIRENT_H}
19207 @item @file{sys/ndir.h} @tab @code{SYSNDIR} @tab @code{HAVE_SYS_NDIR_H}
19208 @item @file{sys/dir.h}  @tab @code{SYSDIR}  @tab @code{HAVE_SYS_DIR_H}
19209 @item @file{ndir.h}     @tab @code{NDIR}    @tab @code{HAVE_NDIR_H}
19210 @end multitable
19211 @end defmac
19213 @defmac AC_DYNIX_SEQ
19214 @acindex{DYNIX_SEQ}
19215 If on DYNIX/ptx, add @option{-lseq} to output variable
19216 @code{LIBS}.  This macro used to be defined as
19218 @example
19219 AC_CHECK_LIB([seq], [getmntent], [LIBS="-lseq $LIBS"])
19220 @end example
19222 @noindent
19223 now it is just @code{AC_FUNC_GETMNTENT} (@pxref{AC_FUNC_GETMNTENT}).
19224 @end defmac
19226 @defmac AC_EXEEXT
19227 @acindex{EXEEXT}
19228 @ovindex EXEEXT
19229 Defined the output variable @code{EXEEXT} based on the output of the
19230 compiler, which is now done automatically.  Typically set to empty
19231 string if Posix and @samp{.exe} if a @acronym{DOS} variant.
19232 @end defmac
19234 @defmac AC_EMXOS2
19235 @acindex{EMXOS2}
19236 Similar to @code{AC_CYGWIN} but checks for the EMX environment on OS/2
19237 and sets @code{EMXOS2}.  Don't use this macro, the dignified means to
19238 check the nature of the host is using @code{AC_CANONICAL_HOST}
19239 (@pxref{Canonicalizing}).
19240 @end defmac
19242 @defmac AC_ENABLE (@var{feature}, @var{action-if-given}, @
19243   @ovar{action-if-not-given})
19244 @acindex{ENABLE}
19245 This is an obsolete version of @code{AC_ARG_ENABLE} that does not
19246 support providing a help string (@pxref{AC_ARG_ENABLE}).
19247 @end defmac
19249 @defmac AC_ERROR
19250 @acindex{ERROR}
19251 Replaced by @code{AC_MSG_ERROR} (@pxref{AC_MSG_ERROR}).
19252 @end defmac
19254 @defmac AC_FIND_X
19255 @acindex{FIND_X}
19256 Replaced by @code{AC_PATH_X} (@pxref{AC_PATH_X}).
19257 @end defmac
19259 @defmac AC_FIND_XTRA
19260 @acindex{FIND_XTRA}
19261 Replaced by @code{AC_PATH_XTRA} (@pxref{AC_PATH_XTRA}).
19262 @end defmac
19264 @defmac AC_FOREACH
19265 @acindex{FOREACH}
19266 Replaced by @code{m4_foreach_w} (@pxref{m4_foreach_w}).
19267 @end defmac
19269 @defmac AC_FUNC_CHECK
19270 @acindex{FUNC_CHECK}
19271 Replaced by @code{AC_CHECK_FUNC} (@pxref{AC_CHECK_FUNC}).
19272 @end defmac
19274 @anchor{AC_FUNC_SETVBUF_REVERSED}
19275 @defmac AC_FUNC_SETVBUF_REVERSED
19276 @acindex{FUNC_SETVBUF_REVERSED}
19277 @cvindex SETVBUF_REVERSED
19278 @c @fuindex setvbuf
19279 @prindex @code{setvbuf}
19280 Do nothing.  Formerly, this macro checked whether @code{setvbuf} takes
19281 the buffering type as its second argument and the buffer pointer as the
19282 third, instead of the other way around, and defined
19283 @code{SETVBUF_REVERSED}.  However, the last systems to have the problem
19284 were those based on SVR2, which became obsolete in 1987, and the macro
19285 is no longer needed.
19286 @end defmac
19288 @defmac AC_FUNC_WAIT3
19289 @acindex{FUNC_WAIT3}
19290 @cvindex HAVE_WAIT3
19291 @c @fuindex wait3
19292 @prindex @code{wait3}
19293 If @code{wait3} is found and fills in the contents of its third argument
19294 (a @samp{struct rusage *}), which @acronym{HP-UX} does not do, define
19295 @code{HAVE_WAIT3}.
19297 These days portable programs should use @code{waitpid}, not
19298 @code{wait3}, as @code{wait3} has been removed from Posix.
19299 @end defmac
19301 @defmac AC_GCC_TRADITIONAL
19302 @acindex{GCC_TRADITIONAL}
19303 Replaced by @code{AC_PROG_GCC_TRADITIONAL} (@pxref{AC_PROG_GCC_TRADITIONAL}).
19304 @end defmac
19306 @defmac AC_GETGROUPS_T
19307 @acindex{GETGROUPS_T}
19308 Replaced by @code{AC_TYPE_GETGROUPS} (@pxref{AC_TYPE_GETGROUPS}).
19309 @end defmac
19311 @defmac AC_GETLOADAVG
19312 @acindex{GETLOADAVG}
19313 Replaced by @code{AC_FUNC_GETLOADAVG} (@pxref{AC_FUNC_GETLOADAVG}).
19314 @end defmac
19316 @defmac AC_GNU_SOURCE
19317 @acindex{GNU_SOURCE}
19318 @cvindex _GNU_SOURCE
19319 This macro is a platform-specific subset of
19320 @code{AC_USE_SYSTEM_EXTENSIONS} (@pxref{AC_USE_SYSTEM_EXTENSIONS}).
19321 @end defmac
19323 @defmac AC_HAVE_FUNCS
19324 @acindex{HAVE_FUNCS}
19325 Replaced by @code{AC_CHECK_FUNCS} (@pxref{AC_CHECK_FUNCS}).
19326 @end defmac
19328 @defmac AC_HAVE_HEADERS
19329 @acindex{HAVE_HEADERS}
19330 Replaced by @code{AC_CHECK_HEADERS} (@pxref{AC_CHECK_HEADERS}).
19331 @end defmac
19333 @defmac AC_HAVE_LIBRARY (@var{library}, @ovar{action-if-found}, @
19334   @ovar{action-if-not-found}, @ovar{other-libraries})
19335 @acindex{HAVE_LIBRARY}
19336 This macro is equivalent to calling @code{AC_CHECK_LIB} with a
19337 @var{function} argument of @code{main}.  In addition, @var{library} can
19338 be written as any of @samp{foo}, @option{-lfoo}, or @samp{libfoo.a}.  In
19339 all of those cases, the compiler is passed @option{-lfoo}.  However,
19340 @var{library} cannot be a shell variable; it must be a literal name.
19341 @xref{AC_CHECK_LIB}.
19342 @end defmac
19344 @defmac AC_HAVE_POUNDBANG
19345 @acindex{HAVE_POUNDBANG}
19346 Replaced by @code{AC_SYS_INTERPRETER} (@pxref{AC_SYS_INTERPRETER}).
19347 @end defmac
19349 @defmac AC_HEADER_CHECK
19350 @acindex{HEADER_CHECK}
19351 Replaced by @code{AC_CHECK_HEADER} (@pxref{AC_CHECK_HEADER}).
19352 @end defmac
19354 @defmac AC_HEADER_EGREP
19355 @acindex{HEADER_EGREP}
19356 Replaced by @code{AC_EGREP_HEADER} (@pxref{AC_EGREP_HEADER}).
19357 @end defmac
19359 @defmac AC_HELP_STRING
19360 @acindex{HELP_STRING}
19361 Replaced by @code{AS_HELP_STRING} (@pxref{AS_HELP_STRING}).
19362 @end defmac
19364 @defmac AC_INIT (@var{unique-file-in-source-dir})
19365 @acindex{INIT}
19366 Formerly @code{AC_INIT} used to have a single argument, and was
19367 equivalent to:
19369 @example
19370 AC_INIT
19371 AC_CONFIG_SRCDIR(@var{unique-file-in-source-dir})
19372 @end example
19373 See @ref{AC_INIT} and @ref{AC_CONFIG_SRCDIR}.
19374 @end defmac
19376 @defmac AC_INLINE
19377 @acindex{INLINE}
19378 Replaced by @code{AC_C_INLINE} (@pxref{AC_C_INLINE}).
19379 @end defmac
19381 @defmac AC_INT_16_BITS
19382 @acindex{INT_16_BITS}
19383 @cvindex INT_16_BITS
19384 If the C type @code{int} is 16 bits wide, define @code{INT_16_BITS}.
19385 Use @samp{AC_CHECK_SIZEOF(int)} instead (@pxref{AC_CHECK_SIZEOF}).
19386 @end defmac
19388 @defmac AC_IRIX_SUN
19389 @acindex{IRIX_SUN}
19390 If on @sc{irix} (Silicon Graphics Unix), add @option{-lsun} to output
19391 @code{LIBS}.  If you were using it to get @code{getmntent}, use
19392 @code{AC_FUNC_GETMNTENT} instead.  If you used it for the NIS versions
19393 of the password and group functions, use @samp{AC_CHECK_LIB(sun,
19394 getpwnam)}.  Up to Autoconf 2.13, it used to be
19396 @example
19397 AC_CHECK_LIB([sun], [getmntent], [LIBS="-lsun $LIBS"])
19398 @end example
19400 @noindent
19401 now it is defined as
19403 @example
19404 AC_FUNC_GETMNTENT
19405 AC_CHECK_LIB([sun], [getpwnam])
19406 @end example
19408 @noindent
19409 See @ref{AC_FUNC_GETMNTENT} and @ref{AC_CHECK_LIB}.
19410 @end defmac
19412 @defmac AC_ISC_POSIX
19413 @acindex{ISC_POSIX}
19414 @ovindex LIBS
19415 This macro adds @option{-lcposix} to output variable @code{LIBS} if
19416 necessary for Posix facilities.  Sun dropped support for the obsolete
19417 @sc{interactive} Systems Corporation Unix on 2006-07-23.  New programs
19418 need not use this macro.  It is implemented as
19419 @code{AC_SEARCH_LIBS([strerror], [cposix])} (@pxref{AC_SEARCH_LIBS}).
19420 @end defmac
19422 @defmac AC_LANG_C
19423 @acindex{LANG_C}
19424 Same as @samp{AC_LANG([C])} (@pxref{AC_LANG}).
19425 @end defmac
19427 @defmac AC_LANG_CPLUSPLUS
19428 @acindex{LANG_CPLUSPLUS}
19429 Same as @samp{AC_LANG([C++])} (@pxref{AC_LANG}).
19430 @end defmac
19432 @defmac AC_LANG_FORTRAN77
19433 @acindex{LANG_FORTRAN77}
19434 Same as @samp{AC_LANG([Fortran 77])} (@pxref{AC_LANG}).
19435 @end defmac
19437 @defmac AC_LANG_RESTORE
19438 @acindex{LANG_RESTORE}
19439 Select the @var{language} that is saved on the top of the stack, as set
19440 by @code{AC_LANG_SAVE}, remove it from the stack, and call
19441 @code{AC_LANG(@var{language})}.  @xref{Language Choice}, for the
19442 preferred way to change languages.
19443 @end defmac
19445 @defmac AC_LANG_SAVE
19446 @acindex{LANG_SAVE}
19447 Remember the current language (as set by @code{AC_LANG}) on a stack.
19448 The current language does not change.  @code{AC_LANG_PUSH} is preferred
19449 (@pxref{AC_LANG_PUSH}).
19450 @end defmac
19452 @defmac AC_LINK_FILES (@var{source}@dots{}, @var{dest}@dots{})
19453 @acindex{LINK_FILES}
19454 This is an obsolete version of @code{AC_CONFIG_LINKS}
19455 (@pxref{AC_CONFIG_LINKS}.  An updated version of:
19457 @example
19458 AC_LINK_FILES(config/$machine.h config/$obj_format.h,
19459               host.h            object.h)
19460 @end example
19462 @noindent
19465 @example
19466 AC_CONFIG_LINKS([host.h:config/$machine.h
19467                 object.h:config/$obj_format.h])
19468 @end example
19469 @end defmac
19471 @defmac AC_LN_S
19472 @acindex{LN_S}
19473 Replaced by @code{AC_PROG_LN_S} (@pxref{AC_PROG_LN_S}).
19474 @end defmac
19476 @defmac AC_LONG_64_BITS
19477 @acindex{LONG_64_BITS}
19478 @cvindex LONG_64_BITS
19479 Define @code{LONG_64_BITS} if the C type @code{long int} is 64 bits wide.
19480 Use the generic macro @samp{AC_CHECK_SIZEOF([long int])} instead
19481 (@pxref{AC_CHECK_SIZEOF}).
19482 @end defmac
19484 @defmac AC_LONG_DOUBLE
19485 @acindex{LONG_DOUBLE}
19486 If the C compiler supports a working @code{long double} type with more
19487 range or precision than the @code{double} type, define
19488 @code{HAVE_LONG_DOUBLE}.
19490 You should use @code{AC_TYPE_LONG_DOUBLE} or
19491 @code{AC_TYPE_LONG_DOUBLE_WIDER} instead.  @xref{Particular Types}.
19492 @end defmac
19494 @defmac AC_LONG_FILE_NAMES
19495 @acindex{LONG_FILE_NAMES}
19496 Replaced by
19497 @example
19498 AC_SYS_LONG_FILE_NAMES
19499 @end example
19500 @noindent
19501 @xref{AC_SYS_LONG_FILE_NAMES}.
19502 @end defmac
19504 @defmac AC_MAJOR_HEADER
19505 @acindex{MAJOR_HEADER}
19506 Replaced by @code{AC_HEADER_MAJOR} (@pxref{AC_HEADER_MAJOR}).
19507 @end defmac
19509 @defmac AC_MEMORY_H
19510 @acindex{MEMORY_H}
19511 @cvindex NEED_MEMORY_H
19512 Used to define @code{NEED_MEMORY_H} if the @code{mem} functions were
19513 defined in @file{memory.h}.  Today it is equivalent to
19514 @samp{AC_CHECK_HEADERS([memory.h])} (@pxref{AC_CHECK_HEADERS}).  Adjust
19515 your code to depend upon
19516 @code{HAVE_MEMORY_H}, not @code{NEED_MEMORY_H}; see @ref{Standard
19517 Symbols}.
19518 @end defmac
19520 @defmac AC_MINGW32
19521 @acindex{MINGW32}
19522 Similar to @code{AC_CYGWIN} but checks for the MinGW compiler
19523 environment and sets @code{MINGW32}.  Don't use this macro, the
19524 dignified means to check the nature of the host is using
19525 @code{AC_CANONICAL_HOST} (@pxref{Canonicalizing}).
19526 @end defmac
19528 @defmac AC_MINIX
19529 @acindex{MINIX}
19530 @cvindex _MINIX
19531 @cvindex _POSIX_SOURCE
19532 @cvindex _POSIX_1_SOURCE
19533 This macro is a platform-specific subset of
19534 @code{AC_USE_SYSTEM_EXTENSIONS} (@pxref{AC_USE_SYSTEM_EXTENSIONS}).
19535 @end defmac
19537 @defmac AC_MINUS_C_MINUS_O
19538 @acindex{MINUS_C_MINUS_O}
19539 Replaced by @code{AC_PROG_CC_C_O} (@pxref{AC_PROG_CC_C_O}).
19540 @end defmac
19542 @defmac AC_MMAP
19543 @acindex{MMAP}
19544 Replaced by @code{AC_FUNC_MMAP} (@pxref{AC_FUNC_MMAP}).
19545 @end defmac
19547 @defmac AC_MODE_T
19548 @acindex{MODE_T}
19549 Replaced by @code{AC_TYPE_MODE_T} (@pxref{AC_TYPE_MODE_T}).
19550 @end defmac
19552 @defmac AC_OBJEXT
19553 @acindex{OBJEXT}
19554 @ovindex OBJEXT
19555 Defined the output variable @code{OBJEXT} based on the output of the
19556 compiler, after .c files have been excluded.  Typically set to @samp{o}
19557 if Posix, @samp{obj} if a @acronym{DOS} variant.
19558 Now the compiler checking macros handle
19559 this automatically.
19560 @end defmac
19562 @defmac AC_OBSOLETE (@var{this-macro-name}, @ovar{suggestion})
19563 @acindex{OBSOLETE}
19564 Make M4 print a message to the standard error output warning that
19565 @var{this-macro-name} is obsolete, and giving the file and line number
19566 where it was called.  @var{this-macro-name} should be the name of the
19567 macro that is calling @code{AC_OBSOLETE}.  If @var{suggestion} is given,
19568 it is printed at the end of the warning message; for example, it can be
19569 a suggestion for what to use instead of @var{this-macro-name}.
19571 For instance
19573 @example
19574 AC_OBSOLETE([$0], [; use AC_CHECK_HEADERS(unistd.h) instead])dnl
19575 @end example
19577 @noindent
19578 You are encouraged to use @code{AU_DEFUN} instead, since it gives better
19579 services to the user (@pxref{AU_DEFUN}).
19580 @end defmac
19582 @defmac AC_OFF_T
19583 @acindex{OFF_T}
19584 Replaced by @code{AC_TYPE_OFF_T} (@pxref{AC_TYPE_OFF_T}).
19585 @end defmac
19587 @defmac AC_OUTPUT (@ovar{file}@dots{}, @ovar{extra-cmds}, @ovar{init-cmds})
19588 @acindex{OUTPUT}
19589 The use of @code{AC_OUTPUT} with arguments is deprecated.  This obsoleted
19590 interface is equivalent to:
19592 @example
19593 @group
19594 AC_CONFIG_FILES(@var{file}@dots{})
19595 AC_CONFIG_COMMANDS([default],
19596                    @var{extra-cmds}, @var{init-cmds})
19597 AC_OUTPUT
19598 @end group
19599 @end example
19601 @noindent
19602 See @ref{AC_CONFIG_FILES}, @ref{AC_CONFIG_COMMANDS}, and @ref{AC_OUTPUT}.
19603 @end defmac
19605 @defmac AC_OUTPUT_COMMANDS (@var{extra-cmds}, @ovar{init-cmds})
19606 @acindex{OUTPUT_COMMANDS}
19607 Specify additional shell commands to run at the end of
19608 @file{config.status}, and shell commands to initialize any variables
19609 from @command{configure}.  This macro may be called multiple times.  It is
19610 obsolete, replaced by @code{AC_CONFIG_COMMANDS} (@pxref{AC_CONFIG_COMMANDS}).
19612 Here is an unrealistic example:
19614 @example
19615 fubar=27
19616 AC_OUTPUT_COMMANDS([echo this is extra $fubar, and so on.],
19617                    [fubar=$fubar])
19618 AC_OUTPUT_COMMANDS([echo this is another, extra, bit],
19619                    [echo init bit])
19620 @end example
19622 Aside from the fact that @code{AC_CONFIG_COMMANDS} requires an
19623 additional key, an important difference is that
19624 @code{AC_OUTPUT_COMMANDS} is quoting its arguments twice, unlike
19625 @code{AC_CONFIG_COMMANDS}.  This means that @code{AC_CONFIG_COMMANDS}
19626 can safely be given macro calls as arguments:
19628 @example
19629 AC_CONFIG_COMMANDS(foo, [my_FOO()])
19630 @end example
19632 @noindent
19633 Conversely, where one level of quoting was enough for literal strings
19634 with @code{AC_OUTPUT_COMMANDS}, you need two with
19635 @code{AC_CONFIG_COMMANDS}.  The following lines are equivalent:
19637 @example
19638 @group
19639 AC_OUTPUT_COMMANDS([echo "Square brackets: []"])
19640 AC_CONFIG_COMMANDS([default], [[echo "Square brackets: []"]])
19641 @end group
19642 @end example
19643 @end defmac
19645 @defmac AC_PID_T
19646 @acindex{PID_T}
19647 Replaced by @code{AC_TYPE_PID_T} (@pxref{AC_TYPE_PID_T}).
19648 @end defmac
19650 @defmac AC_PREFIX
19651 @acindex{PREFIX}
19652 Replaced by @code{AC_PREFIX_PROGRAM} (@pxref{AC_PREFIX_PROGRAM}).
19653 @end defmac
19655 @defmac AC_PROGRAMS_CHECK
19656 @acindex{PROGRAMS_CHECK}
19657 Replaced by @code{AC_CHECK_PROGS} (@pxref{AC_CHECK_PROGS}).
19658 @end defmac
19660 @defmac AC_PROGRAMS_PATH
19661 @acindex{PROGRAMS_PATH}
19662 Replaced by @code{AC_PATH_PROGS} (@pxref{AC_PATH_PROGS}).
19663 @end defmac
19665 @defmac AC_PROGRAM_CHECK
19666 @acindex{PROGRAM_CHECK}
19667 Replaced by @code{AC_CHECK_PROG} (@pxref{AC_CHECK_PROG}).
19668 @end defmac
19670 @defmac AC_PROGRAM_EGREP
19671 @acindex{PROGRAM_EGREP}
19672 Replaced by @code{AC_EGREP_CPP} (@pxref{AC_EGREP_CPP}).
19673 @end defmac
19675 @defmac AC_PROGRAM_PATH
19676 @acindex{PROGRAM_PATH}
19677 Replaced by @code{AC_PATH_PROG} (@pxref{AC_PATH_PROG}).
19678 @end defmac
19680 @defmac AC_REMOTE_TAPE
19681 @acindex{REMOTE_TAPE}
19682 Removed because of limited usefulness.
19683 @end defmac
19685 @defmac AC_RESTARTABLE_SYSCALLS
19686 @acindex{RESTARTABLE_SYSCALLS}
19687 This macro was renamed @code{AC_SYS_RESTARTABLE_SYSCALLS}.  However,
19688 these days portable programs should use @code{sigaction} with
19689 @code{SA_RESTART} if they want restartable system calls.  They should
19690 not rely on @code{HAVE_RESTARTABLE_SYSCALLS}, since nowadays whether a
19691 system call is restartable is a dynamic issue, not a configuration-time
19692 issue.
19693 @end defmac
19695 @defmac AC_RETSIGTYPE
19696 @acindex{RETSIGTYPE}
19697 Replaced by @code{AC_TYPE_SIGNAL} (@pxref{AC_TYPE_SIGNAL}), which itself
19698 is obsolete when assuming C89 or better.
19699 @end defmac
19701 @defmac AC_RSH
19702 @acindex{RSH}
19703 Removed because of limited usefulness.
19704 @end defmac
19706 @defmac AC_SCO_INTL
19707 @acindex{SCO_INTL}
19708 @ovindex LIBS
19709 If on SCO Unix, add @option{-lintl} to output variable @code{LIBS}.  This
19710 macro used to do this:
19712 @example
19713 AC_CHECK_LIB([intl], [strftime], [LIBS="-lintl $LIBS"])
19714 @end example
19716 @noindent
19717 Now it just calls @code{AC_FUNC_STRFTIME} instead (@pxref{AC_FUNC_STRFTIME}).
19718 @end defmac
19720 @defmac AC_SETVBUF_REVERSED
19721 @acindex{SETVBUF_REVERSED}
19722 Replaced by
19723 @example
19724 AC_FUNC_SETVBUF_REVERSED
19725 @end example
19726 @noindent
19727 @xref{AC_FUNC_SETVBUF_REVERSED}.
19728 @end defmac
19730 @defmac AC_SET_MAKE
19731 @acindex{SET_MAKE}
19732 Replaced by @code{AC_PROG_MAKE_SET} (@pxref{AC_PROG_MAKE_SET}).
19733 @end defmac
19735 @defmac AC_SIZEOF_TYPE
19736 @acindex{SIZEOF_TYPE}
19737 Replaced by @code{AC_CHECK_SIZEOF} (@pxref{AC_CHECK_SIZEOF}).
19738 @end defmac
19740 @defmac AC_SIZE_T
19741 @acindex{SIZE_T}
19742 Replaced by @code{AC_TYPE_SIZE_T} (@pxref{AC_TYPE_SIZE_T}).
19743 @end defmac
19745 @defmac AC_STAT_MACROS_BROKEN
19746 @acindex{STAT_MACROS_BROKEN}
19747 Replaced by @code{AC_HEADER_STAT} (@pxref{AC_HEADER_STAT}).
19748 @end defmac
19750 @defmac AC_STDC_HEADERS
19751 @acindex{STDC_HEADERS}
19752 Replaced by @code{AC_HEADER_STDC} (@pxref{AC_HEADER_STDC}).
19753 @end defmac
19755 @defmac AC_STRCOLL
19756 @acindex{STRCOLL}
19757 Replaced by @code{AC_FUNC_STRCOLL} (@pxref{AC_FUNC_STRCOLL}).
19758 @end defmac
19760 @defmac AC_STRUCT_ST_BLKSIZE
19761 @acindex{STRUCT_ST_BLKSIZE}
19762 @cvindex HAVE_STRUCT_STAT_ST_BLKSIZE
19763 @cvindex HAVE_ST_BLKSIZE
19764 If @code{struct stat} contains an @code{st_blksize} member, define
19765 @code{HAVE_STRUCT_STAT_ST_BLKSIZE}.  The former name,
19766 @code{HAVE_ST_BLKSIZE} is to be avoided, as its support will cease in
19767 the future.  This macro is obsoleted, and should be replaced by
19769 @example
19770 AC_CHECK_MEMBERS([struct stat.st_blksize])
19771 @end example
19772 @noindent
19773 @xref{AC_CHECK_MEMBERS}.
19774 @end defmac
19776 @defmac AC_STRUCT_ST_RDEV
19777 @acindex{STRUCT_ST_RDEV}
19778 @cvindex HAVE_ST_RDEV
19779 @cvindex HAVE_STRUCT_STAT_ST_RDEV
19780 If @code{struct stat} contains an @code{st_rdev} member, define
19781 @code{HAVE_STRUCT_STAT_ST_RDEV}.  The former name for this macro,
19782 @code{HAVE_ST_RDEV}, is to be avoided as it will cease to be supported
19783 in the future.  Actually, even the new macro is obsolete and should be
19784 replaced by:
19785 @example
19786 AC_CHECK_MEMBERS([struct stat.st_rdev])
19787 @end example
19788 @noindent
19789 @xref{AC_CHECK_MEMBERS}.
19790 @end defmac
19792 @defmac AC_ST_BLKSIZE
19793 @acindex{ST_BLKSIZE}
19794 Replaced by @code{AC_CHECK_MEMBERS} (@pxref{AC_CHECK_MEMBERS}).
19795 @end defmac
19797 @defmac AC_ST_BLOCKS
19798 @acindex{ST_BLOCKS}
19799 Replaced by @code{AC_STRUCT_ST_BLOCKS} (@pxref{AC_STRUCT_ST_BLOCKS}).
19800 @end defmac
19802 @defmac AC_ST_RDEV
19803 @acindex{ST_RDEV}
19804 Replaced by @code{AC_CHECK_MEMBERS} (@pxref{AC_CHECK_MEMBERS}).
19805 @end defmac
19807 @defmac AC_SYS_RESTARTABLE_SYSCALLS
19808 @acindex{SYS_RESTARTABLE_SYSCALLS}
19809 @cvindex HAVE_RESTARTABLE_SYSCALLS
19810 If the system automatically restarts a system call that is interrupted
19811 by a signal, define @code{HAVE_RESTARTABLE_SYSCALLS}.  This macro does
19812 not check whether system calls are restarted in general---it checks whether a
19813 signal handler installed with @code{signal} (but not @code{sigaction})
19814 causes system calls to be restarted.  It does not check whether system calls
19815 can be restarted when interrupted by signals that have no handler.
19817 These days portable programs should use @code{sigaction} with
19818 @code{SA_RESTART} if they want restartable system calls.  They should
19819 not rely on @code{HAVE_RESTARTABLE_SYSCALLS}, since nowadays whether a
19820 system call is restartable is a dynamic issue, not a configuration-time
19821 issue.
19822 @end defmac
19824 @defmac AC_SYS_SIGLIST_DECLARED
19825 @acindex{SYS_SIGLIST_DECLARED}
19826 This macro was renamed @code{AC_DECL_SYS_SIGLIST}.  However, even that
19827 name is obsolete, as the same functionality is now acheived via
19828 @code{AC_CHECK_DECLS} (@pxref{AC_CHECK_DECLS}).
19829 @end defmac
19831 @defmac AC_TEST_CPP
19832 @acindex{TEST_CPP}
19833 This macro was renamed @code{AC_TRY_CPP}, which in turn was replaced by
19834 @code{AC_PREPROC_IFELSE} (@pxref{AC_PREPROC_IFELSE}).
19835 @end defmac
19837 @defmac AC_TEST_PROGRAM
19838 @acindex{TEST_PROGRAM}
19839 This macro was renamed @code{AC_TRY_RUN}, which in turn was replaced by
19840 @code{AC_RUN_IFELSE} (@pxref{AC_RUN_IFELSE}).
19841 @end defmac
19843 @defmac AC_TIMEZONE
19844 @acindex{TIMEZONE}
19845 Replaced by @code{AC_STRUCT_TIMEZONE} (@pxref{AC_STRUCT_TIMEZONE}).
19846 @end defmac
19848 @defmac AC_TIME_WITH_SYS_TIME
19849 @acindex{TIME_WITH_SYS_TIME}
19850 Replaced by @code{AC_HEADER_TIME} (@pxref{AC_HEADER_TIME}).
19851 @end defmac
19853 @defmac AC_TRY_COMPILE (@var{includes}, @var{function-body}, @
19854   @ovar{action-if-true}, @ovar{action-if-false})
19855 @acindex{TRY_COMPILE}
19856 Same as:
19858 @example
19859 AC_COMPILE_IFELSE(
19860   [AC_LANG_PROGRAM([[@var{includes}]],
19861      [[@var{function-body}]])],
19862   [@var{action-if-true}],
19863   [@var{action-if-false}])
19864 @end example
19866 @noindent
19867 @xref{Running the Compiler}.
19869 This macro double quotes both @var{includes} and @var{function-body}.
19871 For C and C++, @var{includes} is any @code{#include} statements needed
19872 by the code in @var{function-body} (@var{includes} is ignored if
19873 the currently selected language is Fortran or Fortran 77).  The compiler
19874 and compilation flags are determined by the current language
19875 (@pxref{Language Choice}).
19876 @end defmac
19878 @defmac AC_TRY_CPP (@var{input}, @ovar{action-if-true}, @ovar{action-if-false})
19879 @acindex{TRY_CPP}
19880 Same as:
19882 @example
19883 AC_PREPROC_IFELSE(
19884   [AC_LANG_SOURCE([[@var{input}]])],
19885   [@var{action-if-true}],
19886   [@var{action-if-false}])
19887 @end example
19889 @noindent
19890 @xref{Running the Preprocessor}.
19892 This macro double quotes the @var{input}.
19893 @end defmac
19895 @defmac AC_TRY_LINK (@var{includes}, @var{function-body}, @
19896   @ovar{action-if-true}, @ovar{action-if-false})
19897 @acindex{TRY_LINK}
19898 Same as:
19900 @example
19901 AC_LINK_IFELSE(
19902   [AC_LANG_PROGRAM([[@var{includes}]],
19903      [[@var{function-body}]])],
19904   [@var{action-if-true}],
19905   [@var{action-if-false}])
19906 @end example
19908 @noindent
19909 @xref{Running the Compiler}.
19911 This macro double quotes both @var{includes} and @var{function-body}.
19913 Depending on the current language (@pxref{Language Choice}), create a
19914 test program to see whether a function whose body consists of
19915 @var{function-body} can be compiled and linked.  If the file compiles
19916 and links successfully, run shell commands @var{action-if-found},
19917 otherwise run @var{action-if-not-found}.
19919 This macro double quotes both @var{includes} and @var{function-body}.
19921 For C and C++, @var{includes} is any @code{#include} statements needed
19922 by the code in @var{function-body} (@var{includes} is ignored if
19923 the currently selected language is Fortran or Fortran 77).  The compiler
19924 and compilation flags are determined by the current language
19925 (@pxref{Language Choice}), and in addition @code{LDFLAGS} and
19926 @code{LIBS} are used for linking.
19927 @end defmac
19929 @defmac AC_TRY_LINK_FUNC (@var{function}, @ovar{action-if-found}, @
19930   @ovar{action-if-not-found})
19931 @acindex{TRY_LINK_FUNC}
19932 This macro is equivalent to
19933 @example
19934 AC_LINK_IFELSE([AC_LANG_CALL([], [@var{function}])],
19935   [@var{action-if-found}], [@var{action-if-not-found}])
19936 @end example
19937 @noindent
19938 @xref{AC_LINK_IFELSE}.
19939 @end defmac
19941 @defmac AC_TRY_RUN (@var{program}, @ovar{action-if-true}, @
19942   @ovar{action-if-false}, @ovar{action-if-cross-compiling})
19943 @acindex{TRY_RUN}
19944 Same as:
19946 @example
19947 AC_RUN_IFELSE(
19948   [AC_LANG_SOURCE([[@var{program}]])],
19949   [@var{action-if-true}],
19950   [@var{action-if-false}],
19951   [@var{action-if-cross-compiling}])
19952 @end example
19954 @noindent
19955 @xref{Runtime}.
19956 @end defmac
19958 @anchor{AC_TYPE_SIGNAL}
19959 @defmac AC_TYPE_SIGNAL
19960 @acindex{TYPE_SIGNAL}
19961 @cvindex RETSIGTYPE
19962 @hdrindex{signal.h}
19963 If @file{signal.h} declares @code{signal} as returning a pointer to a
19964 function returning @code{void}, define @code{RETSIGTYPE} to be
19965 @code{void}; otherwise, define it to be @code{int}.  These days, it is
19966 portable to assume C89, and that signal handlers return @code{void},
19967 without needing to use this macro or @code{RETSIGTYPE}.
19969 When targetting older K&R C, it is possible to define signal handlers as
19970 returning type @code{RETSIGTYPE}, and omit a return statement:
19972 @example
19973 @group
19974 RETSIGTYPE
19975 hup_handler ()
19977 @dots{}
19979 @end group
19980 @end example
19981 @end defmac
19983 @defmac AC_UID_T
19984 @acindex{UID_T}
19985 Replaced by @code{AC_TYPE_UID_T} (@pxref{AC_TYPE_UID_T}).
19986 @end defmac
19988 @defmac AC_UNISTD_H
19989 @acindex{UNISTD_H}
19990 Same as @samp{AC_CHECK_HEADERS([unistd.h])} (@pxref{AC_CHECK_HEADERS}).
19991 @end defmac
19993 @defmac AC_USG
19994 @acindex{USG}
19995 @cvindex USG
19996 Define @code{USG} if the @acronym{BSD} string functions are defined in
19997 @file{strings.h}.  You should no longer depend upon @code{USG}, but on
19998 @code{HAVE_STRING_H}; see @ref{Standard Symbols}.
19999 @end defmac
20001 @defmac AC_UTIME_NULL
20002 @acindex{UTIME_NULL}
20003 Replaced by @code{AC_FUNC_UTIME_NULL} (@pxref{AC_FUNC_UTIME_NULL}).
20004 @end defmac
20006 @defmac AC_VALIDATE_CACHED_SYSTEM_TUPLE (@ovar{cmd})
20007 @acindex{VALIDATE_CACHED_SYSTEM_TUPLE}
20008 If the cache file is inconsistent with the current host, target and
20009 build system types, it used to execute @var{cmd} or print a default
20010 error message.  This is now handled by default.
20011 @end defmac
20013 @defmac AC_VERBOSE (@var{result-description})
20014 @acindex{VERBOSE}
20015 Replaced by @code{AC_MSG_RESULT} (@pxref{AC_MSG_RESULT}).
20016 @end defmac
20018 @defmac AC_VFORK
20019 @acindex{VFORK}
20020 Replaced by @code{AC_FUNC_FORK} (@pxref{AC_FUNC_FORK}).
20021 @end defmac
20023 @defmac AC_VPRINTF
20024 @acindex{VPRINTF}
20025 Replaced by @code{AC_FUNC_VPRINTF} (@pxref{AC_FUNC_VPRINTF}).
20026 @end defmac
20028 @defmac AC_WAIT3
20029 @acindex{WAIT3}
20030 This macro was renamed @code{AC_FUNC_WAIT3}.  However, these days
20031 portable programs should use @code{waitpid}, not @code{wait3}, as
20032 @code{wait3} has been removed from Posix.
20033 @end defmac
20035 @defmac AC_WARN
20036 @acindex{WARN}
20037 Replaced by @code{AC_MSG_WARN} (@pxref{AC_MSG_WARN}).
20038 @end defmac
20040 @defmac AC_WITH (@var{package}, @var{action-if-given}, @
20041   @ovar{action-if-not-given})
20042 @acindex{WITH}
20043 This is an obsolete version of @code{AC_ARG_WITH} that does not
20044 support providing a help string (@pxref{AC_ARG_WITH}).
20045 @end defmac
20047 @defmac AC_WORDS_BIGENDIAN
20048 @acindex{WORDS_BIGENDIAN}
20049 Replaced by @code{AC_C_BIGENDIAN} (@pxref{AC_C_BIGENDIAN}).
20050 @end defmac
20052 @defmac AC_XENIX_DIR
20053 @acindex{XENIX_DIR}
20054 @ovindex LIBS
20055 This macro used to add @option{-lx} to output variable @code{LIBS} if on
20056 Xenix.  Also, if @file{dirent.h} is being checked for, added
20057 @option{-ldir} to @code{LIBS}.  Now it is merely an alias of
20058 @code{AC_HEADER_DIRENT} instead, plus some code to detect whether
20059 running @sc{xenix} on which you should not depend:
20061 @example
20062 AC_MSG_CHECKING([for Xenix])
20063 AC_EGREP_CPP([yes],
20064 [#if defined M_XENIX && !defined M_UNIX
20065   yes
20066 #endif],
20067              [AC_MSG_RESULT([yes]); XENIX=yes],
20068              [AC_MSG_RESULT([no]); XENIX=])
20069 @end example
20070 @noindent
20071 Don't use this macro, the dignified means to check the nature of the
20072 host is using @code{AC_CANONICAL_HOST} (@pxref{Canonicalizing}).
20073 @end defmac
20075 @defmac AC_YYTEXT_POINTER
20076 @acindex{YYTEXT_POINTER}
20077 This macro was renamed @code{AC_DECL_YYTEXT}, which in turn was
20078 integrated into @code{AC_PROG_LEX} (@pxref{AC_PROG_LEX}).
20079 @end defmac
20081 @node Autoconf 1
20082 @section Upgrading From Version 1
20083 @cindex Upgrading autoconf
20084 @cindex Autoconf upgrading
20086 Autoconf version 2 is mostly backward compatible with version 1.
20087 However, it introduces better ways to do some things, and doesn't
20088 support some of the ugly things in version 1.  So, depending on how
20089 sophisticated your @file{configure.ac} files are, you might have to do
20090 some manual work in order to upgrade to version 2.  This chapter points
20091 out some problems to watch for when upgrading.  Also, perhaps your
20092 @command{configure} scripts could benefit from some of the new features in
20093 version 2; the changes are summarized in the file @file{NEWS} in the
20094 Autoconf distribution.
20096 @menu
20097 * Changed File Names::          Files you might rename
20098 * Changed Makefiles::           New things to put in @file{Makefile.in}
20099 * Changed Macros::              Macro calls you might replace
20100 * Changed Results::             Changes in how to check test results
20101 * Changed Macro Writing::       Better ways to write your own macros
20102 @end menu
20104 @node Changed File Names
20105 @subsection Changed File Names
20107 If you have an @file{aclocal.m4} installed with Autoconf (as opposed to
20108 in a particular package's source directory), you must rename it to
20109 @file{acsite.m4}.  @xref{autoconf Invocation}.
20111 If you distribute @file{install.sh} with your package, rename it to
20112 @file{install-sh} so @command{make} builtin rules don't inadvertently
20113 create a file called @file{install} from it.  @code{AC_PROG_INSTALL}
20114 looks for the script under both names, but it is best to use the new name.
20116 If you were using @file{config.h.top}, @file{config.h.bot}, or
20117 @file{acconfig.h}, you still can, but you have less clutter if you
20118 use the @code{AH_} macros.  @xref{Autoheader Macros}.
20120 @node Changed Makefiles
20121 @subsection Changed Makefiles
20123 Add @samp{@@CFLAGS@@}, @samp{@@CPPFLAGS@@}, and @samp{@@LDFLAGS@@} in
20124 your @file{Makefile.in} files, so they can take advantage of the values
20125 of those variables in the environment when @command{configure} is run.
20126 Doing this isn't necessary, but it's a convenience for users.
20128 Also add @samp{@@configure_input@@} in a comment to each input file for
20129 @code{AC_OUTPUT}, so that the output files contain a comment saying
20130 they were produced by @command{configure}.  Automatically selecting the
20131 right comment syntax for all the kinds of files that people call
20132 @code{AC_OUTPUT} on became too much work.
20134 Add @file{config.log} and @file{config.cache} to the list of files you
20135 remove in @code{distclean} targets.
20137 If you have the following in @file{Makefile.in}:
20139 @example
20140 prefix = /usr/local
20141 exec_prefix = $(prefix)
20142 @end example
20144 @noindent
20145 you must change it to:
20147 @example
20148 prefix = @@prefix@@
20149 exec_prefix = @@exec_prefix@@
20150 @end example
20152 @noindent
20153 The old behavior of replacing those variables without @samp{@@}
20154 characters around them has been removed.
20156 @node Changed Macros
20157 @subsection Changed Macros
20159 Many of the macros were renamed in Autoconf version 2.  You can still
20160 use the old names, but the new ones are clearer, and it's easier to find
20161 the documentation for them.  @xref{Obsolete Macros}, for a table showing the
20162 new names for the old macros.  Use the @command{autoupdate} program to
20163 convert your @file{configure.ac} to using the new macro names.
20164 @xref{autoupdate Invocation}.
20166 Some macros have been superseded by similar ones that do the job better,
20167 but are not call-compatible.  If you get warnings about calling obsolete
20168 macros while running @command{autoconf}, you may safely ignore them, but
20169 your @command{configure} script generally works better if you follow
20170 the advice that is printed about what to replace the obsolete macros with.  In
20171 particular, the mechanism for reporting the results of tests has
20172 changed.  If you were using @command{echo} or @code{AC_VERBOSE} (perhaps
20173 via @code{AC_COMPILE_CHECK}), your @command{configure} script's output
20174 looks better if you switch to @code{AC_MSG_CHECKING} and
20175 @code{AC_MSG_RESULT}.  @xref{Printing Messages}.  Those macros work best
20176 in conjunction with cache variables.  @xref{Caching Results}.
20180 @node Changed Results
20181 @subsection Changed Results
20183 If you were checking the results of previous tests by examining the
20184 shell variable @code{DEFS}, you need to switch to checking the values of
20185 the cache variables for those tests.  @code{DEFS} no longer exists while
20186 @command{configure} is running; it is only created when generating output
20187 files.  This difference from version 1 is because properly quoting the
20188 contents of that variable turned out to be too cumbersome and
20189 inefficient to do every time @code{AC_DEFINE} is called.  @xref{Cache
20190 Variable Names}.
20192 For example, here is a @file{configure.ac} fragment written for Autoconf
20193 version 1:
20195 @example
20196 AC_HAVE_FUNCS(syslog)
20197 case "$DEFS" in
20198 *-DHAVE_SYSLOG*) ;;
20199 *) # syslog is not in the default libraries.  See if it's in some other.
20200   saved_LIBS="$LIBS"
20201   for lib in bsd socket inet; do
20202     AC_CHECKING(for syslog in -l$lib)
20203     LIBS="-l$lib $saved_LIBS"
20204     AC_HAVE_FUNCS(syslog)
20205     case "$DEFS" in
20206     *-DHAVE_SYSLOG*) break ;;
20207     *) ;;
20208     esac
20209     LIBS="$saved_LIBS"
20210   done ;;
20211 esac
20212 @end example
20214 Here is a way to write it for version 2:
20216 @example
20217 AC_CHECK_FUNCS([syslog])
20218 if test $ac_cv_func_syslog = no; then
20219   # syslog is not in the default libraries.  See if it's in some other.
20220   for lib in bsd socket inet; do
20221     AC_CHECK_LIB([$lib], [syslog], [AC_DEFINE([HAVE_SYSLOG])
20222       LIBS="-l$lib $LIBS"; break])
20223   done
20225 @end example
20227 If you were working around bugs in @code{AC_DEFINE_UNQUOTED} by adding
20228 backslashes before quotes, you need to remove them.  It now works
20229 predictably, and does not treat quotes (except back quotes) specially.
20230 @xref{Setting Output Variables}.
20232 All of the Boolean shell variables set by Autoconf macros now use
20233 @samp{yes} for the true value.  Most of them use @samp{no} for false,
20234 though for backward compatibility some use the empty string instead.  If
20235 you were relying on a shell variable being set to something like 1 or
20236 @samp{t} for true, you need to change your tests.
20238 @node Changed Macro Writing
20239 @subsection Changed Macro Writing
20241 When defining your own macros, you should now use @code{AC_DEFUN}
20242 instead of @code{define}.  @code{AC_DEFUN} automatically calls
20243 @code{AC_PROVIDE} and ensures that macros called via @code{AC_REQUIRE}
20244 do not interrupt other macros, to prevent nested @samp{checking@dots{}}
20245 messages on the screen.  There's no actual harm in continuing to use the
20246 older way, but it's less convenient and attractive.  @xref{Macro
20247 Definitions}.
20249 You probably looked at the macros that came with Autoconf as a guide for
20250 how to do things.  It would be a good idea to take a look at the new
20251 versions of them, as the style is somewhat improved and they take
20252 advantage of some new features.
20254 If you were doing tricky things with undocumented Autoconf internals
20255 (macros, variables, diversions), check whether you need to change
20256 anything to account for changes that have been made.  Perhaps you can
20257 even use an officially supported technique in version 2 instead of
20258 kludging.  Or perhaps not.
20260 To speed up your locally written feature tests, add caching to them.
20261 See whether any of your tests are of general enough usefulness to
20262 encapsulate them into macros that you can share.
20265 @node Autoconf 2.13
20266 @section Upgrading From Version 2.13
20267 @cindex Upgrading autoconf
20268 @cindex Autoconf upgrading
20270 The introduction of the previous section (@pxref{Autoconf 1}) perfectly
20271 suits this section@enddots{}
20273 @quotation
20274 Autoconf version 2.50 is mostly backward compatible with version 2.13.
20275 However, it introduces better ways to do some things, and doesn't
20276 support some of the ugly things in version 2.13.  So, depending on how
20277 sophisticated your @file{configure.ac} files are, you might have to do
20278 some manual work in order to upgrade to version 2.50.  This chapter
20279 points out some problems to watch for when upgrading.  Also, perhaps
20280 your @command{configure} scripts could benefit from some of the new
20281 features in version 2.50; the changes are summarized in the file
20282 @file{NEWS} in the Autoconf distribution.
20283 @end quotation
20285 @menu
20286 * Changed Quotation::           Broken code which used to work
20287 * New Macros::                  Interaction with foreign macros
20288 * Hosts and Cross-Compilation::  Bugward compatibility kludges
20289 * AC_LIBOBJ vs LIBOBJS::        LIBOBJS is a forbidden token
20290 * AC_FOO_IFELSE vs AC_TRY_FOO::  A more generic scheme for testing sources
20291 @end menu
20293 @node Changed Quotation
20294 @subsection Changed Quotation
20296 The most important changes are invisible to you: the implementation of
20297 most macros have completely changed.  This allowed more factorization of
20298 the code, better error messages, a higher uniformity of the user's
20299 interface etc.  Unfortunately, as a side effect, some construct which
20300 used to (miraculously) work might break starting with Autoconf 2.50.
20301 The most common culprit is bad quotation.
20303 For instance, in the following example, the message is not properly
20304 quoted:
20306 @example
20307 AC_INIT
20308 AC_CHECK_HEADERS(foo.h, ,
20309   AC_MSG_ERROR(cannot find foo.h, bailing out))
20310 AC_OUTPUT
20311 @end example
20313 @noindent
20314 Autoconf 2.13 simply ignores it:
20316 @example
20317 $ @kbd{autoconf-2.13; ./configure --silent}
20318 creating cache ./config.cache
20319 configure: error: cannot find foo.h
20321 @end example
20323 @noindent
20324 while Autoconf 2.50 produces a broken @file{configure}:
20326 @example
20327 $ @kbd{autoconf-2.50; ./configure --silent}
20328 configure: error: cannot find foo.h
20329 ./configure: exit: bad non-numeric arg `bailing'
20330 ./configure: exit: bad non-numeric arg `bailing'
20332 @end example
20334 The message needs to be quoted, and the @code{AC_MSG_ERROR} invocation
20335 too!
20337 @example
20338 AC_INIT([Example], [1.0], [bug-example@@example.org])
20339 AC_CHECK_HEADERS([foo.h], [],
20340   [AC_MSG_ERROR([cannot find foo.h, bailing out])])
20341 AC_OUTPUT
20342 @end example
20344 Many many (and many more) Autoconf macros were lacking proper quotation,
20345 including no less than@dots{} @code{AC_DEFUN} itself!
20347 @example
20348 $ @kbd{cat configure.in}
20349 AC_DEFUN([AC_PROG_INSTALL],
20350 [# My own much better version
20352 AC_INIT
20353 AC_PROG_INSTALL
20354 AC_OUTPUT
20355 $ @kbd{autoconf-2.13}
20356 autoconf: Undefined macros:
20357 ***BUG in Autoconf--please report*** AC_FD_MSG
20358 ***BUG in Autoconf--please report*** AC_EPI
20359 configure.in:1:AC_DEFUN([AC_PROG_INSTALL],
20360 configure.in:5:AC_PROG_INSTALL
20361 $ @kbd{autoconf-2.50}
20363 @end example
20366 @node New Macros
20367 @subsection New Macros
20369 @cindex undefined macro
20370 @cindex @code{_m4_divert_diversion}
20372 While Autoconf was relatively dormant in the late 1990s, Automake
20373 provided Autoconf-like macros for a while.  Starting with Autoconf 2.50
20374 in 2001, Autoconf provided
20375 versions of these macros, integrated in the @code{AC_} namespace,
20376 instead of @code{AM_}.  But in order to ease the upgrading via
20377 @command{autoupdate}, bindings to such @code{AM_} macros are provided.
20379 Unfortunately older versions of Automake (e.g., Automake 1.4)
20380 did not quote the names of these macros.
20381 Therefore, when @command{m4} finds something like
20382 @samp{AC_DEFUN(AM_TYPE_PTRDIFF_T, @dots{})} in @file{aclocal.m4},
20383 @code{AM_TYPE_PTRDIFF_T} is
20384 expanded, replaced with its Autoconf definition.
20386 Fortunately Autoconf catches pre-@code{AC_INIT} expansions, and
20387 complains, in its own words:
20389 @example
20390 $ @kbd{cat configure.ac}
20391 AC_INIT([Example], [1.0], [bug-example@@example.org])
20392 AM_TYPE_PTRDIFF_T
20393 $ @kbd{aclocal-1.4}
20394 $ @kbd{autoconf}
20395 aclocal.m4:17: error: m4_defn: undefined macro: _m4_divert_diversion
20396 aclocal.m4:17: the top level
20397 autom4te: m4 failed with exit status: 1
20399 @end example
20401 Modern versions of Automake no longer define most of these
20402 macros, and properly quote the names of the remaining macros.
20403 If you must use an old Automake, do not depend upon macros from Automake
20404 as it is simply not its job
20405 to provide macros (but the one it requires itself):
20407 @example
20408 $ @kbd{cat configure.ac}
20409 AC_INIT([Example], [1.0], [bug-example@@example.org])
20410 AM_TYPE_PTRDIFF_T
20411 $ @kbd{rm aclocal.m4}
20412 $ @kbd{autoupdate}
20413 autoupdate: `configure.ac' is updated
20414 $ @kbd{cat configure.ac}
20415 AC_INIT([Example], [1.0], [bug-example@@example.org])
20416 AC_CHECK_TYPES([ptrdiff_t])
20417 $ @kbd{aclocal-1.4}
20418 $ @kbd{autoconf}
20420 @end example
20423 @node Hosts and Cross-Compilation
20424 @subsection Hosts and Cross-Compilation
20425 @cindex Cross compilation
20427 Based on the experience of compiler writers, and after long public
20428 debates, many aspects of the cross-compilation chain have changed:
20430 @itemize @minus
20431 @item
20432 the relationship between the build, host, and target architecture types,
20434 @item
20435 the command line interface for specifying them to @command{configure},
20437 @item
20438 the variables defined in @command{configure},
20440 @item
20441 the enabling of cross-compilation mode.
20442 @end itemize
20444 @sp 1
20446 The relationship between build, host, and target have been cleaned up:
20447 the chain of default is now simply: target defaults to host, host to
20448 build, and build to the result of @command{config.guess}.  Nevertheless,
20449 in order to ease the transition from 2.13 to 2.50, the following
20450 transition scheme is implemented.  @emph{Do not rely on it}, as it will
20451 be completely disabled in a couple of releases (we cannot keep it, as it
20452 proves to cause more problems than it cures).
20454 They all default to the result of running @command{config.guess}, unless
20455 you specify either @option{--build} or @option{--host}.  In this case,
20456 the default becomes the system type you specified.  If you specify both,
20457 and they're different, @command{configure} enters cross compilation
20458 mode, so it doesn't run any tests that require execution.
20460 Hint: if you mean to override the result of @command{config.guess},
20461 prefer @option{--build} over @option{--host}.  In the future,
20462 @option{--host} will not override the name of the build system type.
20463 Whenever you specify @option{--host}, be sure to specify @option{--build}
20464 too.
20466 @sp 1
20468 For backward compatibility, @command{configure} accepts a system
20469 type as an option by itself.  Such an option overrides the
20470 defaults for build, host, and target system types.  The following
20471 configure statement configures a cross toolchain that runs on
20472 Net@acronym{BSD}/alpha but generates code for @acronym{GNU} Hurd/sparc,
20473 which is also the build platform.
20475 @example
20476 ./configure --host=alpha-netbsd sparc-gnu
20477 @end example
20479 @sp 1
20481 In Autoconf 2.13 and before, the variables @code{build}, @code{host},
20482 and @code{target} had a different semantics before and after the
20483 invocation of @code{AC_CANONICAL_BUILD} etc.  Now, the argument of
20484 @option{--build} is strictly copied into @code{build_alias}, and is left
20485 empty otherwise.  After the @code{AC_CANONICAL_BUILD}, @code{build} is
20486 set to the canonicalized build type.  To ease the transition, before,
20487 its contents is the same as that of @code{build_alias}.  Do @emph{not}
20488 rely on this broken feature.
20490 For consistency with the backward compatibility scheme exposed above,
20491 when @option{--host} is specified but @option{--build} isn't, the build
20492 system is assumed to be the same as @option{--host}, and
20493 @samp{build_alias} is set to that value.  Eventually, this
20494 historically incorrect behavior will go away.
20496 @sp 1
20498 The former scheme to enable cross-compilation proved to cause more harm
20499 than good, in particular, it used to be triggered too easily, leaving
20500 regular end users puzzled in front of cryptic error messages.
20501 @command{configure} could even enter cross-compilation mode only
20502 because the compiler was not functional.  This is mainly because
20503 @command{configure} used to try to detect cross-compilation, instead of
20504 waiting for an explicit flag from the user.
20506 Now, @command{configure} enters cross-compilation mode if and only if
20507 @option{--host} is passed.
20509 That's the short documentation.  To ease the transition between 2.13 and
20510 its successors, a more complicated scheme is implemented.  @emph{Do not
20511 rely on the following}, as it will be removed in the near future.
20513 If you specify @option{--host}, but not @option{--build}, when
20514 @command{configure} performs the first compiler test it tries to run
20515 an executable produced by the compiler.  If the execution fails, it
20516 enters cross-compilation mode.  This is fragile.  Moreover, by the time
20517 the compiler test is performed, it may be too late to modify the
20518 build-system type: other tests may have already been performed.
20519 Therefore, whenever you specify @option{--host}, be sure to specify
20520 @option{--build} too.
20522 @example
20523 ./configure --build=i686-pc-linux-gnu --host=m68k-coff
20524 @end example
20526 @noindent
20527 enters cross-compilation mode.  The former interface, which
20528 consisted in setting the compiler to a cross-compiler without informing
20529 @command{configure} is obsolete.  For instance, @command{configure}
20530 fails if it can't run the code generated by the specified compiler if you
20531 configure as follows:
20533 @example
20534 ./configure CC=m68k-coff-gcc
20535 @end example
20538 @node AC_LIBOBJ vs LIBOBJS
20539 @subsection @code{AC_LIBOBJ} vs.@: @code{LIBOBJS}
20541 Up to Autoconf 2.13, the replacement of functions was triggered via the
20542 variable @code{LIBOBJS}.  Since Autoconf 2.50, the macro
20543 @code{AC_LIBOBJ} should be used instead (@pxref{Generic Functions}).
20544 Starting at Autoconf 2.53, the use of @code{LIBOBJS} is an error.
20546 This change is mandated by the unification of the @acronym{GNU} Build System
20547 components.  In particular, the various fragile techniques used to parse
20548 a @file{configure.ac} are all replaced with the use of traces.  As a
20549 consequence, any action must be traceable, which obsoletes critical
20550 variable assignments.  Fortunately, @code{LIBOBJS} was the only problem,
20551 and it can even be handled gracefully (read, ``without your having to
20552 change something'').
20554 There were two typical uses of @code{LIBOBJS}: asking for a replacement
20555 function, and adjusting @code{LIBOBJS} for Automake and/or Libtool.
20557 @sp 1
20559 As for function replacement, the fix is immediate: use
20560 @code{AC_LIBOBJ}.  For instance:
20562 @example
20563 LIBOBJS="$LIBOBJS fnmatch.o"
20564 LIBOBJS="$LIBOBJS malloc.$ac_objext"
20565 @end example
20567 @noindent
20568 should be replaced with:
20570 @example
20571 AC_LIBOBJ([fnmatch])
20572 AC_LIBOBJ([malloc])
20573 @end example
20575 @sp 1
20577 @ovindex LIBOBJDIR
20578 When used with Automake 1.10 or newer, a suitable value for
20579 @code{LIBOBJDIR} is set so that the @code{LIBOBJS} and @code{LTLIBOBJS}
20580 can be referenced from any @file{Makefile.am}.  Even without Automake,
20581 arranging for @code{LIBOBJDIR} to be set correctly enables
20582 referencing @code{LIBOBJS} and @code{LTLIBOBJS} in another directory.
20583 The @code{LIBOBJDIR} feature is experimental.
20586 @node AC_FOO_IFELSE vs AC_TRY_FOO
20587 @subsection @code{AC_FOO_IFELSE} vs.@: @code{AC_TRY_FOO}
20589 Since Autoconf 2.50, internal codes uses @code{AC_PREPROC_IFELSE},
20590 @code{AC_COMPILE_IFELSE}, @code{AC_LINK_IFELSE}, and
20591 @code{AC_RUN_IFELSE} on one hand and @code{AC_LANG_SOURCES},
20592 and @code{AC_LANG_PROGRAM} on the other hand instead of the deprecated
20593 @code{AC_TRY_CPP}, @code{AC_TRY_COMPILE}, @code{AC_TRY_LINK}, and
20594 @code{AC_TRY_RUN}.  The motivations where:
20595 @itemize @minus
20596 @item
20597 a more consistent interface: @code{AC_TRY_COMPILE} etc.@: were double
20598 quoting their arguments;
20600 @item
20601 the combinatoric explosion is solved by decomposing on the one hand the
20602 generation of sources, and on the other hand executing the program;
20604 @item
20605 this scheme helps supporting more languages than plain C and C++.
20606 @end itemize
20608 In addition to the change of syntax, the philosophy has changed too:
20609 while emphasis was put on speed at the expense of accuracy, today's
20610 Autoconf promotes accuracy of the testing framework at, ahem@dots{}, the
20611 expense of speed.
20614 As a perfect example of what is @emph{not} to be done, here is how to
20615 find out whether a header file contains a particular declaration, such
20616 as a typedef, a structure, a structure member, or a function.  Use
20617 @code{AC_EGREP_HEADER} instead of running @code{grep} directly on the
20618 header file; on some systems the symbol might be defined in another
20619 header file that the file you are checking includes.
20621 As a (bad) example, here is how you should not check for C preprocessor
20622 symbols, either defined by header files or predefined by the C
20623 preprocessor: using @code{AC_EGREP_CPP}:
20625 @example
20626 @group
20627 AC_EGREP_CPP(yes,
20628 [#ifdef _AIX
20629   yes
20630 #endif
20631 ], is_aix=yes, is_aix=no)
20632 @end group
20633 @end example
20635 The above example, properly written would (i) use
20636 @code{AC_LANG_PROGRAM}, and (ii) run the compiler:
20638 @example
20639 @group
20640 AC_COMPILE_IFELSE([AC_LANG_PROGRAM(
20641 [[#ifndef _AIX
20642  error: This isn't AIX!
20643 #endif
20644 ]])],
20645                    [is_aix=yes],
20646                    [is_aix=no])
20647 @end group
20648 @end example
20651 @c ============================= Generating Test Suites with Autotest
20653 @node Using Autotest
20654 @chapter Generating Test Suites with Autotest
20656 @cindex Autotest
20658 @display
20659 @strong{N.B.: This section describes an experimental feature which will
20660 be part of Autoconf in a forthcoming release.  Although we believe
20661 Autotest is stabilizing, this documentation describes an interface which
20662 might change in the future: do not depend upon Autotest without
20663 subscribing to the Autoconf mailing lists.}
20664 @end display
20666 It is paradoxical that portable projects depend on nonportable tools
20667 to run their test suite.  Autoconf by itself is the paragon of this
20668 problem: although it aims at perfectly portability, up to 2.13 its
20669 test suite was using Deja@acronym{GNU}, a rich and complex testing
20670 framework, but which is far from being standard on Posix systems.
20671 Worse yet, it was likely to be missing on the most fragile platforms,
20672 the very platforms that are most likely to torture Autoconf and
20673 exhibit deficiencies.
20675 To circumvent this problem, many package maintainers have developed their
20676 own testing framework, based on simple shell scripts whose sole outputs
20677 are exit status values describing whether the test succeeded.  Most of
20678 these tests share common patterns, and this can result in lots of
20679 duplicated code and tedious maintenance.
20681 Following exactly the same reasoning that yielded to the inception of
20682 Autoconf, Autotest provides a test suite generation framework, based on
20683 M4 macros building a portable shell script.  The suite itself is
20684 equipped with automatic logging and tracing facilities which greatly
20685 diminish the interaction with bug reporters, and simple timing reports.
20687 Autoconf itself has been using Autotest for years, and we do attest that
20688 it has considerably improved the strength of the test suite and the
20689 quality of bug reports.  Other projects are known to use some generation
20690 of Autotest, such as Bison, Free Recode, Free Wdiff, @acronym{GNU} Tar, each of
20691 them with different needs, and this usage has validated Autotest as a general
20692 testing framework.
20694 Nonetheless, compared to Deja@acronym{GNU}, Autotest is inadequate for
20695 interactive tool testing, which is probably its main limitation.
20697 @menu
20698 * Using an Autotest Test Suite::  Autotest and the user
20699 * Writing Testsuites::          Autotest macros
20700 * testsuite Invocation::        Running @command{testsuite} scripts
20701 * Making testsuite Scripts::    Using autom4te to create @command{testsuite}
20702 @end menu
20704 @node Using an Autotest Test Suite
20705 @section Using an Autotest Test Suite
20707 @menu
20708 * testsuite Scripts::           The concepts of Autotest
20709 * Autotest Logs::               Their contents
20710 @end menu
20712 @node testsuite Scripts
20713 @subsection @command{testsuite} Scripts
20715 @cindex @command{testsuite}
20717 Generating testing or validation suites using Autotest is rather easy.
20718 The whole validation suite is held in a file to be processed through
20719 @command{autom4te}, itself using @acronym{GNU} M4 under the scene, to
20720 produce a stand-alone Bourne shell script which then gets distributed.
20721 Neither @command{autom4te} nor @acronym{GNU} M4 are needed at
20722 the installer's end.
20724 @cindex test group
20725 Each test of the validation suite should be part of some test group.  A
20726 @dfn{test group} is a sequence of interwoven tests that ought to be
20727 executed together, usually because one test in the group creates data
20728 files than a later test in the same group needs to read.  Complex test
20729 groups make later debugging more tedious.  It is much better to
20730 keep only a few tests per test group.  Ideally there is only one test
20731 per test group.
20733 For all but the simplest packages, some file such as @file{testsuite.at}
20734 does not fully hold all test sources, as these are often easier to
20735 maintain in separate files.  Each of these separate files holds a single
20736 test group, or a sequence of test groups all addressing some common
20737 functionality in the package.  In such cases, @file{testsuite.at}
20738 merely initializes the validation suite, and sometimes does elementary
20739 health checking, before listing include statements for all other test
20740 files.  The special file @file{package.m4}, containing the
20741 identification of the package, is automatically included if found.
20743 A convenient alternative consists in moving all the global issues
20744 (local Autotest macros, elementary health checking, and @code{AT_INIT}
20745 invocation) into the file @code{local.at}, and making
20746 @file{testsuite.at} be a simple list of @code{m4_include} of sub test
20747 suites.  In such case, generating the whole test suite or pieces of it
20748 is only a matter of choosing the @command{autom4te} command line
20749 arguments.
20751 The validation scripts that Autotest produces are by convention called
20752 @command{testsuite}.  When run, @command{testsuite} executes each test
20753 group in turn, producing only one summary line per test to say if that
20754 particular test succeeded or failed.  At end of all tests, summarizing
20755 counters get printed.  One debugging directory is left for each test
20756 group which failed, if any: such directories are named
20757 @file{testsuite.dir/@var{nn}}, where @var{nn} is the sequence number of
20758 the test group, and they include:
20760 @itemize @bullet
20761 @item a debugging script named @file{run} which reruns the test in
20762 @dfn{debug mode} (@pxref{testsuite Invocation}).  The automatic generation
20763 of debugging scripts has the purpose of easing the chase for bugs.
20765 @item all the files created with @code{AT_DATA}
20767 @item a log of the run, named @file{testsuite.log}
20768 @end itemize
20770 In the ideal situation, none of the tests fail, and consequently no
20771 debugging directory is left behind for validation.
20773 It often happens in practice that individual tests in the validation
20774 suite need to get information coming out of the configuration process.
20775 Some of this information, common for all validation suites, is provided
20776 through the file @file{atconfig}, automatically created by
20777 @code{AC_CONFIG_TESTDIR}.  For configuration informations which your
20778 testing environment specifically needs, you might prepare an optional
20779 file named @file{atlocal.in}, instantiated by @code{AC_CONFIG_FILES}.
20780 The configuration process produces @file{atconfig} and @file{atlocal}
20781 out of these two input files, and these two produced files are
20782 automatically read by the @file{testsuite} script.
20784 Here is a diagram showing the relationship between files.
20786 @noindent
20787 Files used in preparing a software package for distribution:
20789 @example
20790                 [package.m4] -->.
20791                                  \
20792 subfile-1.at ->.  [local.at] ---->+
20793     ...         \                  \
20794 subfile-i.at ---->-- testsuite.at -->-- autom4te* -->testsuite
20795     ...         /
20796 subfile-n.at ->'
20797 @end example
20799 @noindent
20800 Files used in configuring a software package:
20802 @example
20803                                      .--> atconfig
20804                                     /
20805 [atlocal.in] -->  config.status* --<
20806                                     \
20807                                      `--> [atlocal]
20808 @end example
20810 @noindent
20811 Files created during the test suite execution:
20813 @example
20814 atconfig -->.                    .--> testsuite.log
20815              \                  /
20816               >-- testsuite* --<
20817              /                  \
20818 [atlocal] ->'                    `--> [testsuite.dir]
20819 @end example
20822 @node Autotest Logs
20823 @subsection Autotest Logs
20825 When run, the test suite creates a log file named after itself, e.g., a
20826 test suite named @command{testsuite} creates @file{testsuite.log}.  It
20827 contains a lot of information, usually more than maintainers actually
20828 need, but therefore most of the time it contains all that is needed:
20830 @table @asis
20831 @item command line arguments
20832 @c akim s/to consist in/to consist of/
20833 A bad but unfortunately widespread habit consists of
20834 setting environment variables before the command, such as in
20835 @samp{CC=my-home-grown-cc ./testsuite}.  The test suite does not
20836 know this change, hence (i) it cannot report it to you, and (ii)
20837 it cannot preserve the value of @code{CC} for subsequent runs.
20838 Autoconf faced exactly the same problem, and solved it by asking
20839 users to pass the variable definitions as command line arguments.
20840 Autotest requires this rule, too, but has no means to enforce it; the log
20841 then contains a trace of the variables that were changed by the user.
20843 @item @file{ChangeLog} excerpts
20844 The topmost lines of all the @file{ChangeLog} files found in the source
20845 hierarchy.  This is especially useful when bugs are reported against
20846 development versions of the package, since the version string does not
20847 provide sufficient information to know the exact state of the sources
20848 the user compiled.  Of course, this relies on the use of a
20849 @file{ChangeLog}.
20851 @item build machine
20852 Running a test suite in a cross-compile environment is not an easy task,
20853 since it would mean having the test suite run on a machine @var{build},
20854 while running programs on a machine @var{host}.  It is much simpler to
20855 run both the test suite and the programs on @var{host}, but then, from
20856 the point of view of the test suite, there remains a single environment,
20857 @var{host} = @var{build}.  The log contains relevant information on the
20858 state of the build machine, including some important environment
20859 variables.
20860 @c FIXME: How about having an M4sh macro to say `hey, log the value
20861 @c of `@dots{}'?  This would help both Autoconf and Autotest.
20863 @item tested programs
20864 The absolute file name and answers to @option{--version} of the tested
20865 programs (see @ref{Writing Testsuites}, @code{AT_TESTED}).
20867 @item configuration log
20868 The contents of @file{config.log}, as created by @command{configure},
20869 are appended.  It contains the configuration flags and a detailed report
20870 on the configuration itself.
20871 @end table
20874 @node Writing Testsuites
20875 @section Writing @file{testsuite.at}
20877 The @file{testsuite.at} is a Bourne shell script making use of special
20878 Autotest M4 macros.  It often contains a call to @code{AT_INIT} near
20879 its beginning followed by one call to @code{m4_include} per source file
20880 for tests.  Each such included file, or the remainder of
20881 @file{testsuite.at} if include files are not used, contain a sequence of
20882 test groups.  Each test group begins with a call to @code{AT_SETUP},
20883 then an arbitrary number of shell commands or calls to @code{AT_CHECK},
20884 and then completes with a call to @code{AT_CLEANUP}.  Multiple test
20885 groups can be categorized by a call to @code{AT_BANNER}.
20887 @defmac AT_INIT (@ovar{name})
20888 @atindex{INIT}
20889 @c FIXME: Not clear, plus duplication of the information.
20890 Initialize Autotest.  Giving a @var{name} to the test suite is
20891 encouraged if your package includes several test suites.  In any case,
20892 the test suite always displays the package name and version.  It also
20893 inherits the package bug report address.
20894 @end defmac
20896 @defmac AT_COPYRIGHT (@var{copyright-notice})
20897 @atindex{COPYRIGHT}
20898 @cindex Copyright Notice
20899 State that, in addition to the Free Software Foundation's copyright on
20900 the Autotest macros, parts of your test suite are covered by
20901 @var{copyright-notice}.
20903 The @var{copyright-notice} shows up in both the head of
20904 @command{testsuite} and in @samp{testsuite --version}.
20905 @end defmac
20907 @defmac AT_TESTED (@var{executables})
20908 @atindex{TESTED}
20909 Log the file name and answer to @option{--version} of each program in
20910 space-separated list @var{executables}.  Several invocations register
20911 new executables, in other words, don't fear registering one program
20912 several times.
20913 @end defmac
20915 Autotest test suites rely on @env{PATH} to find the tested program.
20916 This avoids the need to generate absolute names of the various tools, and
20917 makes it possible to test installed programs.  Therefore, knowing which
20918 programs are being exercised is crucial to understanding problems in
20919 the test suite itself, or its occasional misuses.  It is a good idea to
20920 also subscribe foreign programs you depend upon, to avoid incompatible
20921 diagnostics.
20923 @sp 1
20925 @defmac AT_BANNER (@var{test-category-name})
20926 @atindex{BANNER}
20927 This macro identifies the start of a category of related test groups.
20928 When the resulting @file{testsuite} is invoked with more than one test
20929 group to run, its output will include a banner containing
20930 @var{test-category-name} prior to any tests run from that category.  The
20931 banner should be no more than about 40 or 50 characters.  A blank banner
20932 will not print, effectively ending a category and letting subsequent
20933 test groups behave as though they are uncategorized when run in
20934 isolation.
20935 @end defmac
20937 @defmac AT_SETUP (@var{test-group-name})
20938 @atindex{SETUP}
20939 This macro starts a group of related tests, all to be executed in the
20940 same subshell.  It accepts a single argument, which holds a few words
20941 (no more than about 30 or 40 characters) quickly describing the purpose
20942 of the test group being started.  @var{test-group-name} must not expand
20943 to unbalanced quotes, although quadrigraphs can be used.
20944 @end defmac
20946 @defmac AT_KEYWORDS (@var{keywords})
20947 @atindex{KEYWORDS}
20948 Associate the space-separated list of @var{keywords} to the enclosing
20949 test group.  This makes it possible to run ``slices'' of the test suite.
20950 For instance, if some of your test groups exercise some @samp{foo}
20951 feature, then using @samp{AT_KEYWORDS(foo)} lets you run
20952 @samp{./testsuite -k foo} to run exclusively these test groups.  The
20953 @var{title} of the test group is automatically recorded to
20954 @code{AT_KEYWORDS}.
20956 Several invocations within a test group accumulate new keywords.  In
20957 other words, don't fear registering the same keyword several times in a
20958 test group.
20959 @end defmac
20961 @defmac AT_CAPTURE_FILE (@var{file})
20962 @atindex{CAPTURE_FILE}
20963 If the current test group fails, log the contents of @var{file}.
20964 Several identical calls within one test group have no additional effect.
20965 @end defmac
20967 @defmac AT_XFAIL_IF (@var{shell-condition})
20968 @atindex{XFAIL_IF}
20969 Determine whether the test is expected to fail because it is a known
20970 bug (for unsupported features, you should skip the test).
20971 @var{shell-condition} is a shell expression such as a @code{test}
20972 command; you can instantiate this macro many times from within the
20973 same test group, and one of the conditions is enough to turn
20974 the test into an expected failure.
20975 @end defmac
20977 @defmac AT_CLEANUP
20978 @atindex{CLEANUP}
20979 End the current test group.
20980 @end defmac
20982 @sp 1
20984 @defmac AT_DATA (@var{file}, @var{contents})
20985 @atindex{DATA}
20986 Initialize an input data @var{file} with given @var{contents}.  Of
20987 course, the @var{contents} have to be properly quoted between square
20988 brackets to protect against included commas or spurious M4
20989 expansion.  The contents must end with an end of line.  @var{file} must
20990 be a single shell word that expands into a single file name.
20991 @end defmac
20993 @defmac AT_CHECK (@var{commands}, @dvar{status, 0}, @dvar{stdout, }, @
20994   @dvar{stderr, }, @ovar{run-if-fail}, @ovar{run-if-pass})
20995 @atindex{CHECK}
20996 Execute a test by performing given shell @var{commands}.  These commands
20997 should normally exit with @var{status}, while producing expected
20998 @var{stdout} and @var{stderr} contents.  If @var{commands} exit with
20999 status 77, then the whole test group is skipped.  Otherwise, if this test
21000 fails, run shell commands @var{run-if-fail} or, if this test passes, run shell
21001 commands @var{run-if-pass}.
21003 This macro must be invoked in between @code{AT_SETUP} and @code{AT_CLEANUP}.
21005 @c Previously, we had this:
21006 @c  The @var{commands} @emph{must not} redirect the standard output, nor the
21007 @c  standard error.
21008 @c to prevent trigerring the double redirect bug on Ultrix, see
21009 @c `File Descriptors'.  This was too restricting, and Ultrix is pretty
21010 @c much dead, so we dropped the limitation; the obvious workaround on
21011 @c Ultrix is to use a working shell there.
21013 If @var{status}, or @var{stdout}, or @var{stderr} is @samp{ignore}, then
21014 the corresponding value is not checked.
21016 The special value @samp{expout} for @var{stdout} means the expected
21017 output of the @var{commands} is the content of the file @file{expout}.
21018 If @var{stdout} is @samp{stdout}, then the standard output of the
21019 @var{commands} is available for further tests in the file @file{stdout}.
21020 Similarly for @var{stderr} with @samp{experr} and @samp{stderr}.
21021 @end defmac
21024 @node testsuite Invocation
21025 @section Running @command{testsuite} Scripts
21026 @cindex @command{testsuite}
21028 Autotest test suites support the following arguments:
21030 @table @option
21031 @item --help
21032 @itemx -h
21033 Display the list of options and exit successfully.
21035 @item --version
21036 @itemx -V
21037 Display the version of the test suite and exit successfully.
21039 @item --directory=@var{dir}
21040 @itemx -C @var{dir}
21041 Change the current directory to @var{dir} before creating any files.
21042 Useful for running the testsuite in a subdirectory from a top-level
21043 Makefile.
21045 @item --jobs@r{[}=@var{n}@r{]}
21046 @itemx -j@ovar{n}
21047 Run @var{n} tests in parallel, if possible.  If @var{n} is not given,
21048 run all given tests in parallel.  Note that there should be no space
21049 before the argument to @option{-j}, as @option{-j @var{number}} denotes
21050 the separate arguments @option{-j} and @option{@var{number}}, see below.
21052 In parallel mode, the standard input device of the testsuite script is
21053 not available to commands inside a test group.  Furthermore, banner
21054 lines are not printed, and the summary line for each test group is
21055 output after the test group completes.  Summary lines may appear
21056 unordered.  If verbose and trace output are enabled (see below), they
21057 may appear intermixed from concurrently running tests.
21059 Parallel mode requires the @command{mkfifo} command to work, and will be
21060 silently disabled otherwise.
21062 @item --clean
21063 @itemx -c
21064 Remove all the files the test suite might have created and exit.  Meant
21065 for @code{clean} Make targets.
21067 @item --list
21068 @itemx -l
21069 List all the tests (or only the selection), including their possible
21070 keywords.
21071 @end table
21073 @sp 1
21075 By default all tests are performed (or described with
21076 @option{--list}) in the default environment first silently, then
21077 verbosely, but the environment, set of tests, and verbosity level can be
21078 tuned:
21080 @table @samp
21081 @item @var{variable}=@var{value}
21082 Set the environment @var{variable} to @var{value}.  Use this rather
21083 than @samp{FOO=foo ./testsuite} as debugging scripts would then run in a
21084 different environment.
21086 @cindex @code{AUTOTEST_PATH}
21087 The variable @code{AUTOTEST_PATH} specifies the testing path to prepend
21088 to @env{PATH}.  Relative directory names (not starting with
21089 @samp{/}) are considered to be relative to the top level of the
21090 package being built.  All directories are made absolute, first
21091 starting from the top level @emph{build} tree, then from the
21092 @emph{source} tree.  For instance @samp{./testsuite
21093 AUTOTEST_PATH=tests:bin} for a @file{/src/foo-1.0} source package built
21094 in @file{/tmp/foo} results in @samp{/tmp/foo/tests:/tmp/foo/bin} and
21095 then @samp{/src/foo-1.0/tests:/src/foo-1.0/bin} being prepended to
21096 @env{PATH}.
21098 @item @var{number}
21099 @itemx @var{number}-@var{number}
21100 @itemx @var{number}-
21101 @itemx -@var{number}
21102 Add the corresponding test groups, with obvious semantics, to the
21103 selection.
21105 @item --keywords=@var{keywords}
21106 @itemx -k @var{keywords}
21107 Add to the selection the test groups with title or keywords (arguments
21108 to @code{AT_SETUP} or @code{AT_KEYWORDS}) that match @emph{all} keywords
21109 of the comma separated list @var{keywords}, case-insensitively.  Use
21110 @samp{!} immediately before the keyword to invert the selection for this
21111 keyword.  By default, the keywords match whole words; enclose them in
21112 @samp{.*} to also match parts of words.
21114 For example, running
21116 @example
21117 @kbd{./testsuite -k 'autoupdate,.*FUNC.*'}
21118 @end example
21120 @noindent
21121 selects all tests tagged @samp{autoupdate} @emph{and} with tags
21122 containing @samp{FUNC} (as in @samp{AC_CHECK_FUNC}, @samp{AC_FUNC_ALLOCA},
21123 etc.), while
21125 @example
21126 @kbd{./testsuite -k '!autoupdate' -k '.*FUNC.*'}
21127 @end example
21129 @noindent
21130 selects all tests not tagged @samp{autoupdate} @emph{or} with tags
21131 containing @samp{FUNC}.
21133 @item --errexit
21134 @itemx -e
21135 If any test fails, immediately abort testing.  It implies
21136 @option{--debug}: post test group clean up, and top-level logging
21137 are inhibited.  This option is meant for the full test
21138 suite, it is not really useful for generated debugging scripts.
21139 If the testsuite is run in parallel mode using @option{--jobs},
21140 then concurrently running tests will finish before exiting.
21142 @item --verbose
21143 @itemx -v
21144 Force more verbosity in the detailed output of what is being done.  This
21145 is the default for debugging scripts.
21147 @item --debug
21148 @itemx -d
21149 Do not remove the files after a test group was performed ---but they are
21150 still removed @emph{before}, therefore using this option is sane when
21151 running several test groups.  Create debugging scripts.  Do not
21152 overwrite the top-level
21153 log (in order to preserve supposedly existing full log file).  This is
21154 the default for debugging scripts, but it can also be useful to debug
21155 the testsuite itself.
21157 @item --trace
21158 @itemx -x
21159 Trigger shell tracing of the test groups.
21160 @end table
21163 @node Making testsuite Scripts
21164 @section Making @command{testsuite} Scripts
21166 For putting Autotest into movement, you need some configuration and
21167 makefile machinery.  We recommend, at least if your package uses deep or
21168 shallow hierarchies, that you use @file{tests/} as the name of the
21169 directory holding all your tests and their makefile.  Here is a
21170 check list of things to do.
21172 @itemize @minus
21174 @item
21175 @cindex @file{package.m4}
21176 @atindex{PACKAGE_STRING}
21177 @atindex{PACKAGE_BUGREPORT}
21178 @atindex{PACKAGE_NAME}
21179 @atindex{PACKAGE_TARNAME}
21180 @atindex{PACKAGE_VERSION}
21181 Make sure to create the file @file{package.m4}, which defines the
21182 identity of the package.  It must define @code{AT_PACKAGE_STRING}, the
21183 full signature of the package, and @code{AT_PACKAGE_BUGREPORT}, the
21184 address to which bug reports should be sent.  For sake of completeness,
21185 we suggest that you also define @code{AT_PACKAGE_NAME},
21186 @code{AT_PACKAGE_TARNAME}, and @code{AT_PACKAGE_VERSION}.
21187 @xref{Initializing configure}, for a description of these variables.  We
21188 suggest the following makefile excerpt:
21190 @smallexample
21191 # The `:;' works around a Bash 3.2 bug when the output is not writeable.
21192 $(srcdir)/package.m4: $(top_srcdir)/configure.ac
21193         :;@{ \
21194           echo '# Signature of the current package.' && \
21195           echo 'm4_define([AT_PACKAGE_NAME],      [@@PACKAGE_NAME@@])' && \
21196           echo 'm4_define([AT_PACKAGE_TARNAME],   [@@PACKAGE_TARNAME@@])' && \
21197           echo 'm4_define([AT_PACKAGE_VERSION],   [@@PACKAGE_VERSION@@])' && \
21198           echo 'm4_define([AT_PACKAGE_STRING],    [@@PACKAGE_STRING@@])' && \
21199           echo 'm4_define([AT_PACKAGE_BUGREPORT], [@@PACKAGE_BUGREPORT@@])'; \
21200         @} >'$(srcdir)/package.m4'
21201 @end smallexample
21203 @noindent
21204 Be sure to distribute @file{package.m4} and to put it into the source
21205 hierarchy: the test suite ought to be shipped!
21207 @item
21208 Invoke @code{AC_CONFIG_TESTDIR}.
21210 @defmac AC_CONFIG_TESTDIR (@var{directory}, @dvar{test-path, directory})
21211 @acindex{CONFIG_TESTDIR}
21212 An Autotest test suite is to be configured in @var{directory}.  This
21213 macro requires the instantiation of @file{@var{directory}/atconfig} from
21214 @file{@var{directory}/atconfig.in}, and sets the default
21215 @code{AUTOTEST_PATH} to @var{test-path} (@pxref{testsuite Invocation}).
21216 @end defmac
21218 @item
21219 Still within @file{configure.ac}, as appropriate, ensure that some
21220 @code{AC_CONFIG_FILES} command includes substitution for
21221 @file{tests/atlocal}.
21223 @item
21224 The @file{tests/Makefile.in} should be modified so the validation in
21225 your package is triggered by @samp{make check}.  An example is provided
21226 below.
21227 @end itemize
21229 With Automake, here is a minimal example about how to link @samp{make
21230 check} with a validation suite.
21232 @example
21233 EXTRA_DIST = testsuite.at $(TESTSUITE) atlocal.in
21234 TESTSUITE = $(srcdir)/testsuite
21236 check-local: atconfig atlocal $(TESTSUITE)
21237         $(SHELL) '$(TESTSUITE)' $(TESTSUITEFLAGS)
21239 installcheck-local: atconfig atlocal $(TESTSUITE)
21240         $(SHELL) '$(TESTSUITE)' AUTOTEST_PATH='$(bindir)' \
21241           $(TESTSUITEFLAGS)
21243 clean-local:
21244         test ! -f '$(TESTSUITE)' || \
21245          $(SHELL) '$(TESTSUITE)' --clean
21247 AUTOTEST = $(AUTOM4TE) --language=autotest
21248 $(TESTSUITE): $(srcdir)/testsuite.at
21249         $(AUTOTEST) -I '$(srcdir)' -o $@@.tmp $@@.at
21250         mv $@@.tmp $@@
21251 @end example
21253 You might want to list explicitly the dependencies, i.e., the list of
21254 the files @file{testsuite.at} includes.
21256 If you don't use Automake, you might need to add lines inspired from the
21257 following:
21259 @example
21260 subdir = tests
21262 atconfig: $(top_builddir)/config.status
21263         cd $(top_builddir) && \
21264            $(SHELL) ./config.status $(subdir)/$@@
21266 atlocal: $(srcdir)/atlocal.in $(top_builddir)/config.status
21267         cd $(top_builddir) && \
21268            $(SHELL) ./config.status $(subdir)/$@@
21269 @end example
21271 @noindent
21272 and manage to have @code{$(EXTRA_DIST)} distributed.
21274 If you use Automake, however, you don't need to add a rule to generate
21275 @file{atlocal}.
21277 With all this in place, and if you have not initialized @samp{TESTSUITEFLAGS}
21278 within your makefile, you can fine-tune test suite execution with this
21279 variable, for example:
21281 @example
21282 make check TESTSUITEFLAGS='-v -d -x 75 -k AC_PROG_CC CFLAGS=-g'
21283 @end example
21287 @c =============================== Frequent Autoconf Questions, with answers
21289 @node FAQ
21290 @chapter Frequent Autoconf Questions, with answers
21292 Several questions about Autoconf come up occasionally.  Here some of them
21293 are addressed.
21295 @menu
21296 * Distributing::                Distributing @command{configure} scripts
21297 * Why GNU M4::                  Why not use the standard M4?
21298 * Bootstrapping::               Autoconf and @acronym{GNU} M4 require each other?
21299 * Why Not Imake::               Why @acronym{GNU} uses @command{configure} instead of Imake
21300 * Defining Directories::        Passing @code{datadir} to program
21301 * Autom4te Cache::              What is it?  Can I remove it?
21302 * Present But Cannot Be Compiled::  Compiler and Preprocessor Disagree
21303 @end menu
21305 @node Distributing
21306 @section Distributing @command{configure} Scripts
21307 @cindex License
21309 @display
21310 What are the restrictions on distributing @command{configure}
21311 scripts that Autoconf generates?  How does that affect my
21312 programs that use them?
21313 @end display
21315 There are no restrictions on how the configuration scripts that Autoconf
21316 produces may be distributed or used.  In Autoconf version 1, they were
21317 covered by the @acronym{GNU} General Public License.  We still encourage
21318 software authors to distribute their work under terms like those of the
21319 @acronym{GPL}, but doing so is not required to use Autoconf.
21321 Of the other files that might be used with @command{configure},
21322 @file{config.h.in} is under whatever copyright you use for your
21323 @file{configure.ac}.  @file{config.sub} and @file{config.guess} have an
21324 exception to the @acronym{GPL} when they are used with an Autoconf-generated
21325 @command{configure} script, which permits you to distribute them under the
21326 same terms as the rest of your package.  @file{install-sh} is from the X
21327 Consortium and is not copyrighted.
21329 @node Why GNU M4
21330 @section Why Require @acronym{GNU} M4?
21332 @display
21333 Why does Autoconf require @acronym{GNU} M4?
21334 @end display
21336 Many M4 implementations have hard-coded limitations on the size and
21337 number of macros that Autoconf exceeds.  They also lack several
21338 builtin macros that it would be difficult to get along without in a
21339 sophisticated application like Autoconf, including:
21341 @example
21342 m4_builtin
21343 m4_indir
21344 m4_bpatsubst
21345 __file__
21346 __line__
21347 @end example
21349 Autoconf requires version 1.4.5 or later of @acronym{GNU} M4.
21351 Since only software maintainers need to use Autoconf, and since @acronym{GNU}
21352 M4 is simple to configure and install, it seems reasonable to require
21353 @acronym{GNU} M4 to be installed also.  Many maintainers of @acronym{GNU} and
21354 other free software already have most of the @acronym{GNU} utilities
21355 installed, since they prefer them.
21357 @node Bootstrapping
21358 @section How Can I Bootstrap?
21359 @cindex Bootstrap
21361 @display
21362 If Autoconf requires @acronym{GNU} M4 and @acronym{GNU} M4 has an Autoconf
21363 @command{configure} script, how do I bootstrap?  It seems like a chicken
21364 and egg problem!
21365 @end display
21367 This is a misunderstanding.  Although @acronym{GNU} M4 does come with a
21368 @command{configure} script produced by Autoconf, Autoconf is not required
21369 in order to run the script and install @acronym{GNU} M4.  Autoconf is only
21370 required if you want to change the M4 @command{configure} script, which few
21371 people have to do (mainly its maintainer).
21373 @node Why Not Imake
21374 @section Why Not Imake?
21375 @cindex Imake
21377 @display
21378 Why not use Imake instead of @command{configure} scripts?
21379 @end display
21381 Several people have written addressing this question, so I include
21382 adaptations of their explanations here.
21384 The following answer is based on one written by Richard Pixley:
21386 @quotation
21387 Autoconf generated scripts frequently work on machines that it has
21388 never been set up to handle before.  That is, it does a good job of
21389 inferring a configuration for a new system.  Imake cannot do this.
21391 Imake uses a common database of host specific data.  For X11, this makes
21392 sense because the distribution is made as a collection of tools, by one
21393 central authority who has control over the database.
21395 @acronym{GNU} tools are not released this way.  Each @acronym{GNU} tool has a
21396 maintainer; these maintainers are scattered across the world.  Using a
21397 common database would be a maintenance nightmare.  Autoconf may appear
21398 to be this kind of database, but in fact it is not.  Instead of listing
21399 host dependencies, it lists program requirements.
21401 If you view the @acronym{GNU} suite as a collection of native tools, then the
21402 problems are similar.  But the @acronym{GNU} development tools can be
21403 configured as cross tools in almost any host+target permutation.  All of
21404 these configurations can be installed concurrently.  They can even be
21405 configured to share host independent files across hosts.  Imake doesn't
21406 address these issues.
21408 Imake templates are a form of standardization.  The @acronym{GNU} coding
21409 standards address the same issues without necessarily imposing the same
21410 restrictions.
21411 @end quotation
21414 Here is some further explanation, written by Per Bothner:
21416 @quotation
21417 One of the advantages of Imake is that it easy to generate large
21418 makefiles using the @samp{#include} and macro mechanisms of @command{cpp}.
21419 However, @code{cpp} is not programmable: it has limited conditional
21420 facilities, and no looping.  And @code{cpp} cannot inspect its
21421 environment.
21423 All of these problems are solved by using @code{sh} instead of
21424 @code{cpp}.  The shell is fully programmable, has macro substitution,
21425 can execute (or source) other shell scripts, and can inspect its
21426 environment.
21427 @end quotation
21430 Paul Eggert elaborates more:
21432 @quotation
21433 With Autoconf, installers need not assume that Imake itself is already
21434 installed and working well.  This may not seem like much of an advantage
21435 to people who are accustomed to Imake.  But on many hosts Imake is not
21436 installed or the default installation is not working well, and requiring
21437 Imake to install a package hinders the acceptance of that package on
21438 those hosts.  For example, the Imake template and configuration files
21439 might not be installed properly on a host, or the Imake build procedure
21440 might wrongly assume that all source files are in one big directory
21441 tree, or the Imake configuration might assume one compiler whereas the
21442 package or the installer needs to use another, or there might be a
21443 version mismatch between the Imake expected by the package and the Imake
21444 supported by the host.  These problems are much rarer with Autoconf,
21445 where each package comes with its own independent configuration
21446 processor.
21448 Also, Imake often suffers from unexpected interactions between
21449 @command{make} and the installer's C preprocessor.  The fundamental problem
21450 here is that the C preprocessor was designed to preprocess C programs,
21451 not makefiles.  This is much less of a problem with Autoconf,
21452 which uses the general-purpose preprocessor M4, and where the
21453 package's author (rather than the installer) does the preprocessing in a
21454 standard way.
21455 @end quotation
21458 Finally, Mark Eichin notes:
21460 @quotation
21461 Imake isn't all that extensible, either.  In order to add new features to
21462 Imake, you need to provide your own project template, and duplicate most
21463 of the features of the existing one.  This means that for a sophisticated
21464 project, using the vendor-provided Imake templates fails to provide any
21465 leverage---since they don't cover anything that your own project needs
21466 (unless it is an X11 program).
21468 On the other side, though:
21470 The one advantage that Imake has over @command{configure}:
21471 @file{Imakefile} files tend to be much shorter (likewise, less redundant)
21472 than @file{Makefile.in} files.  There is a fix to this, however---at least
21473 for the Kerberos V5 tree, we've modified things to call in common
21474 @file{post.in} and @file{pre.in} makefile fragments for the
21475 entire tree.  This means that a lot of common things don't have to be
21476 duplicated, even though they normally are in @command{configure} setups.
21477 @end quotation
21480 @node Defining Directories
21481 @section How Do I @code{#define} Installation Directories?
21483 @display
21484 My program needs library files, installed in @code{datadir} and
21485 similar.  If I use
21487 @example
21488 AC_DEFINE_UNQUOTED([DATADIR], [$datadir],
21489   [Define to the read-only architecture-independent
21490    data directory.])
21491 @end example
21493 @noindent
21494 I get
21496 @example
21497 #define DATADIR "$@{prefix@}/share"
21498 @end example
21499 @end display
21501 As already explained, this behavior is on purpose, mandated by the
21502 @acronym{GNU} Coding Standards, see @ref{Installation Directory
21503 Variables}.  There are several means to achieve a similar goal:
21505 @itemize @minus
21506 @item
21507 Do not use @code{AC_DEFINE} but use your makefile to pass the
21508 actual value of @code{datadir} via compilation flags.
21509 @xref{Installation Directory Variables}, for the details.
21511 @item
21512 This solution can be simplified when compiling a program: you may either
21513 extend the @code{CPPFLAGS}:
21515 @example
21516 CPPFLAGS = -DDATADIR='"$(datadir)"' @@CPPFLAGS@@
21517 @end example
21519 @noindent
21520 If you are using Automake, you should use @code{AM_CPPFLAGS} instead:
21522 @example
21523 AM_CPPFLAGS = -DDATADIR='"$(datadir)"'
21524 @end example
21526 @noindent
21527 Alternatively, create a dedicated header file:
21529 @example
21530 DISTCLEANFILES = myprog-paths.h
21531 myprog-paths.h: Makefile
21532         echo '#define DATADIR "$(datadir)"' >$@@
21533 @end example
21535 @item
21536 Use @code{AC_DEFINE} but have @command{configure} compute the literal
21537 value of @code{datadir} and others.  Many people have wrapped macros to
21538 automate this task; for an example, see the macro @code{AC_DEFINE_DIR} from
21539 the @uref{http://@/autoconf-archive@/.cryp.to/, Autoconf Macro
21540 Archive}.
21542 This solution does not conform to the @acronym{GNU} Coding Standards.
21544 @item
21545 Note that all the previous solutions hard wire the absolute name of
21546 these directories in the executables, which is not a good property.  You
21547 may try to compute the names relative to @code{prefix}, and try to
21548 find @code{prefix} at runtime, this way your package is relocatable.
21549 @end itemize
21552 @node Autom4te Cache
21553 @section What is @file{autom4te.cache}?
21555 @display
21556 What is this directory @file{autom4te.cache}?  Can I safely remove it?
21557 @end display
21559 In the @acronym{GNU} Build System, @file{configure.ac} plays a central
21560 role and is read by many tools: @command{autoconf} to create
21561 @file{configure}, @command{autoheader} to create @file{config.h.in},
21562 @command{automake} to create @file{Makefile.in}, @command{autoscan} to
21563 check the completeness of @file{configure.ac}, @command{autoreconf} to
21564 check the @acronym{GNU} Build System components that are used.  To
21565 ``read @file{configure.ac}'' actually means to compile it with M4,
21566 which can be a long process for complex @file{configure.ac}.
21568 This is why all these tools, instead of running directly M4, invoke
21569 @command{autom4te} (@pxref{autom4te Invocation}) which, while answering to
21570 a specific demand, stores additional information in
21571 @file{autom4te.cache} for future runs.  For instance, if you run
21572 @command{autoconf}, behind the scenes, @command{autom4te} also
21573 stores information for the other tools, so that when you invoke
21574 @command{autoheader} or @command{automake} etc., reprocessing
21575 @file{configure.ac} is not needed.  The speed up is frequently 30%,
21576 and is increasing with the size of @file{configure.ac}.
21578 But it is and remains being simply a cache: you can safely remove it.
21580 @sp 1
21582 @display
21583 Can I permanently get rid of it?
21584 @end display
21586 The creation of this cache can be disabled from
21587 @file{~/.autom4te.cfg}, see @ref{Customizing autom4te}, for more
21588 details.  You should be aware that disabling the cache slows down the
21589 Autoconf test suite by 40%.  The more @acronym{GNU} Build System
21590 components are used, the more the cache is useful; for instance
21591 running @samp{autoreconf -f} on the Core Utilities is twice slower without
21592 the cache @emph{although @option{--force} implies that the cache is
21593 not fully exploited}, and eight times slower than without
21594 @option{--force}.
21597 @node Present But Cannot Be Compiled
21598 @section Header Present But Cannot Be Compiled
21600 The most important guideline to bear in mind when checking for
21601 features is to mimic as much as possible the intended use.
21602 Unfortunately, old versions of @code{AC_CHECK_HEADER} and
21603 @code{AC_CHECK_HEADERS} failed to follow this idea, and called
21604 the preprocessor, instead of the compiler, to check for headers.  As a
21605 result, incompatibilities between headers went unnoticed during
21606 configuration, and maintainers finally had to deal with this issue
21607 elsewhere.
21609 As of Autoconf 2.56 both checks are performed, and @command{configure}
21610 complains loudly if the compiler and the preprocessor do not agree.
21611 For the time being the result used is that of the preprocessor, to give
21612 maintainers time to adjust their @file{configure.ac}, but in the
21613 future, only the compiler will be considered.
21615 Consider the following example:
21617 @smallexample
21618 $ @kbd{cat number.h}
21619 typedef int number;
21620 $ @kbd{cat pi.h}
21621 const number pi = 3;
21622 $ @kbd{cat configure.ac}
21623 AC_INIT([Example], [1.0], [bug-example@@example.org])
21624 AC_CHECK_HEADERS([pi.h])
21625 $ @kbd{autoconf -Wall}
21626 $ @kbd{./configure}
21627 checking for gcc... gcc
21628 checking for C compiler default output file name... a.out
21629 checking whether the C compiler works... yes
21630 checking whether we are cross compiling... no
21631 checking for suffix of executables...
21632 checking for suffix of object files... o
21633 checking whether we are using the GNU C compiler... yes
21634 checking whether gcc accepts -g... yes
21635 checking for gcc option to accept ISO C89... none needed
21636 checking how to run the C preprocessor... gcc -E
21637 checking for grep that handles long lines and -e... grep
21638 checking for egrep... grep -E
21639 checking for ANSI C header files... yes
21640 checking for sys/types.h... yes
21641 checking for sys/stat.h... yes
21642 checking for stdlib.h... yes
21643 checking for string.h... yes
21644 checking for memory.h... yes
21645 checking for strings.h... yes
21646 checking for inttypes.h... yes
21647 checking for stdint.h... yes
21648 checking for unistd.h... yes
21649 checking pi.h usability... no
21650 checking pi.h presence... yes
21651 configure: WARNING: pi.h: present but cannot be compiled
21652 configure: WARNING: pi.h:     check for missing prerequisite headers?
21653 configure: WARNING: pi.h: see the Autoconf documentation
21654 configure: WARNING: pi.h:     section "Present But Cannot Be Compiled"
21655 configure: WARNING: pi.h: proceeding with the preprocessor's result
21656 configure: WARNING: pi.h: in the future, the compiler will take precedence
21657 configure: WARNING:     ## -------------------------------------- ##
21658 configure: WARNING:     ## Report this to bug-example@@example.org ##
21659 configure: WARNING:     ## -------------------------------------- ##
21660 checking for pi.h... yes
21661 @end smallexample
21663 @noindent
21664 The proper way the handle this case is using the fourth argument
21665 (@pxref{Generic Headers}):
21667 @example
21668 $ @kbd{cat configure.ac}
21669 AC_INIT([Example], [1.0], [bug-example@@example.org])
21670 AC_CHECK_HEADERS([number.h pi.h], [], [],
21671 [[#ifdef HAVE_NUMBER_H
21672 # include <number.h>
21673 #endif
21675 $ @kbd{autoconf -Wall}
21676 $ @kbd{./configure}
21677 checking for gcc... gcc
21678 checking for C compiler default output... a.out
21679 checking whether the C compiler works... yes
21680 checking whether we are cross compiling... no
21681 checking for suffix of executables...
21682 checking for suffix of object files... o
21683 checking whether we are using the GNU C compiler... yes
21684 checking whether gcc accepts -g... yes
21685 checking for gcc option to accept ANSI C... none needed
21686 checking for number.h... yes
21687 checking for pi.h... yes
21688 @end example
21690 See @ref{Particular Headers}, for a list of headers with their
21691 prerequisite.
21693 @c ===================================================== History of Autoconf.
21695 @node History
21696 @chapter History of Autoconf
21697 @cindex History of autoconf
21699 You may be wondering, Why was Autoconf originally written?  How did it
21700 get into its present form?  (Why does it look like gorilla spit?)  If
21701 you're not wondering, then this chapter contains no information useful
21702 to you, and you might as well skip it.  If you @emph{are} wondering,
21703 then let there be light@enddots{}
21705 @menu
21706 * Genesis::                     Prehistory and naming of @command{configure}
21707 * Exodus::                      The plagues of M4 and Perl
21708 * Leviticus::                   The priestly code of portability arrives
21709 * Numbers::                     Growth and contributors
21710 * Deuteronomy::                 Approaching the promises of easy configuration
21711 @end menu
21713 @node Genesis
21714 @section Genesis
21716 In June 1991 I was maintaining many of the @acronym{GNU} utilities for the
21717 Free Software Foundation.  As they were ported to more platforms and
21718 more programs were added, the number of @option{-D} options that users
21719 had to select in the makefile (around 20) became burdensome.
21720 Especially for me---I had to test each new release on a bunch of
21721 different systems.  So I wrote a little shell script to guess some of
21722 the correct settings for the fileutils package, and released it as part
21723 of fileutils 2.0.  That @command{configure} script worked well enough that
21724 the next month I adapted it (by hand) to create similar @command{configure}
21725 scripts for several other @acronym{GNU} utilities packages.  Brian Berliner
21726 also adapted one of my scripts for his @acronym{CVS} revision control system.
21728 Later that summer, I learned that Richard Stallman and Richard Pixley
21729 were developing similar scripts to use in the @acronym{GNU} compiler tools;
21730 so I adapted my @command{configure} scripts to support their evolving
21731 interface: using the file name @file{Makefile.in} as the templates;
21732 adding @samp{+srcdir}, the first option (of many); and creating
21733 @file{config.status} files.
21735 @node Exodus
21736 @section Exodus
21738 As I got feedback from users, I incorporated many improvements, using
21739 Emacs to search and replace, cut and paste, similar changes in each of
21740 the scripts.  As I adapted more @acronym{GNU} utilities packages to use
21741 @command{configure} scripts, updating them all by hand became impractical.
21742 Rich Murphey, the maintainer of the @acronym{GNU} graphics utilities, sent me
21743 mail saying that the @command{configure} scripts were great, and asking if
21744 I had a tool for generating them that I could send him.  No, I thought,
21745 but I should!  So I started to work out how to generate them.  And the
21746 journey from the slavery of hand-written @command{configure} scripts to the
21747 abundance and ease of Autoconf began.
21749 Cygnus @command{configure}, which was being developed at around that time,
21750 is table driven; it is meant to deal mainly with a discrete number of
21751 system types with a small number of mainly unguessable features (such as
21752 details of the object file format).  The automatic configuration system
21753 that Brian Fox had developed for Bash takes a similar approach.  For
21754 general use, it seems to me a hopeless cause to try to maintain an
21755 up-to-date database of which features each variant of each operating
21756 system has.  It's easier and more reliable to check for most features on
21757 the fly---especially on hybrid systems that people have hacked on
21758 locally or that have patches from vendors installed.
21760 I considered using an architecture similar to that of Cygnus
21761 @command{configure}, where there is a single @command{configure} script that
21762 reads pieces of @file{configure.in} when run.  But I didn't want to have
21763 to distribute all of the feature tests with every package, so I settled
21764 on having a different @command{configure} made from each
21765 @file{configure.in} by a preprocessor.  That approach also offered more
21766 control and flexibility.
21768 I looked briefly into using the Metaconfig package, by Larry Wall,
21769 Harlan Stenn, and Raphael Manfredi, but I decided not to for several
21770 reasons.  The @command{Configure} scripts it produces are interactive,
21771 which I find quite inconvenient; I didn't like the ways it checked for
21772 some features (such as library functions); I didn't know that it was
21773 still being maintained, and the @command{Configure} scripts I had
21774 seen didn't work on many modern systems (such as System V R4 and NeXT);
21775 it wasn't flexible in what it could do in response to a feature's
21776 presence or absence; I found it confusing to learn; and it was too big
21777 and complex for my needs (I didn't realize then how much Autoconf would
21778 eventually have to grow).
21780 I considered using Perl to generate my style of @command{configure}
21781 scripts, but decided that M4 was better suited to the job of simple
21782 textual substitutions: it gets in the way less, because output is
21783 implicit.  Plus, everyone already has it.  (Initially I didn't rely on
21784 the @acronym{GNU} extensions to M4.)  Also, some of my friends at the
21785 University of Maryland had recently been putting M4 front ends on
21786 several programs, including @code{tvtwm}, and I was interested in trying
21787 out a new language.
21789 @node Leviticus
21790 @section Leviticus
21792 Since my @command{configure} scripts determine the system's capabilities
21793 automatically, with no interactive user intervention, I decided to call
21794 the program that generates them Autoconfig.  But with a version number
21795 tacked on, that name would be too long for old Unix file systems,
21796 so I shortened it to Autoconf.
21798 In the fall of 1991 I called together a group of fellow questers after
21799 the Holy Grail of portability (er, that is, alpha testers) to give me
21800 feedback as I encapsulated pieces of my handwritten scripts in M4 macros
21801 and continued to add features and improve the techniques used in the
21802 checks.  Prominent among the testers were Fran@,{c}ois Pinard, who came up
21803 with the idea of making an Autoconf shell script to run M4
21804 and check for unresolved macro calls; Richard Pixley, who suggested
21805 running the compiler instead of searching the file system to find
21806 include files and symbols, for more accurate results; Karl Berry, who
21807 got Autoconf to configure @TeX{} and added the macro index to the
21808 documentation; and Ian Lance Taylor, who added support for creating a C
21809 header file as an alternative to putting @option{-D} options in a
21810 makefile, so he could use Autoconf for his @acronym{UUCP} package.
21811 The alpha testers cheerfully adjusted their files again and again as the
21812 names and calling conventions of the Autoconf macros changed from
21813 release to release.  They all contributed many specific checks, great
21814 ideas, and bug fixes.
21816 @node Numbers
21817 @section Numbers
21819 In July 1992, after months of alpha testing, I released Autoconf 1.0,
21820 and converted many @acronym{GNU} packages to use it.  I was surprised by how
21821 positive the reaction to it was.  More people started using it than I
21822 could keep track of, including people working on software that wasn't
21823 part of the @acronym{GNU} Project (such as TCL, FSP, and Kerberos V5).
21824 Autoconf continued to improve rapidly, as many people using the
21825 @command{configure} scripts reported problems they encountered.
21827 Autoconf turned out to be a good torture test for M4 implementations.
21828 Unix M4 started to dump core because of the length of the
21829 macros that Autoconf defined, and several bugs showed up in @acronym{GNU}
21830 M4 as well.  Eventually, we realized that we needed to use some
21831 features that only @acronym{GNU} M4 has.  4.3@acronym{BSD} M4, in
21832 particular, has an impoverished set of builtin macros; the System V
21833 version is better, but still doesn't provide everything we need.
21835 More development occurred as people put Autoconf under more stresses
21836 (and to uses I hadn't anticipated).  Karl Berry added checks for X11.
21837 david zuhn contributed C++ support.  Fran@,{c}ois Pinard made it diagnose
21838 invalid arguments.  Jim Blandy bravely coerced it into configuring
21839 @acronym{GNU} Emacs, laying the groundwork for several later improvements.
21840 Roland McGrath got it to configure the @acronym{GNU} C Library, wrote the
21841 @command{autoheader} script to automate the creation of C header file
21842 templates, and added a @option{--verbose} option to @command{configure}.
21843 Noah Friedman added the @option{--autoconf-dir} option and
21844 @code{AC_MACRODIR} environment variable.  (He also coined the term
21845 @dfn{autoconfiscate} to mean ``adapt a software package to use
21846 Autoconf''.)  Roland and Noah improved the quoting protection in
21847 @code{AC_DEFINE} and fixed many bugs, especially when I got sick of
21848 dealing with portability problems from February through June, 1993.
21850 @node Deuteronomy
21851 @section Deuteronomy
21853 A long wish list for major features had accumulated, and the effect of
21854 several years of patching by various people had left some residual
21855 cruft.  In April 1994, while working for Cygnus Support, I began a major
21856 revision of Autoconf.  I added most of the features of the Cygnus
21857 @command{configure} that Autoconf had lacked, largely by adapting the
21858 relevant parts of Cygnus @command{configure} with the help of david zuhn
21859 and Ken Raeburn.  These features include support for using
21860 @file{config.sub}, @file{config.guess}, @option{--host}, and
21861 @option{--target}; making links to files; and running @command{configure}
21862 scripts in subdirectories.  Adding these features enabled Ken to convert
21863 @acronym{GNU} @code{as}, and Rob Savoye to convert Deja@acronym{GNU}, to using
21864 Autoconf.
21866 I added more features in response to other peoples' requests.  Many
21867 people had asked for @command{configure} scripts to share the results of
21868 the checks between runs, because (particularly when configuring a large
21869 source tree, like Cygnus does) they were frustratingly slow.  Mike
21870 Haertel suggested adding site-specific initialization scripts.  People
21871 distributing software that had to unpack on MS-DOS asked for a way to
21872 override the @file{.in} extension on the file names, which produced file
21873 names like @file{config.h.in} containing two dots.  Jim Avera did an
21874 extensive examination of the problems with quoting in @code{AC_DEFINE}
21875 and @code{AC_SUBST}; his insights led to significant improvements.
21876 Richard Stallman asked that compiler output be sent to @file{config.log}
21877 instead of @file{/dev/null}, to help people debug the Emacs
21878 @command{configure} script.
21880 I made some other changes because of my dissatisfaction with the quality
21881 of the program.  I made the messages showing results of the checks less
21882 ambiguous, always printing a result.  I regularized the names of the
21883 macros and cleaned up coding style inconsistencies.  I added some
21884 auxiliary utilities that I had developed to help convert source code
21885 packages to use Autoconf.  With the help of Fran@,{c}ois Pinard, I made
21886 the macros not interrupt each others' messages.  (That feature revealed
21887 some performance bottlenecks in @acronym{GNU} M4, which he hastily
21888 corrected!)  I reorganized the documentation around problems people want
21889 to solve.  And I began a test suite, because experience had shown that
21890 Autoconf has a pronounced tendency to regress when we change it.
21892 Again, several alpha testers gave invaluable feedback, especially
21893 Fran@,{c}ois Pinard, Jim Meyering, Karl Berry, Rob Savoye, Ken Raeburn,
21894 and Mark Eichin.
21896 Finally, version 2.0 was ready.  And there was much rejoicing.  (And I
21897 have free time again.  I think.  Yeah, right.)
21900 @c ========================================================== Appendices
21903 @node GNU Free Documentation License
21904 @appendix GNU Free Documentation License
21906 @include fdl.texi
21908 @node Indices
21909 @appendix Indices
21911 @menu
21912 * Environment Variable Index::  Index of environment variables used
21913 * Output Variable Index::       Index of variables set in output files
21914 * Preprocessor Symbol Index::   Index of C preprocessor symbols defined
21915 * Autoconf Macro Index::        Index of Autoconf macros
21916 * M4 Macro Index::              Index of M4, M4sugar, and M4sh macros
21917 * Autotest Macro Index::        Index of Autotest macros
21918 * Program & Function Index::    Index of those with portability problems
21919 * Concept Index::               General index
21920 @end menu
21922 @node Environment Variable Index
21923 @appendixsec Environment Variable Index
21925 This is an alphabetical list of the environment variables that Autoconf
21926 checks.
21928 @printindex ev
21930 @node Output Variable Index
21931 @appendixsec Output Variable Index
21933 This is an alphabetical list of the variables that Autoconf can
21934 substitute into files that it creates, typically one or more
21935 makefiles.  @xref{Setting Output Variables}, for more information
21936 on how this is done.
21938 @printindex ov
21940 @node Preprocessor Symbol Index
21941 @appendixsec Preprocessor Symbol Index
21943 This is an alphabetical list of the C preprocessor symbols that the
21944 Autoconf macros define.  To work with Autoconf, C source code needs to
21945 use these names in @code{#if} or @code{#ifdef} directives.
21947 @printindex cv
21949 @node Autoconf Macro Index
21950 @appendixsec Autoconf Macro Index
21952 This is an alphabetical list of the Autoconf macros.
21953 @ifset shortindexflag
21954 To make the list easier to use, the macros are listed without their
21955 preceding @samp{AC_}.
21956 @end ifset
21958 @printindex AC
21960 @node M4 Macro Index
21961 @appendixsec M4 Macro Index
21963 This is an alphabetical list of the M4, M4sugar, and M4sh macros.
21964 @ifset shortindexflag
21965 To make the list easier to use, the macros are listed without their
21966 preceding @samp{m4_} or @samp{AS_}.
21967 @end ifset
21969 @printindex MS
21971 @node Autotest Macro Index
21972 @appendixsec Autotest Macro Index
21974 This is an alphabetical list of the Autotest macros.
21975 @ifset shortindexflag
21976 To make the list easier to use, the macros are listed without their
21977 preceding @samp{AT_}.
21978 @end ifset
21980 @printindex AT
21982 @node Program & Function Index
21983 @appendixsec Program and Function Index
21985 This is an alphabetical list of the programs and functions whose
21986 portability is discussed in this document.
21988 @printindex pr
21990 @node Concept Index
21991 @appendixsec Concept Index
21993 This is an alphabetical list of the files, tools, and concepts
21994 introduced in this document.
21996 @printindex cp
21998 @bye
22000 @c  LocalWords:  texinfo setfilename autoconf texi settitle setchapternewpage
22001 @c  LocalWords:  setcontentsaftertitlepage finalout ARG ovar varname dvar acx
22002 @c  LocalWords:  makeinfo dvi defcodeindex ev ov CPP cv Autotest mv defindex fn
22003 @c  LocalWords:  shortindexflag iftex ifset acindex ACindex ifclear ahindex fu
22004 @c  LocalWords:  asindex MSindex atindex ATindex auindex hdrindex prindex FIXME
22005 @c  LocalWords:  msindex alloca fnindex Aaarg indices FSF's dircategory ifnames
22006 @c  LocalWords:  direntry autoscan autoreconf autoheader autoupdate config FDs
22007 @c  LocalWords:  testsuite titlepage Elliston Demaille vskip filll ifnottex hmm
22008 @c  LocalWords:  insertcopying Autoconf's detailmenu Automake Libtool Posix ois
22009 @c  LocalWords:  Systemology Checkpointing Changequote INTERCAL changequote dfn
22010 @c  LocalWords:  Quadrigraphs builtins Shellology acconfig Bugward LIBOBJ Imake
22011 @c  LocalWords:  LIBOBJS IFELSE cindex flushright Pinard Metaconfig uref Simons
22012 @c  LocalWords:  distclean uninstall noindent versioning Tromey dir
22013 @c  LocalWords:  SAMS samp aclocal acsite underquoted emph itemx prepend SUBST
22014 @c  LocalWords:  evindex automake Gettext autopoint gettext symlink libtoolize
22015 @c  LocalWords:  defmac INIT tarname ovindex cvindex BUGREPORT PREREQ asis PROG
22016 @c  LocalWords:  SRCDIR srcdir globbing afterwards cmds foos fooo foooo init cd
22017 @c  LocalWords:  builddir timestamp src Imakefile chmod defvar CFLAGS CPPFLAGS
22018 @c  LocalWords:  CXXFLAGS DEFS DHAVE defvarx FCFLAGS FFLAGS LDFLAGS bindir GCC
22019 @c  LocalWords:  datadir datarootdir docdir dvidir htmldir libdir ifnothtml kbd
22020 @c  LocalWords:  includedir infodir libexecdir localedir localstatedir mandir
22021 @c  LocalWords:  oldincludedir pdfdir PDF psdir PostScript sbindir sysconfdir
22022 @c  LocalWords:  sharedstatedir DDATADIR sed tmp pkgdatadir VPATH conf unistd
22023 @c  LocalWords:  undef endif builtin FUNCS ifndef STACKSEG getb GETB YMP fubar
22024 @c  LocalWords:  PRE dest SUBDIRS subdirs fi struct STDC stdlib stddef INTTYPES
22025 @c  LocalWords:  inttypes STDINT stdint AWK AIX Solaris NeXT env EGREP FGREP yy
22026 @c  LocalWords:  LEXLIB YYTEXT lfl nonportable Automake's LN RANLIB byacc INETD
22027 @c  LocalWords:  inetd prog PROGS progs ranlib lmp lXt lX nsl gethostbyname UX
22028 @c  LocalWords:  NextStep isinf isnan glibc IRIX sunmath lm lsunmath pre sizeof
22029 @c  LocalWords:  ld inline malloc putenv setenv FreeBSD realloc SunOS MinGW
22030 @c  LocalWords:  snprintf vsnprintf sprintf vsprintf sscanf gcc strerror ifdef
22031 @c  LocalWords:  strnlen sysconf PAGESIZE unsetenv va fallback memcpy dst FUNC
22032 @c  LocalWords:  PowerPC GNUC libPW pragma Olibcalls CHOWN chown CLOSEDIR VFORK
22033 @c  LocalWords:  closedir FNMATCH fnmatch vfork FSEEKO LARGEFILE fseeko SVR sc
22034 @c  LocalWords:  largefile GETGROUPS getgroups GETLOADAVG DGUX UMAX NLIST KMEM
22035 @c  LocalWords:  SETGID getloadavg nlist GETMNTENT irix
22036 @c  LocalWords:  getmntent UnixWare GETPGRP getpgid getpgrp Posix's pid LSTAT
22037 @c  LocalWords:  lstat rpl MEMCMP memcmp OpenStep MBRTOWC mbrtowc MKTIME mktime
22038 @c  LocalWords:  localtime MMAP mmap OBSTACK obstack obstacks ARGTYPES timeval
22039 @c  LocalWords:  SETPGRP setpgrp defmacx Hurd SETVBUF setvbuf STRCOLL strcoll
22040 @c  LocalWords:  STRTOD strtod DECL STRFTIME strftime SCO UTIME utime VPRINTF
22041 @c  LocalWords:  DOPRNT vprintf doprnt sp unfixable LIBSOURCE LIBSOURCES Eggert
22042 @c  LocalWords:  linux netinet ia Tru XFree DIRENT NDIR dirent ndir multitable
22043 @c  LocalWords:  NAMLEN strlen namlen MKDEV SYSMACROS makedev RESOLV resolv DNS
22044 @c  LocalWords:  inet structs NAMESER arpa NETDB netdb UTekV UTS GCC's kB
22045 @c  LocalWords:  STDBOOL BOOL stdbool conformant cplusplus bool Bool stdarg tm
22046 @c  LocalWords:  ctype strchr strrchr rindex bcopy memmove memchr WEXITSTATUS
22047 @c  LocalWords:  WIFEXITED TIOCGWINSZ GWINSZ termios preprocess preprocessable
22048 @c  LocalWords:  DECLS strdup calloc BLKSIZE blksize RDEV rdev TZNAME tzname pw
22049 @c  LocalWords:  passwd gecos pwd MBSTATE mbstate wchar RETSIGTYPE hup UID uid
22050 @c  LocalWords:  gid ptrdiff uintmax EXEEXT OBJEXT Ae conftest AXP str
22051 @c  LocalWords:  ALIGNOF WERROR Werror cpp HP's WorkShop egcs un fied stdc CXX
22052 @c  LocalWords:  varargs BIGENDIAN Endianness SPARC endianness grep'ed CONST FC
22053 @c  LocalWords:  const STRINGIZE stringizing PARAMS unprotoize protos KCC cxx
22054 @c  LocalWords:  xlC aCC CXXCPP FREEFORM xlf FLIBS FCLIBS ish SRCEXT XTRA LFS
22055 @c  LocalWords:  ISC lcposix MINIX Minix conditionalized inlines hw dD confdefs
22056 @c  LocalWords:  fputs stdout PREPROC ar UFS HFS QNX realtime fstype STATVFS se
22057 @c  LocalWords:  statvfs STATFS statfs func machfile hdr lelf raboof DEFUN GTK
22058 @c  LocalWords:  GTKMM Grmph ified ine defn baz EOF qar Ahhh changecom algol io
22059 @c  LocalWords:  changeword quadrigraphs quadrigraph dnl SGI atoi overquoting
22060 @c  LocalWords:  Aas Wcross sep args namespace undefine bpatsubst popdef dquote
22061 @c  LocalWords:  bregexp Overquote overquotation meisch maisch meische maische
22062 @c  LocalWords:  miscian DIRNAME dirname MKDIR CATFILE XMKMF TRAVOLTA celsius
22063 @c  LocalWords:  EMX emxos Emacsen Korn DYNIX subshell posix Ksh ksh Pdksh Zsh
22064 @c  LocalWords:  pdksh zsh Allbery Lipe Kubota UWS zorglub stderr eval esac lfn
22065 @c  LocalWords:  drivespec Posixy DJGPP doschk prettybird LPT pfew Zsh's yu yaa
22066 @c  LocalWords:  yM uM aM firebird IP subdir misparses ok Unpatched abc bc zA
22067 @c  LocalWords:  CDPATH DUALCASE LINENO prepass Subshells lineno NULLCMD cmp wc
22068 @c  LocalWords:  MAILPATH scanset arg NetBSD Almquist printf expr cp
22069 @c  LocalWords:  Oliva awk Aaaaarg cmd regex xfoo GNV OpenVMS VM
22070 @c  LocalWords:  sparc Proulx nbar nfoo maxdepth acdilrtu TWG mc
22071 @c  LocalWords:  mkdir exe uname OpenBSD Fileutils mktemp umask TMPDIR guid os
22072 @c  LocalWords:  fooXXXXXX Unicos utimes hpux hppa unescaped
22073 @c  LocalWords:  pmake DOS's gmake ifoo DESTDIR autoconfiscated pc coff mips gg
22074 @c  LocalWords:  dec ultrix cpu wildcards rpcc rdtsc powerpc readline
22075 @c  LocalWords:  withval vxworks gless localcache usr LOFF loff CYGWIN Cygwin
22076 @c  LocalWords:  cygwin SIGLIST siglist SYSNDIR SYSDIR ptx lseq rusage elif MSC
22077 @c  LocalWords:  lfoo POUNDBANG lsun NIS getpwnam SYSCALLS RSH INTL lintl aix
22078 @c  LocalWords:  intl lx ldir syslog bsd EPI toolchain netbsd objext de KNR nn
22079 @c  LocalWords:  fication LTLIBOBJS Wdiff TESTDIR atconfig atlocal akim XFAIL
22080 @c  LocalWords:  ChangeLog prepended errexit smallexample TESTSUITEFLAGS GPL er
22081 @c  LocalWords:  installcheck autotest indir Pixley Bothner Eichin Kerberos adl
22082 @c  LocalWords:  DISTCLEANFILES preprocessor's fileutils Stallman Murphey Stenn
22083 @c  LocalWords:  Manfredi Autoconfig TCL FSP david zuhn Blandy MACRODIR Raeburn
22084 @c  LocalWords:  autoconfiscate Savoye Haertel Avera Meyering fdl appendixsec
22085 @c  LocalWords:  printindex american LIBOBJDIR LibdirTest ERLCFLAGS OBJCFLAGS
22086 @c  LocalWords:  VER Gnulib online xyes strcpy TYPEOF typeof OBJC objcc objc ln
22087 @c  LocalWords:  GOBJC OTP ERLC erl valloc decr dumpdef errprint incr
22088 @c  LocalWords:  esyscmd len maketemp pushdef substr syscmd sysval translit txt
22089 @c  LocalWords:  sinclude foreach myvar tolower toupper uniq BASENAME STDIN
22090 @c  LocalWords:  Dynix descrips basename aname cname macroexpands xno xcheck
22091 @c  LocalWords:  LIBREADLINE lreadline lncurses libreadline
22093 @c Local Variables:
22094 @c fill-column: 72
22095 @c ispell-local-dictionary: "american"
22096 @c indent-tabs-mode: nil
22097 @c whitespace-check-buffer-indent: nil
22098 @c End: