Document pdksh exec behavior.
[autoconf.git] / doc / autoconf.texi
blob554d2ec86e34fb25f18a5f9c7b4f2415f5665eca
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, DEFAULT)
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{]}
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{]}
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 is for @acronym{GNU} Autoconf
181 (version @value{VERSION}, @value{UPDATED}),
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 * Writing Autoconf Macros::     Adding new macros to Autoconf
264 * Portable Shell::              Shell script portability pitfalls
265 * Portable Make::               Makefile portability pitfalls
266 * Portable C and C++::          C and C++ portability pitfalls
267 * Manual Configuration::        Selecting features that can't be guessed
268 * Site Configuration::          Local defaults for @command{configure}
269 * Running configure Scripts::   How to use the Autoconf output
270 * config.status Invocation::    Recreating a configuration
271 * Obsolete Constructs::         Kept for backward compatibility
272 * Using Autotest::              Creating portable test suites
273 * FAQ::                         Frequent Autoconf Questions, with answers
274 * History::                     History of Autoconf
275 * GNU Free Documentation License::  License for copying this manual
276 * Indices::                     Indices of symbols, concepts, etc.
278 @detailmenu
279  --- The Detailed Node Listing ---
281 The @acronym{GNU} Build System
283 * Automake::                    Escaping makefile hell
284 * Gnulib::                      The @acronym{GNU} portability library
285 * Libtool::                     Building libraries portably
286 * Pointers::                    More info on the @acronym{GNU} build system
288 Making @command{configure} Scripts
290 * Writing Autoconf Input::      What to put in an Autoconf input file
291 * autoscan Invocation::         Semi-automatic @file{configure.ac} writing
292 * ifnames Invocation::          Listing the conditionals in source code
293 * autoconf Invocation::         How to create configuration scripts
294 * autoreconf Invocation::       Remaking multiple @command{configure} scripts
296 Writing @file{configure.ac}
298 * Shell Script Compiler::       Autoconf as solution of a problem
299 * Autoconf Language::           Programming in Autoconf
300 * Autoconf Input Layout::       Standard organization of @file{configure.ac}
302 Initialization and Output Files
304 * Initializing configure::      Option processing etc.
305 * Versioning::                  Dealing with Autoconf versions
306 * Notices::                     Copyright, version numbers in @command{configure}
307 * Input::                       Where Autoconf should find files
308 * Output::                      Outputting results from the configuration
309 * Configuration Actions::       Preparing the output based on results
310 * Configuration Files::         Creating output files
311 * Makefile Substitutions::      Using output variables in makefiles
312 * Configuration Headers::       Creating a configuration header file
313 * Configuration Commands::      Running arbitrary instantiation commands
314 * Configuration Links::         Links depending on the configuration
315 * Subdirectories::              Configuring independent packages together
316 * Default Prefix::              Changing the default installation prefix
318 Substitutions in Makefiles
320 * Preset Output Variables::     Output variables that are always set
321 * Installation Directory Variables::  Other preset output variables
322 * Changed Directory Variables:: Warnings about @file{datarootdir}
323 * Build Directories::           Supporting multiple concurrent compiles
324 * Automatic Remaking::          Makefile rules for configuring
326 Configuration Header Files
328 * Header Templates::            Input for the configuration headers
329 * autoheader Invocation::       How to create configuration templates
330 * Autoheader Macros::           How to specify CPP templates
332 Existing Tests
334 * Common Behavior::             Macros' standard schemes
335 * Alternative Programs::        Selecting between alternative programs
336 * Files::                       Checking for the existence of files
337 * Libraries::                   Library archives that might be missing
338 * Library Functions::           C library functions that might be missing
339 * Header Files::                Header files that might be missing
340 * Declarations::                Declarations that may be missing
341 * Structures::                  Structures or members that might be missing
342 * Types::                       Types that might be missing
343 * Compilers and Preprocessors::  Checking for compiling programs
344 * System Services::             Operating system services
345 * Posix Variants::              Special kludges for specific Posix variants
346 * Erlang Libraries::            Checking for the existence of Erlang libraries
348 Common Behavior
350 * Standard Symbols::            Symbols defined by the macros
351 * Default Includes::            Includes used by the generic macros
353 Alternative Programs
355 * Particular Programs::         Special handling to find certain programs
356 * Generic Programs::            How to find other programs
358 Library Functions
360 * Function Portability::        Pitfalls with usual functions
361 * Particular Functions::        Special handling to find certain functions
362 * Generic Functions::           How to find other functions
364 Header Files
366 * Header Portability::          Collected knowledge on common headers
367 * Particular Headers::          Special handling to find certain headers
368 * Generic Headers::             How to find other headers
370 Declarations
372 * Particular Declarations::     Macros to check for certain declarations
373 * Generic Declarations::        How to find other declarations
375 Structures
377 * Particular Structures::       Macros to check for certain structure members
378 * Generic Structures::          How to find other structure members
380 Types
382 * Particular Types::            Special handling to find certain types
383 * Generic Types::               How to find other types
385 Compilers and Preprocessors
387 * Specific Compiler Characteristics::  Some portability issues
388 * Generic Compiler Characteristics::  Language independent tests and features
389 * C Compiler::                  Checking its characteristics
390 * C++ Compiler::                Likewise
391 * Objective C Compiler::        Likewise
392 * Erlang Compiler and Interpreter::  Likewise
393 * Fortran Compiler::            Likewise
395 Writing Tests
397 * Language Choice::             Selecting which language to use for testing
398 * Writing Test Programs::       Forging source files for compilers
399 * Running the Preprocessor::    Detecting preprocessor symbols
400 * Running the Compiler::        Detecting language or header features
401 * Running the Linker::          Detecting library features
402 * Runtime::                     Testing for runtime features
403 * Systemology::                 A zoology of operating systems
404 * Multiple Cases::              Tests for several possible values
406 Writing Test Programs
408 * Guidelines::                  General rules for writing test programs
409 * Test Functions::              Avoiding pitfalls in test programs
410 * Generating Sources::          Source program boilerplate
412 Results of Tests
414 * Defining Symbols::            Defining C preprocessor symbols
415 * Setting Output Variables::    Replacing variables in output files
416 * Special Chars in Variables::  Characters to beware of in variables
417 * Caching Results::             Speeding up subsequent @command{configure} runs
418 * Printing Messages::           Notifying @command{configure} users
420 Caching Results
422 * Cache Variable Names::        Shell variables used in caches
423 * Cache Files::                 Files @command{configure} uses for caching
424 * Cache Checkpointing::         Loading and saving the cache file
426 Programming in M4
428 * M4 Quotation::                Protecting macros from unwanted expansion
429 * Using autom4te::              The Autoconf executables backbone
430 * Programming in M4sugar::      Convenient pure M4 macros
431 * Programming in M4sh::         Common shell Constructs
432 * File Descriptor Macros::      File descriptor macros for input and output
434 M4 Quotation
436 * Active Characters::           Characters that change the behavior of M4
437 * One Macro Call::              Quotation and one macro call
438 * Quoting and Parameters::      M4 vs. shell parameters
439 * Quotation and Nested Macros::  Macros calling macros
440 * Changequote is Evil::         Worse than INTERCAL: M4 + changequote
441 * Quadrigraphs::                Another way to escape special characters
442 * Quotation Rule Of Thumb::     One parenthesis, one quote
444 Using @command{autom4te}
446 * autom4te Invocation::         A @acronym{GNU} M4 wrapper
447 * Customizing autom4te::        Customizing the Autoconf package
449 Programming in M4sugar
451 * Redefined M4 Macros::         M4 builtins changed in M4sugar
452 * Diagnostic Macros::           Diagnostic messages from M4sugar
453 * Diversion support::           Diversions in M4sugar
454 * Conditional constructs::      Conditions in M4
455 * Looping constructs::          Iteration in M4
456 * Evaluation Macros::           More quotation and evaluation control
457 * Text processing Macros::      String manipulation in M4
458 * Number processing Macros::    Arithmetic computation in M4
459 * Forbidden Patterns::          Catching unexpanded macros
461 Writing Autoconf Macros
463 * Macro Definitions::           Basic format of an Autoconf macro
464 * Macro Names::                 What to call your new macros
465 * Reporting Messages::          Notifying @command{autoconf} users
466 * Dependencies Between Macros::  What to do when macros depend on other macros
467 * Obsoleting Macros::           Warning about old ways of doing things
468 * Coding Style::                Writing Autoconf macros @`a la Autoconf
470 Dependencies Between Macros
472 * Prerequisite Macros::         Ensuring required information
473 * Suggested Ordering::          Warning about possible ordering problems
474 * One-Shot Macros::             Ensuring a macro is called only once
476 Portable Shell Programming
478 * Shellology::                  A zoology of shells
479 * Here-Documents::              Quirks and tricks
480 * File Descriptors::            FDs and redirections
481 * File System Conventions::     File names
482 * Shell Pattern Matching::      Pattern matching
483 * Shell Substitutions::         Variable and command expansions
484 * Assignments::                 Varying side effects of assignments
485 * Parentheses::                 Parentheses in shell scripts
486 * Slashes::                     Slashes in shell scripts
487 * Special Shell Variables::     Variables you should not change
488 * Shell Functions::             What to look out for if you use them
489 * Limitations of Builtins::     Portable use of not so portable /bin/sh
490 * Limitations of Usual Tools::  Portable use of portable tools
492 Portable Make Programming
494 * $< in Ordinary Make Rules::   $< in ordinary rules
495 * Failure in Make Rules::       Failing portably in rules
496 * Special Chars in Names::      Special Characters in Macro Names
497 * Backslash-Newline-Newline::   Empty last lines in macro definitions
498 * Backslash-Newline Comments::  Spanning comments across line boundaries
499 * Long Lines in Makefiles::     Line length limitations
500 * Macros and Submakes::         @code{make macro=value} and submakes
501 * The Make Macro MAKEFLAGS::    @code{$(MAKEFLAGS)} portability issues
502 * The Make Macro SHELL::        @code{$(SHELL)} portability issues
503 * Comments in Make Rules::      Other problems with Make comments
504 * obj/ and Make::               Don't name a subdirectory @file{obj}
505 * make -k Status::              Exit status of @samp{make -k}
506 * VPATH and Make::              @code{VPATH} woes
507 * Single Suffix Rules::         Single suffix rules and separated dependencies
508 * Timestamps and Make::         Subsecond timestamp resolution
510 @code{VPATH} and Make
512 * VPATH and Double-colon::      Problems with @samp{::} on ancient hosts
513 * $< in Explicit Rules::        @code{$<} does not work in ordinary rules
514 * Automatic Rule Rewriting::    @code{VPATH} goes wild on Solaris
515 * Tru64 Directory Magic::       @command{mkdir} goes wild on Tru64
516 * Make Target Lookup::          More details about @code{VPATH} lookup
518 Portable C and C++ Programming
520 * Varieties of Unportability::  How to make your programs unportable
521 * Integer Overflow::            When integers get too large
522 * Preprocessor Arithmetic::     @code{#if} expression problems
523 * Null Pointers::               Properties of null pointers
524 * Buffer Overruns::             Subscript errors and the like
525 * Volatile Objects::            @code{volatile} and signals
526 * Floating Point Portability::  Portable floating-point arithmetic
527 * Exiting Portably::            Exiting and the exit status
529 Manual Configuration
531 * Specifying Names::            Specifying the system type
532 * Canonicalizing::              Getting the canonical system type
533 * Using System Type::           What to do with the system type
535 Site Configuration
537 * Help Formatting::             Customizing @samp{configure --help}
538 * External Software::           Working with other optional software
539 * Package Options::             Selecting optional features
540 * Pretty Help Strings::         Formatting help string
541 * Option Checking::             Controlling checking of @command{configure} options
542 * Site Details::                Configuring site details
543 * Transforming Names::          Changing program names when installing
544 * Site Defaults::               Giving @command{configure} local defaults
546 Transforming Program Names When Installing
548 * Transformation Options::      @command{configure} options to transform names
549 * Transformation Examples::     Sample uses of transforming names
550 * Transformation Rules::        Makefile uses of transforming names
552 Running @command{configure} Scripts
554 * Basic Installation::          Instructions for typical cases
555 * Compilers and Options::       Selecting compilers and optimization
556 * Multiple Architectures::      Compiling for multiple architectures at once
557 * Installation Names::          Installing in different directories
558 * Optional Features::           Selecting optional features
559 * System Type::                 Specifying the system type
560 * Sharing Defaults::            Setting site-wide defaults for @command{configure}
561 * Defining Variables::          Specifying the compiler etc.
562 * configure Invocation::        Changing how @command{configure} runs
564 Obsolete Constructs
566 * Obsolete config.status Use::  Obsolete convention for @command{config.status}
567 * acconfig Header::             Additional entries in @file{config.h.in}
568 * autoupdate Invocation::       Automatic update of @file{configure.ac}
569 * Obsolete Macros::             Backward compatibility macros
570 * Autoconf 1::                  Tips for upgrading your files
571 * Autoconf 2.13::               Some fresher tips
573 Upgrading From Version 1
575 * Changed File Names::          Files you might rename
576 * Changed Makefiles::           New things to put in @file{Makefile.in}
577 * Changed Macros::              Macro calls you might replace
578 * Changed Results::             Changes in how to check test results
579 * Changed Macro Writing::       Better ways to write your own macros
581 Upgrading From Version 2.13
583 * Changed Quotation::           Broken code which used to work
584 * New Macros::                  Interaction with foreign macros
585 * Hosts and Cross-Compilation::  Bugward compatibility kludges
586 * AC_LIBOBJ vs LIBOBJS::        LIBOBJS is a forbidden token
587 * AC_FOO_IFELSE vs AC_TRY_FOO::  A more generic scheme for testing sources
589 Generating Test Suites with Autotest
591 * Using an Autotest Test Suite::  Autotest and the user
592 * Writing Testsuites::          Autotest macros
593 * testsuite Invocation::        Running @command{testsuite} scripts
594 * Making testsuite Scripts::    Using autom4te to create @command{testsuite}
596 Using an Autotest Test Suite
598 * testsuite Scripts::           The concepts of Autotest
599 * Autotest Logs::               Their contents
601 Frequent Autoconf Questions, with answers
603 * Distributing::                Distributing @command{configure} scripts
604 * Why GNU M4::                  Why not use the standard M4?
605 * Bootstrapping::               Autoconf and @acronym{GNU} M4 require each other?
606 * Why Not Imake::               Why @acronym{GNU} uses @command{configure} instead of Imake
607 * Defining Directories::        Passing @code{datadir} to program
608 * Autom4te Cache::              What is it?  Can I remove it?
609 * Present But Cannot Be Compiled::  Compiler and Preprocessor Disagree
611 History of Autoconf
613 * Genesis::                     Prehistory and naming of @command{configure}
614 * Exodus::                      The plagues of M4 and Perl
615 * Leviticus::                   The priestly code of portability arrives
616 * Numbers::                     Growth and contributors
617 * Deuteronomy::                 Approaching the promises of easy configuration
619 Indices
621 * Environment Variable Index::  Index of environment variables used
622 * Output Variable Index::       Index of variables set in output files
623 * Preprocessor Symbol Index::   Index of C preprocessor symbols defined
624 * Autoconf Macro Index::        Index of Autoconf macros
625 * M4 Macro Index::              Index of M4, M4sugar, and M4sh macros
626 * Autotest Macro Index::        Index of Autotest macros
627 * Program & Function Index::    Index of those with portability problems
628 * Concept Index::               General index
630 @end detailmenu
631 @end menu
633 @c ============================================================= Introduction.
635 @node Introduction
636 @chapter Introduction
637 @cindex Introduction
639 @flushright
640 A physicist, an engineer, and a computer scientist were discussing the
641 nature of God.  ``Surely a Physicist,'' said the physicist, ``because
642 early in the Creation, God made Light; and you know, Maxwell's
643 equations, the dual nature of electromagnetic waves, the relativistic
644 consequences@dots{}'' ``An Engineer!,'' said the engineer, ``because
645 before making Light, God split the Chaos into Land and Water; it takes a
646 hell of an engineer to handle that big amount of mud, and orderly
647 separation of solids from liquids@dots{}'' The computer scientist
648 shouted: ``And the Chaos, where do you think it was coming from, hmm?''
650 ---Anonymous
651 @end flushright
652 @c (via Franc,ois Pinard)
654 Autoconf is a tool for producing shell scripts that automatically
655 configure software source code packages to adapt to many kinds of
656 Posix-like systems.  The configuration scripts produced by Autoconf
657 are independent of Autoconf when they are run, so their users do not
658 need to have Autoconf.
660 The configuration scripts produced by Autoconf require no manual user
661 intervention when run; they do not normally even need an argument
662 specifying the system type.  Instead, they individually test for the
663 presence of each feature that the software package they are for might need.
664 (Before each check, they print a one-line message stating what they are
665 checking for, so the user doesn't get too bored while waiting for the
666 script to finish.)  As a result, they deal well with systems that are
667 hybrids or customized from the more common Posix variants.  There is
668 no need to maintain files that list the features supported by each
669 release of each variant of Posix.
671 For each software package that Autoconf is used with, it creates a
672 configuration script from a template file that lists the system features
673 that the package needs or can use.  After the shell code to recognize
674 and respond to a system feature has been written, Autoconf allows it to
675 be shared by many software packages that can use (or need) that feature.
676 If it later turns out that the shell code needs adjustment for some
677 reason, it needs to be changed in only one place; all of the
678 configuration scripts can be regenerated automatically to take advantage
679 of the updated code.
681 @c "Those who do not understand Unix are condemned to reinvent it, poorly."
682 @c --Henry Spencer, 1987 (see http://en.wikipedia.org/wiki/Unix_philosophy)
683 Those who do not understand Autoconf are condemned to reinvent it, poorly.
684 The primary goal of Autoconf is making the @emph{user's} life easier;
685 making the @emph{maintainer's} life easier is only a secondary goal.
686 Put another way, the primary goal is not to make the generation of
687 @file{configure} automatic for package maintainers (although patches
688 along that front are welcome, since package maintainers form the user
689 base of Autoconf); rather, the goal is to make @file{configure}
690 painless, portable, and predictable for the end user of each
691 @dfn{autoconfiscated} package.  And to this degree, Autoconf is highly
692 successful at its goal --- most complaints to the Autoconf list are
693 about difficulties in writing Autoconf input, and not in the behavior of
694 the resulting @file{configure}.  Even packages that don't use Autoconf
695 will generally provide a @file{configure} script, and the most common
696 complaint about these alternative home-grown scripts is that they fail
697 to meet one or more of the @acronym{GNU} Coding Standards that users
698 have come to expect from Autoconf-generated @file{configure} scripts.
700 The Metaconfig package is similar in purpose to Autoconf, but the
701 scripts it produces require manual user intervention, which is quite
702 inconvenient when configuring large source trees.  Unlike Metaconfig
703 scripts, Autoconf scripts can support cross-compiling, if some care is
704 taken in writing them.
706 Autoconf does not solve all problems related to making portable
707 software packages---for a more complete solution, it should be used in
708 concert with other @acronym{GNU} build tools like Automake and
709 Libtool.  These other tools take on jobs like the creation of a
710 portable, recursive makefile with all of the standard targets,
711 linking of shared libraries, and so on.  @xref{The GNU Build System},
712 for more information.
714 Autoconf imposes some restrictions on the names of macros used with
715 @code{#if} in C programs (@pxref{Preprocessor Symbol Index}).
717 Autoconf requires @acronym{GNU} M4 version 1.4.5 or later in order to
718 generate the scripts.  It uses features that some versions of M4,
719 including @acronym{GNU} M4 1.3, do not have.  Autoconf works better
720 with @acronym{GNU} M4 version 1.4.11 or later, though this is not
721 required.
723 @xref{Autoconf 1}, for information about upgrading from version 1.
724 @xref{History}, for the story of Autoconf's development.  @xref{FAQ},
725 for answers to some common questions about Autoconf.
727 See the @uref{http://www.gnu.org/software/autoconf/,
728 Autoconf web page} for up-to-date information, details on the mailing
729 lists, pointers to a list of known bugs, etc.
731 Mail suggestions to @email{autoconf@@gnu.org, the Autoconf mailing
732 list}.  Past suggestions are
733 @uref{http://lists.gnu.org/archive/html/autoconf/, archived}.
735 Mail bug reports to @email{bug-autoconf@@gnu.org, the
736 Autoconf Bugs mailing list}.  Past bug reports are
737 @uref{http://lists.gnu.org/archive/html/bug-autoconf/, archived}.
739 If possible, first check that your bug is
740 not already solved in current development versions, and that it has not
741 been reported yet.  Be sure to include all the needed information and a
742 short @file{configure.ac} that demonstrates the problem.
744 Autoconf's development tree is accessible via @command{git}; see the
745 @uref{http://savannah.gnu.org/projects/autoconf/, Autoconf
746 Summary} for details, or view
747 @uref{http://git.sv.gnu.org/gitweb/?p=autoconf.git, the actual
748 repository}.  Anonymous @acronym{CVS} access is also available, see
749 @file{README} for more details.  Patches relative to the
750 current @command{git} version can be sent for review to the
751 @email{autoconf-patches@@gnu.org, Autoconf Patches mailing list}.
752 Discussions on past patches are
753 @uref{http://lists.gnu.org/@/archive/@/html/@/autoconf-patches/,
754 archived}, and all commits are archived in the read-only
755 @email{autoconf-commit@@gnu.org, Autoconf Commit mailing list}, which is
756 also @uref{http://lists.gnu.org/@/archive/@/html/@/autoconf-commit/,
757 archived}.
759 Because of its mission, the Autoconf package itself
760 includes only a set of often-used
761 macros that have already demonstrated their usefulness.  Nevertheless,
762 if you wish to share your macros, or find existing ones, see the
763 @uref{http://autoconf-archive.cryp.to/, Autoconf Macro
764 Archive}, which is kindly run by @email{simons@@cryp.to,
765 Peter Simons}.
768 @c ================================================= The GNU Build System
770 @node The GNU Build System
771 @chapter The @acronym{GNU} Build System
772 @cindex @acronym{GNU} build system
774 Autoconf solves an important problem---reliable discovery of
775 system-specific build and runtime information---but this is only one
776 piece of the puzzle for the development of portable software.  To this
777 end, the @acronym{GNU} project has developed a suite of integrated
778 utilities to finish the job Autoconf started: the @acronym{GNU} build
779 system, whose most important components are Autoconf, Automake, and
780 Libtool.  In this chapter, we introduce you to those tools, point you
781 to sources of more information, and try to convince you to use the
782 entire @acronym{GNU} build system for your software.
784 @menu
785 * Automake::                    Escaping makefile hell
786 * Gnulib::                      The @acronym{GNU} portability library
787 * Libtool::                     Building libraries portably
788 * Pointers::                    More info on the @acronym{GNU} build system
789 @end menu
791 @node Automake
792 @section Automake
794 The ubiquity of @command{make} means that a makefile is almost the
795 only viable way to distribute automatic build rules for software, but
796 one quickly runs into its numerous limitations.  Its lack of
797 support for automatic dependency tracking, recursive builds in
798 subdirectories, reliable timestamps (e.g., for network file systems), and
799 so on, mean that developers must painfully (and often incorrectly)
800 reinvent the wheel for each project.  Portability is non-trivial, thanks
801 to the quirks of @command{make} on many systems.  On top of all this is the
802 manual labor required to implement the many standard targets that users
803 have come to expect (@code{make install}, @code{make distclean},
804 @code{make uninstall}, etc.).  Since you are, of course, using Autoconf,
805 you also have to insert repetitive code in your @code{Makefile.in} to
806 recognize @code{@@CC@@}, @code{@@CFLAGS@@}, and other substitutions
807 provided by @command{configure}.  Into this mess steps @dfn{Automake}.
808 @cindex Automake
810 Automake allows you to specify your build needs in a @code{Makefile.am}
811 file with a vastly simpler and more powerful syntax than that of a plain
812 makefile, and then generates a portable @code{Makefile.in} for
813 use with Autoconf.  For example, the @code{Makefile.am} to build and
814 install a simple ``Hello world'' program might look like:
816 @example
817 bin_PROGRAMS = hello
818 hello_SOURCES = hello.c
819 @end example
821 @noindent
822 The resulting @code{Makefile.in} (~400 lines) automatically supports all
823 the standard targets, the substitutions provided by Autoconf, automatic
824 dependency tracking, @code{VPATH} building, and so on.  @command{make}
825 builds the @code{hello} program, and @code{make install} installs it
826 in @file{/usr/local/bin} (or whatever prefix was given to
827 @command{configure}, if not @file{/usr/local}).
829 The benefits of Automake increase for larger packages (especially ones
830 with subdirectories), but even for small programs the added convenience
831 and portability can be substantial.  And that's not all@enddots{}
833 @node Gnulib
834 @section Gnulib
836 @acronym{GNU} software has a well-deserved reputation for running on
837 many different types of systems.  While our primary goal is to write
838 software for the @acronym{GNU} system, many users and developers have
839 been introduced to us through the systems that they were already using.
841 @cindex Gnulib
842 Gnulib is a central location for common @acronym{GNU} code, intended to
843 be shared among free software packages.  Its components are typically
844 shared at the source level, rather than being a library that gets built,
845 installed, and linked against.  The idea is to copy files from Gnulib
846 into your own source tree.  There is no distribution tarball; developers
847 should just grab source modules from the repository.  The source files
848 are available online, under various licenses, mostly @acronym{GNU}
849 @acronym{GPL} or @acronym{GNU} @acronym{LGPL}.
851 Gnulib modules typically contain C source code along with Autoconf
852 macros used to configure the source code.  For example, the Gnulib
853 @code{stdbool} module implements a @file{stdbool.h} header that nearly
854 conforms to C99, even on old-fashioned hosts that lack @file{stdbool.h}.
855 This module contains a source file for the replacement header, along
856 with an Autoconf macro that arranges to use the replacement header on
857 old-fashioned systems.
859 @node Libtool
860 @section Libtool
862 Often, one wants to build not only programs, but libraries, so that
863 other programs can benefit from the fruits of your labor.  Ideally, one
864 would like to produce @emph{shared} (dynamically linked) libraries,
865 which can be used by multiple programs without duplication on disk or in
866 memory and can be updated independently of the linked programs.
867 Producing shared libraries portably, however, is the stuff of
868 nightmares---each system has its own incompatible tools, compiler flags,
869 and magic incantations.  Fortunately, @acronym{GNU} provides a solution:
870 @dfn{Libtool}.
871 @cindex Libtool
873 Libtool handles all the requirements of building shared libraries for
874 you, and at this time seems to be the @emph{only} way to do so with any
875 portability.  It also handles many other headaches, such as: the
876 interaction of Make rules with the variable suffixes of
877 shared libraries, linking reliably with shared libraries before they are
878 installed by the superuser, and supplying a consistent versioning system
879 (so that different versions of a library can be installed or upgraded
880 without breaking binary compatibility).  Although Libtool, like
881 Autoconf, can be used without Automake, it is most simply utilized in
882 conjunction with Automake---there, Libtool is used automatically
883 whenever shared libraries are needed, and you need not know its syntax.
885 @node Pointers
886 @section Pointers
888 Developers who are used to the simplicity of @command{make} for small
889 projects on a single system might be daunted at the prospect of
890 learning to use Automake and Autoconf.  As your software is
891 distributed to more and more users, however, you otherwise
892 quickly find yourself putting lots of effort into reinventing the
893 services that the @acronym{GNU} build tools provide, and making the
894 same mistakes that they once made and overcame.  (Besides, since
895 you're already learning Autoconf, Automake is a piece of cake.)
897 There are a number of places that you can go to for more information on
898 the @acronym{GNU} build tools.
900 @itemize @minus
902 @item Web
904 The home pages for
905 @uref{http://www.gnu.org/@/software/@/autoconf/, Autoconf},
906 @uref{http://www.gnu.org/@/software/@/automake/, Automake},
907 @uref{http://www.gnu.org/@/software/@/gnulib/, Gnulib}, and
908 @uref{http://www.gnu.org/@/software/@/libtool/, Libtool}.
910 @item Automake Manual
912 @xref{Top, , Automake, automake, @acronym{GNU} Automake}, for more
913 information on Automake.
915 @item Books
917 The book @cite{@acronym{GNU} Autoconf, Automake and
918 Libtool}@footnote{@cite{@acronym{GNU} Autoconf, Automake and Libtool},
919 by G. V. Vaughan, B. Elliston, T. Tromey, and I. L. Taylor.  SAMS (originally
920 New Riders), 2000, ISBN 1578701902.} describes the complete @acronym{GNU}
921 build environment.  You can also find
922 @uref{http://sources.redhat.com/@/autobook/, the entire book on-line}.
924 @end itemize
926 @c ================================================= Making configure Scripts.
928 @node Making configure Scripts
929 @chapter Making @command{configure} Scripts
930 @cindex @file{aclocal.m4}
931 @cindex @command{configure}
933 The configuration scripts that Autoconf produces are by convention
934 called @command{configure}.  When run, @command{configure} creates several
935 files, replacing configuration parameters in them with appropriate
936 values.  The files that @command{configure} creates are:
938 @itemize @minus
939 @item
940 one or more @file{Makefile} files, usually one in each subdirectory of the
941 package (@pxref{Makefile Substitutions});
943 @item
944 optionally, a C header file, the name of which is configurable,
945 containing @code{#define} directives (@pxref{Configuration Headers});
947 @item
948 a shell script called @file{config.status} that, when run, recreates
949 the files listed above (@pxref{config.status Invocation});
951 @item
952 an optional shell script normally called @file{config.cache}
953 (created when using @samp{configure --config-cache}) that
954 saves the results of running many of the tests (@pxref{Cache Files});
956 @item
957 a file called @file{config.log} containing any messages produced by
958 compilers, to help debugging if @command{configure} makes a mistake.
959 @end itemize
961 @cindex @file{configure.in}
962 @cindex @file{configure.ac}
963 To create a @command{configure} script with Autoconf, you need to write an
964 Autoconf input file @file{configure.ac} (or @file{configure.in}) and run
965 @command{autoconf} on it.  If you write your own feature tests to
966 supplement those that come with Autoconf, you might also write files
967 called @file{aclocal.m4} and @file{acsite.m4}.  If you use a C header
968 file to contain @code{#define} directives, you might also run
969 @command{autoheader}, and you can distribute the generated file
970 @file{config.h.in} with the package.
972 Here is a diagram showing how the files that can be used in
973 configuration are produced.  Programs that are executed are suffixed by
974 @samp{*}.  Optional files are enclosed in square brackets (@samp{[]}).
975 @command{autoconf} and @command{autoheader} also read the installed Autoconf
976 macro files (by reading @file{autoconf.m4}).
978 @noindent
979 Files used in preparing a software package for distribution:
980 @example
981 your source files --> [autoscan*] --> [configure.scan] --> configure.ac
983 @group
984 configure.ac --.
985                |   .------> autoconf* -----> configure
986 [aclocal.m4] --+---+
987                |   `-----> [autoheader*] --> [config.h.in]
988 [acsite.m4] ---'
989 @end group
991 Makefile.in -------------------------------> Makefile.in
992 @end example
994 @noindent
995 Files used in configuring a software package:
996 @example
997 @group
998                        .-------------> [config.cache]
999 configure* ------------+-------------> config.log
1000                        |
1001 [config.h.in] -.       v            .-> [config.h] -.
1002                +--> config.status* -+               +--> make*
1003 Makefile.in ---'                    `-> Makefile ---'
1004 @end group
1005 @end example
1007 @menu
1008 * Writing Autoconf Input::      What to put in an Autoconf input file
1009 * autoscan Invocation::         Semi-automatic @file{configure.ac} writing
1010 * ifnames Invocation::          Listing the conditionals in source code
1011 * autoconf Invocation::         How to create configuration scripts
1012 * autoreconf Invocation::       Remaking multiple @command{configure} scripts
1013 @end menu
1015 @node Writing Autoconf Input
1016 @section Writing @file{configure.ac}
1018 To produce a @command{configure} script for a software package, create a
1019 file called @file{configure.ac} that contains invocations of the
1020 Autoconf macros that test the system features your package needs or can
1021 use.  Autoconf macros already exist to check for many features; see
1022 @ref{Existing Tests}, for their descriptions.  For most other features,
1023 you can use Autoconf template macros to produce custom checks; see
1024 @ref{Writing Tests}, for information about them.  For especially tricky
1025 or specialized features, @file{configure.ac} might need to contain some
1026 hand-crafted shell commands; see @ref{Portable Shell}.  The
1027 @command{autoscan} program can give you a good start in writing
1028 @file{configure.ac} (@pxref{autoscan Invocation}, for more information).
1030 Previous versions of Autoconf promoted the name @file{configure.in},
1031 which is somewhat ambiguous (the tool needed to process this file is not
1032 described by its extension), and introduces a slight confusion with
1033 @file{config.h.in} and so on (for which @samp{.in} means ``to be
1034 processed by @command{configure}'').  Using @file{configure.ac} is now
1035 preferred.
1037 @menu
1038 * Shell Script Compiler::       Autoconf as solution of a problem
1039 * Autoconf Language::           Programming in Autoconf
1040 * Autoconf Input Layout::       Standard organization of @file{configure.ac}
1041 @end menu
1043 @node Shell Script Compiler
1044 @subsection A Shell Script Compiler
1046 Just as for any other computer language, in order to properly program
1047 @file{configure.ac} in Autoconf you must understand @emph{what} problem
1048 the language tries to address and @emph{how} it does so.
1050 The problem Autoconf addresses is that the world is a mess.  After all,
1051 you are using Autoconf in order to have your package compile easily on
1052 all sorts of different systems, some of them being extremely hostile.
1053 Autoconf itself bears the price for these differences: @command{configure}
1054 must run on all those systems, and thus @command{configure} must limit itself
1055 to their lowest common denominator of features.
1057 Naturally, you might then think of shell scripts; who needs
1058 @command{autoconf}?  A set of properly written shell functions is enough to
1059 make it easy to write @command{configure} scripts by hand.  Sigh!
1060 Unfortunately, shell functions do not belong to the least common
1061 denominator; therefore, where you would like to define a function and
1062 use it ten times, you would instead need to copy its body ten times.
1063 Even in 2007, where shells without any function support are far and
1064 few between, there are pitfalls to avoid when making use of them.
1066 So, what is really needed is some kind of compiler, @command{autoconf},
1067 that takes an Autoconf program, @file{configure.ac}, and transforms it
1068 into a portable shell script, @command{configure}.
1070 How does @command{autoconf} perform this task?
1072 There are two obvious possibilities: creating a brand new language or
1073 extending an existing one.  The former option is attractive: all
1074 sorts of optimizations could easily be implemented in the compiler and
1075 many rigorous checks could be performed on the Autoconf program
1076 (e.g., rejecting any non-portable construct).  Alternatively, you can
1077 extend an existing language, such as the @code{sh} (Bourne shell)
1078 language.
1080 Autoconf does the latter: it is a layer on top of @code{sh}.  It was
1081 therefore most convenient to implement @command{autoconf} as a macro
1082 expander: a program that repeatedly performs @dfn{macro expansions} on
1083 text input, replacing macro calls with macro bodies and producing a pure
1084 @code{sh} script in the end.  Instead of implementing a dedicated
1085 Autoconf macro expander, it is natural to use an existing
1086 general-purpose macro language, such as M4, and implement the extensions
1087 as a set of M4 macros.
1090 @node Autoconf Language
1091 @subsection The Autoconf Language
1092 @cindex quotation
1094 The Autoconf language differs from many other computer
1095 languages because it treats actual code the same as plain text.  Whereas
1096 in C, for instance, data and instructions have different syntactic
1097 status, in Autoconf their status is rigorously the same.  Therefore, we
1098 need a means to distinguish literal strings from text to be expanded:
1099 quotation.
1101 When calling macros that take arguments, there must not be any white
1102 space between the macro name and the open parenthesis.  Arguments should
1103 be enclosed within the M4 quote characters @samp{[} and @samp{]}, and be
1104 separated by commas.  Any leading blanks or newlines in arguments are ignored,
1105 unless they are quoted.  You should always quote an argument that
1106 might contain a macro name, comma, parenthesis, or a leading blank or
1107 newline.  This rule applies recursively for every macro
1108 call, including macros called from other macros.
1110 For instance:
1112 @example
1113 AC_CHECK_HEADER([stdio.h],
1114                 [AC_DEFINE([HAVE_STDIO_H], [1],
1115                    [Define to 1 if you have <stdio.h>.])],
1116                 [AC_MSG_ERROR([Sorry, can't do anything for you])])
1117 @end example
1119 @noindent
1120 is quoted properly.  You may safely simplify its quotation to:
1122 @example
1123 AC_CHECK_HEADER([stdio.h],
1124                 [AC_DEFINE([HAVE_STDIO_H], 1,
1125                    [Define to 1 if you have <stdio.h>.])],
1126                 [AC_MSG_ERROR([Sorry, can't do anything for you])])
1127 @end example
1129 @noindent
1130 because @samp{1} cannot contain a macro call.  Here, the argument of
1131 @code{AC_MSG_ERROR} must be quoted; otherwise, its comma would be
1132 interpreted as an argument separator.  Also, the second and third arguments
1133 of @samp{AC_CHECK_HEADER} must be quoted, since they contain
1134 macro calls.  The three arguments @samp{HAVE_STDIO_H}, @samp{stdio.h},
1135 and @samp{Define to 1 if you have <stdio.h>.} do not need quoting, but
1136 if you unwisely defined a macro with a name like @samp{Define} or
1137 @samp{stdio} then they would need quoting.  Cautious Autoconf users
1138 would keep the quotes, but many Autoconf users find such precautions
1139 annoying, and would rewrite the example as follows:
1141 @example
1142 AC_CHECK_HEADER(stdio.h,
1143                 [AC_DEFINE(HAVE_STDIO_H, 1,
1144                    [Define to 1 if you have <stdio.h>.])],
1145                 [AC_MSG_ERROR([Sorry, can't do anything for you])])
1146 @end example
1148 @noindent
1149 This is safe, so long as you adopt good naming conventions and do not
1150 define macros with names like @samp{HAVE_STDIO_H}, @samp{stdio}, or
1151 @samp{h}.  Though it is also safe here to omit the quotes around
1152 @samp{Define to 1 if you have <stdio.h>.} this is not recommended, as
1153 message strings are more likely to inadvertently contain commas.
1155 The following example is wrong and dangerous, as it is underquoted:
1157 @example
1158 AC_CHECK_HEADER(stdio.h,
1159                 AC_DEFINE(HAVE_STDIO_H, 1,
1160                    Define to 1 if you have <stdio.h>.),
1161                 AC_MSG_ERROR([Sorry, can't do anything for you]))
1162 @end example
1164 In other cases, you may have to use text that also resembles a macro
1165 call.  You must quote that text even when it is not passed as a macro
1166 argument:
1168 @example
1169 echo "Hard rock was here!  --[AC_DC]"
1170 @end example
1172 @noindent
1173 which results in:
1175 @example
1176 echo "Hard rock was here!  --AC_DC"
1177 @end example
1179 @noindent
1180 When you use the same text in a macro argument, you must therefore have
1181 an extra quotation level (since one is stripped away by the macro
1182 substitution).  In general, then, it is a good idea to @emph{use double
1183 quoting for all literal string arguments}:
1185 @example
1186 AC_MSG_WARN([[AC_DC stinks  --Iron Maiden]])
1187 @end example
1189 You are now able to understand one of the constructs of Autoconf that
1190 has been continually misunderstood@dots{}  The rule of thumb is that
1191 @emph{whenever you expect macro expansion, expect quote expansion};
1192 i.e., expect one level of quotes to be lost.  For instance:
1194 @example
1195 AC_COMPILE_IFELSE([char b[10];], [], [AC_MSG_ERROR([you lose])])
1196 @end example
1198 @noindent
1199 is incorrect: here, the first argument of @code{AC_COMPILE_IFELSE} is
1200 @samp{char b[10];} and is expanded once, which results in
1201 @samp{char b10;}.  (There was an idiom common in Autoconf's past to
1202 address this issue via the M4 @code{changequote} primitive, but do not
1203 use it!)  Let's take a closer look: the author meant the first argument
1204 to be understood as a literal, and therefore it must be quoted twice:
1206 @example
1207 AC_COMPILE_IFELSE([[char b[10];]], [], [AC_MSG_ERROR([you lose])])
1208 @end example
1210 @noindent
1211 Voil@`a, you actually produce @samp{char b[10];} this time!
1213 On the other hand, descriptions (e.g., the last parameter of
1214 @code{AC_DEFINE} or @code{AS_HELP_STRING}) are not literals---they
1215 are subject to line breaking, for example---and should not be double quoted.
1216 Even if these descriptions are short and are not actually broken, double
1217 quoting them yields weird results.
1219 Some macros take optional arguments, which this documentation represents
1220 as @ovar{arg} (not to be confused with the quote characters).  You may
1221 just leave them empty, or use @samp{[]} to make the emptiness of the
1222 argument explicit, or you may simply omit the trailing commas.  The
1223 three lines below are equivalent:
1225 @example
1226 AC_CHECK_HEADERS([stdio.h], [], [], [])
1227 AC_CHECK_HEADERS([stdio.h],,,)
1228 AC_CHECK_HEADERS([stdio.h])
1229 @end example
1231 It is best to put each macro call on its own line in
1232 @file{configure.ac}.  Most of the macros don't add extra newlines; they
1233 rely on the newline after the macro call to terminate the commands.
1234 This approach makes the generated @command{configure} script a little
1235 easier to read by not inserting lots of blank lines.  It is generally
1236 safe to set shell variables on the same line as a macro call, because
1237 the shell allows assignments without intervening newlines.
1239 You can include comments in @file{configure.ac} files by starting them
1240 with the @samp{#}.  For example, it is helpful to begin
1241 @file{configure.ac} files with a line like this:
1243 @example
1244 # Process this file with autoconf to produce a configure script.
1245 @end example
1247 @node Autoconf Input Layout
1248 @subsection Standard @file{configure.ac} Layout
1250 The order in which @file{configure.ac} calls the Autoconf macros is not
1251 important, with a few exceptions.  Every @file{configure.ac} must
1252 contain a call to @code{AC_INIT} before the checks, and a call to
1253 @code{AC_OUTPUT} at the end (@pxref{Output}).  Additionally, some macros
1254 rely on other macros having been called first, because they check
1255 previously set values of some variables to decide what to do.  These
1256 macros are noted in the individual descriptions (@pxref{Existing
1257 Tests}), and they also warn you when @command{configure} is created if they
1258 are called out of order.
1260 To encourage consistency, here is a suggested order for calling the
1261 Autoconf macros.  Generally speaking, the things near the end of this
1262 list are those that could depend on things earlier in it.  For example,
1263 library functions could be affected by types and libraries.
1265 @display
1266 @group
1267 Autoconf requirements
1268 @code{AC_INIT(@var{package}, @var{version}, @var{bug-report-address})}
1269 information on the package
1270 checks for programs
1271 checks for libraries
1272 checks for header files
1273 checks for types
1274 checks for structures
1275 checks for compiler characteristics
1276 checks for library functions
1277 checks for system services
1278 @code{AC_CONFIG_FILES(@r{[}@var{file@dots{}}@r{]})}
1279 @code{AC_OUTPUT}
1280 @end group
1281 @end display
1284 @node autoscan Invocation
1285 @section Using @command{autoscan} to Create @file{configure.ac}
1286 @cindex @command{autoscan}
1288 The @command{autoscan} program can help you create and/or maintain a
1289 @file{configure.ac} file for a software package.  @command{autoscan}
1290 examines source files in the directory tree rooted at a directory given
1291 as a command line argument, or the current directory if none is given.
1292 It searches the source files for common portability problems and creates
1293 a file @file{configure.scan} which is a preliminary @file{configure.ac}
1294 for that package, and checks a possibly existing @file{configure.ac} for
1295 completeness.
1297 When using @command{autoscan} to create a @file{configure.ac}, you
1298 should manually examine @file{configure.scan} before renaming it to
1299 @file{configure.ac}; it probably needs some adjustments.
1300 Occasionally, @command{autoscan} outputs a macro in the wrong order
1301 relative to another macro, so that @command{autoconf} produces a warning;
1302 you need to move such macros manually.  Also, if you want the package to
1303 use a configuration header file, you must add a call to
1304 @code{AC_CONFIG_HEADERS} (@pxref{Configuration Headers}).  You might
1305 also have to change or add some @code{#if} directives to your program in
1306 order to make it work with Autoconf (@pxref{ifnames Invocation}, for
1307 information about a program that can help with that job).
1309 When using @command{autoscan} to maintain a @file{configure.ac}, simply
1310 consider adding its suggestions.  The file @file{autoscan.log}
1311 contains detailed information on why a macro is requested.
1313 @command{autoscan} uses several data files (installed along with Autoconf)
1314 to determine which macros to output when it finds particular symbols in
1315 a package's source files.  These data files all have the same format:
1316 each line consists of a symbol, one or more blanks, and the Autoconf macro to
1317 output if that symbol is encountered.  Lines starting with @samp{#} are
1318 comments.
1320 @command{autoscan} accepts the following options:
1322 @table @option
1323 @item --help
1324 @itemx -h
1325 Print a summary of the command line options and exit.
1327 @item --version
1328 @itemx -V
1329 Print the version number of Autoconf and exit.
1331 @item --verbose
1332 @itemx -v
1333 Print the names of the files it examines and the potentially interesting
1334 symbols it finds in them.  This output can be voluminous.
1336 @item --include=@var{dir}
1337 @itemx -I @var{dir}
1338 Append @var{dir} to the include path.  Multiple invocations accumulate.
1340 @item --prepend-include=@var{dir}
1341 @item -B @var{dir}
1342 Prepend @var{dir} to the include path.  Multiple invocations accumulate.
1343 @end table
1345 @node ifnames Invocation
1346 @section Using @command{ifnames} to List Conditionals
1347 @cindex @command{ifnames}
1349 @command{ifnames} can help you write @file{configure.ac} for a software
1350 package.  It prints the identifiers that the package already uses in C
1351 preprocessor conditionals.  If a package has already been set up to have
1352 some portability, @command{ifnames} can thus help you figure out what its
1353 @command{configure} needs to check for.  It may help fill in some gaps in a
1354 @file{configure.ac} generated by @command{autoscan} (@pxref{autoscan
1355 Invocation}).
1357 @command{ifnames} scans all of the C source files named on the command line
1358 (or the standard input, if none are given) and writes to the standard
1359 output a sorted list of all the identifiers that appear in those files
1360 in @code{#if}, @code{#elif}, @code{#ifdef}, or @code{#ifndef}
1361 directives.  It prints each identifier on a line, followed by a
1362 space-separated list of the files in which that identifier occurs.
1364 @noindent
1365 @command{ifnames} accepts the following options:
1367 @table @option
1368 @item --help
1369 @itemx -h
1370 Print a summary of the command line options and exit.
1372 @item --version
1373 @itemx -V
1374 Print the version number of Autoconf and exit.
1375 @end table
1377 @node autoconf Invocation
1378 @section Using @command{autoconf} to Create @command{configure}
1379 @cindex @command{autoconf}
1381 To create @command{configure} from @file{configure.ac}, run the
1382 @command{autoconf} program with no arguments.  @command{autoconf} processes
1383 @file{configure.ac} with the M4 macro processor, using the
1384 Autoconf macros.  If you give @command{autoconf} an argument, it reads that
1385 file instead of @file{configure.ac} and writes the configuration script
1386 to the standard output instead of to @command{configure}.  If you give
1387 @command{autoconf} the argument @option{-}, it reads from the standard
1388 input instead of @file{configure.ac} and writes the configuration script
1389 to the standard output.
1391 The Autoconf macros are defined in several files.  Some of the files are
1392 distributed with Autoconf; @command{autoconf} reads them first.  Then it
1393 looks for the optional file @file{acsite.m4} in the directory that
1394 contains the distributed Autoconf macro files, and for the optional file
1395 @file{aclocal.m4} in the current directory.  Those files can contain
1396 your site's or the package's own Autoconf macro definitions
1397 (@pxref{Writing Autoconf Macros}, for more information).  If a macro is
1398 defined in more than one of the files that @command{autoconf} reads, the
1399 last definition it reads overrides the earlier ones.
1401 @command{autoconf} accepts the following options:
1403 @table @option
1404 @item --help
1405 @itemx -h
1406 Print a summary of the command line options and exit.
1408 @item --version
1409 @itemx -V
1410 Print the version number of Autoconf and exit.
1412 @item --verbose
1413 @itemx -v
1414 Report processing steps.
1416 @item --debug
1417 @itemx -d
1418 Don't remove the temporary files.
1420 @item --force
1421 @itemx -f
1422 Remake @file{configure} even if newer than its input files.
1424 @item --include=@var{dir}
1425 @itemx -I @var{dir}
1426 Append @var{dir} to the include path.  Multiple invocations accumulate.
1428 @item --prepend-include=@var{dir}
1429 @item -B @var{dir}
1430 Prepend @var{dir} to the include path.  Multiple invocations accumulate.
1432 @item --output=@var{file}
1433 @itemx -o @var{file}
1434 Save output (script or trace) to @var{file}.  The file @option{-} stands
1435 for the standard output.
1437 @item --warnings=@var{category}
1438 @itemx -W @var{category}
1439 @evindex WARNINGS
1440 Report the warnings related to @var{category} (which can actually be a
1441 comma separated list).  @xref{Reporting Messages}, macro
1442 @code{AC_DIAGNOSE}, for a comprehensive list of categories.  Special
1443 values include:
1445 @table @samp
1446 @item all
1447 report all the warnings
1449 @item none
1450 report none
1452 @item error
1453 treats warnings as errors
1455 @item no-@var{category}
1456 disable warnings falling into @var{category}
1457 @end table
1459 Warnings about @samp{syntax} are enabled by default, and the environment
1460 variable @env{WARNINGS}, a comma separated list of categories, is
1461 honored as well.  Passing @option{-W @var{category}} actually behaves as if
1462 you had passed @option{--warnings syntax,$WARNINGS,@var{category}}.  If
1463 you want to disable the defaults and @env{WARNINGS}, but (for example)
1464 enable the warnings about obsolete constructs, you would use @option{-W
1465 none,obsolete}.
1467 @cindex Back trace
1468 @cindex Macro invocation stack
1469 Because @command{autoconf} uses @command{autom4te} behind the scenes, it
1470 displays a back trace for errors, but not for warnings; if you want
1471 them, just pass @option{-W error}.  @xref{autom4te Invocation}, for some
1472 examples.
1474 @item --trace=@var{macro}[:@var{format}]
1475 @itemx -t @var{macro}[:@var{format}]
1476 Do not create the @command{configure} script, but list the calls to
1477 @var{macro} according to the @var{format}.  Multiple @option{--trace}
1478 arguments can be used to list several macros.  Multiple @option{--trace}
1479 arguments for a single macro are not cumulative; instead, you should
1480 just make @var{format} as long as needed.
1482 The @var{format} is a regular string, with newlines if desired, and
1483 several special escape codes.  It defaults to @samp{$f:$l:$n:$%}; see
1484 @ref{autom4te Invocation}, for details on the @var{format}.
1486 @item --initialization
1487 @itemx -i
1488 By default, @option{--trace} does not trace the initialization of the
1489 Autoconf macros (typically the @code{AC_DEFUN} definitions).  This
1490 results in a noticeable speedup, but can be disabled by this option.
1491 @end table
1494 It is often necessary to check the content of a @file{configure.ac}
1495 file, but parsing it yourself is extremely fragile and error-prone.  It
1496 is suggested that you rely upon @option{--trace} to scan
1497 @file{configure.ac}.  For instance, to find the list of variables that
1498 are substituted, use:
1500 @example
1501 @group
1502 $ @kbd{autoconf -t AC_SUBST}
1503 configure.ac:2:AC_SUBST:ECHO_C
1504 configure.ac:2:AC_SUBST:ECHO_N
1505 configure.ac:2:AC_SUBST:ECHO_T
1506 @i{More traces deleted}
1507 @end group
1508 @end example
1510 @noindent
1511 The example below highlights the difference between @samp{$@@},
1512 @samp{$*}, and @samp{$%}.
1514 @example
1515 @group
1516 $ @kbd{cat configure.ac}
1517 AC_DEFINE(This, is, [an
1518 [example]])
1519 $ @kbd{autoconf -t 'AC_DEFINE:@@: $@@}
1520 *: $*
1521 %: $%'
1522 @@: [This],[is],[an
1523 [example]]
1524 *: This,is,an
1525 [example]
1526 %: This:is:an [example]
1527 @end group
1528 @end example
1530 @noindent
1531 The @var{format} gives you a lot of freedom:
1533 @example
1534 @group
1535 $ @kbd{autoconf -t 'AC_SUBST:$$ac_subst@{"$1"@} = "$f:$l";'}
1536 $ac_subst@{"ECHO_C"@} = "configure.ac:2";
1537 $ac_subst@{"ECHO_N"@} = "configure.ac:2";
1538 $ac_subst@{"ECHO_T"@} = "configure.ac:2";
1539 @i{More traces deleted}
1540 @end group
1541 @end example
1543 @noindent
1544 A long @var{separator} can be used to improve the readability of complex
1545 structures, and to ease their parsing (for instance when no single
1546 character is suitable as a separator):
1548 @example
1549 @group
1550 $ @kbd{autoconf -t 'AM_MISSING_PROG:$@{|:::::|@}*'}
1551 ACLOCAL|:::::|aclocal|:::::|$missing_dir
1552 AUTOCONF|:::::|autoconf|:::::|$missing_dir
1553 AUTOMAKE|:::::|automake|:::::|$missing_dir
1554 @i{More traces deleted}
1555 @end group
1556 @end example
1558 @node autoreconf Invocation
1559 @section Using @command{autoreconf} to Update @command{configure} Scripts
1560 @cindex @command{autoreconf}
1562 Installing the various components of the @acronym{GNU} Build System can be
1563 tedious: running @command{autopoint} for Gettext, @command{automake} for
1564 @file{Makefile.in} etc.@: in each directory.  It may be needed either
1565 because some tools such as @command{automake} have been updated on your
1566 system, or because some of the sources such as @file{configure.ac} have
1567 been updated, or finally, simply in order to install the @acronym{GNU} Build
1568 System in a fresh tree.
1570 @command{autoreconf} runs @command{autoconf}, @command{autoheader},
1571 @command{aclocal}, @command{automake}, @command{libtoolize}, and
1572 @command{autopoint} (when appropriate) repeatedly to update the
1573 @acronym{GNU} Build System in the specified directories and their
1574 subdirectories (@pxref{Subdirectories}).  By default, it only remakes
1575 those files that are older than their sources.  The environment variables
1576 @env{AUTOCONF}, @env{AUTOHEADER}, @env{AUTOMAKE}, @env{ACLOCAL},
1577 @env{AUTOPOINT}, @env{LIBTOOLIZE}, @env{M4}, and @env{MAKE} may be used
1578 to override the invocation of the respective tools.
1580 If you install a new version of some tool, you can make
1581 @command{autoreconf} remake @emph{all} of the files by giving it the
1582 @option{--force} option.
1584 @xref{Automatic Remaking}, for Make rules to automatically
1585 rebuild @command{configure} scripts when their source files change.  That
1586 method handles the timestamps of configuration header templates
1587 properly, but does not pass @option{--autoconf-dir=@var{dir}} or
1588 @option{--localdir=@var{dir}}.
1590 @cindex Gettext
1591 @cindex @command{autopoint}
1592 Gettext supplies the @command{autopoint} command to add translation
1593 infrastructure to a source package.  If you use @command{autopoint},
1594 your @file{configure.ac} should invoke both @code{AM_GNU_GETTEXT} and
1595 @code{AM_GNU_GETTEXT_VERSION(@var{gettext-version})}.  @xref{autopoint
1596 Invocation, , Invoking the @code{autopoint} Program, gettext,
1597 @acronym{GNU} @code{gettext} utilities}, for further details.
1599 @noindent
1600 @command{autoreconf} accepts the following options:
1602 @table @option
1603 @item --help
1604 @itemx -h
1605 Print a summary of the command line options and exit.
1607 @item --version
1608 @itemx -V
1609 Print the version number of Autoconf and exit.
1611 @item --verbose
1612 Print the name of each directory @command{autoreconf} examines and the
1613 commands it runs.  If given two or more times, pass @option{--verbose}
1614 to subordinate tools that support it.
1616 @item --debug
1617 @itemx -d
1618 Don't remove the temporary files.
1620 @item --force
1621 @itemx -f
1622 Remake even @file{configure} scripts and configuration headers that are
1623 newer than their input files (@file{configure.ac} and, if present,
1624 @file{aclocal.m4}).
1626 @item --install
1627 @itemx -i
1628 Install the missing auxiliary files in the package.  By default, files
1629 are copied; this can be changed with @option{--symlink}.
1631 If deemed appropriate, this option triggers calls to
1632 @samp{automake --add-missing},
1633 @samp{libtoolize}, @samp{autopoint}, etc.
1635 @item --no-recursive
1636 Do not rebuild files in subdirectories to configure (see @ref{Subdirectories},
1637 macro @code{AC_CONFIG_SUBDIRS}).
1639 @item --symlink
1640 @itemx -s
1641 When used with @option{--install}, install symbolic links to the missing
1642 auxiliary files instead of copying them.
1644 @item --make
1645 @itemx -m
1646 When the directories were configured, update the configuration by
1647 running @samp{./config.status --recheck && ./config.status}, and then
1648 run @samp{make}.
1650 @item --include=@var{dir}
1651 @itemx -I @var{dir}
1652 Append @var{dir} to the include path.  Multiple invocations accumulate.
1653 Passed on to @command{autoconf} and @command{autoheader} internally.
1655 @item --prepend-include=@var{dir}
1656 @item -B @var{dir}
1657 Prepend @var{dir} to the include path.  Multiple invocations accumulate.
1658 Passed on to @command{autoconf} and @command{autoheader} internally.
1660 @item --warnings=@var{category}
1661 @itemx -W @var{category}
1662 @evindex WARNINGS
1663 Report the warnings related to @var{category} (which can actually be a
1664 comma separated list).
1666 @table @samp
1667 @item cross
1668 related to cross compilation issues.
1670 @item obsolete
1671 report the uses of obsolete constructs.
1673 @item portability
1674 portability issues
1676 @item syntax
1677 dubious syntactic constructs.
1679 @item all
1680 report all the warnings
1682 @item none
1683 report none
1685 @item error
1686 treats warnings as errors
1688 @item no-@var{category}
1689 disable warnings falling into @var{category}
1690 @end table
1692 Warnings about @samp{syntax} are enabled by default, and the environment
1693 variable @env{WARNINGS}, a comma separated list of categories, is
1694 honored as well.  Passing @option{-W @var{category}} actually behaves as if
1695 you had passed @option{--warnings syntax,$WARNINGS,@var{category}}.  If
1696 you want to disable the defaults and @env{WARNINGS}, but (for example)
1697 enable the warnings about obsolete constructs, you would use @option{-W
1698 none,obsolete}.
1699 @end table
1701 If you want @command{autoreconf} to pass flags that are not listed here
1702 on to @command{aclocal}, set @code{ACLOCAL_AMFLAGS} in your @file{Makefile.am}.
1703 Due to a limitation in the Autoconf implementation these flags currently
1704 must be set on a single line in @file{Makefile.am}, without any
1705 backslash-newlines.
1707 @c ========================================= Initialization and Output Files.
1709 @node Setup
1710 @chapter Initialization and Output Files
1712 Autoconf-generated @command{configure} scripts need some information about
1713 how to initialize, such as how to find the package's source files and
1714 about the output files to produce.  The following sections describe the
1715 initialization and the creation of output files.
1717 @menu
1718 * Initializing configure::      Option processing etc.
1719 * Versioning::                  Dealing with Autoconf versions
1720 * Notices::                     Copyright, version numbers in @command{configure}
1721 * Input::                       Where Autoconf should find files
1722 * Output::                      Outputting results from the configuration
1723 * Configuration Actions::       Preparing the output based on results
1724 * Configuration Files::         Creating output files
1725 * Makefile Substitutions::      Using output variables in makefiles
1726 * Configuration Headers::       Creating a configuration header file
1727 * Configuration Commands::      Running arbitrary instantiation commands
1728 * Configuration Links::         Links depending on the configuration
1729 * Subdirectories::              Configuring independent packages together
1730 * Default Prefix::              Changing the default installation prefix
1731 @end menu
1733 @node Initializing configure
1734 @section Initializing @command{configure}
1736 Every @command{configure} script must call @code{AC_INIT} before doing
1737 anything else.  The only other required macro is @code{AC_OUTPUT}
1738 (@pxref{Output}).
1740 @anchor{AC_INIT}
1741 @defmac AC_INIT (@var{package}, @var{version}, @ovar{bug-report}, @
1742   @ovar{tarname})
1743 @acindex{INIT}
1744 Process any command-line arguments and perform various initializations
1745 and verifications.
1747 Set the name of the @var{package} and its @var{version}.  These are
1748 typically used in @option{--version} support, including that of
1749 @command{configure}.  The optional argument @var{bug-report} should be
1750 the email to which users should send bug reports.  The package
1751 @var{tarname} differs from @var{package}: the latter designates the full
1752 package name (e.g., @samp{GNU Autoconf}), while the former is meant for
1753 distribution tar ball names (e.g., @samp{autoconf}).  It defaults to
1754 @var{package} with @samp{GNU } stripped, lower-cased, and all characters
1755 other than alphanumerics and underscores are changed to @samp{-}.
1757 It is preferable that the arguments of @code{AC_INIT} be static, i.e.,
1758 there should not be any shell computation, but they can be computed by
1761 The following M4 macros (e.g., @code{AC_PACKAGE_NAME}), output variables
1762 (e.g., @code{PACKAGE_NAME}), and preprocessor symbols (e.g.,
1763 @code{PACKAGE_NAME}), are defined by @code{AC_INIT}:
1765 @table @asis
1766 @item @code{AC_PACKAGE_NAME}, @code{PACKAGE_NAME}
1767 @acindex{PACKAGE_NAME}
1768 @ovindex PACKAGE_NAME
1769 @cvindex PACKAGE_NAME
1770 Exactly @var{package}.
1772 @item @code{AC_PACKAGE_TARNAME}, @code{PACKAGE_TARNAME}
1773 @acindex{PACKAGE_TARNAME}
1774 @ovindex PACKAGE_TARNAME
1775 @cvindex PACKAGE_TARNAME
1776 Exactly @var{tarname}.
1778 @item @code{AC_PACKAGE_VERSION}, @code{PACKAGE_VERSION}
1779 @acindex{PACKAGE_VERSION}
1780 @ovindex PACKAGE_VERSION
1781 @cvindex PACKAGE_VERSION
1782 Exactly @var{version}.
1784 @item @code{AC_PACKAGE_STRING}, @code{PACKAGE_STRING}
1785 @acindex{PACKAGE_STRING}
1786 @ovindex PACKAGE_STRING
1787 @cvindex PACKAGE_STRING
1788 Exactly @samp{@var{package} @var{version}}.
1790 @item @code{AC_PACKAGE_BUGREPORT}, @code{PACKAGE_BUGREPORT}
1791 @acindex{PACKAGE_BUGREPORT}
1792 @ovindex PACKAGE_BUGREPORT
1793 @cvindex PACKAGE_BUGREPORT
1794 Exactly @var{bug-report}.
1795 @end table
1796 @end defmac
1798 If your @command{configure} script does its own option processing, it
1799 should inspect @samp{$@@} or @samp{$*} immediately after calling
1800 @code{AC_INIT}, because other Autoconf macros liberally use the
1801 @command{set} command to process strings, and this has the side effect
1802 of updating @samp{$@@} and @samp{$*}.  However, we suggest that you use
1803 standard macros like @code{AC_ARG_ENABLE} instead of attempting to
1804 implement your own option processing.  @xref{Site Configuration}.
1806 @node Versioning
1807 @section Dealing with Autoconf versions
1808 @cindex Autoconf version
1809 @cindex version, Autoconf
1811 The following optional macros can be used to help choose the minimum
1812 version of Autoconf that can successfully compile a given
1813 @file{configure.ac}.
1815 @defmac AC_PREREQ (@var{version})
1816 @acindex{PREREQ}
1817 @cindex Version
1818 Ensure that a recent enough version of Autoconf is being used.  If the
1819 version of Autoconf being used to create @command{configure} is
1820 earlier than @var{version}, print an error message to the standard
1821 error output and exit with failure (exit status is 63).  For example:
1823 @example
1824 AC_PREREQ([@value{VERSION}])
1825 @end example
1827 This macro is the only macro that may be used before @code{AC_INIT}, but
1828 for consistency, you are invited not to do so.
1829 @end defmac
1831 @defmac AC_AUTOCONF_VERSION
1832 @acindex{AUTOCONF_VERSION}
1833 This macro was introduced in Autoconf 2.62.  It identifies the version
1834 of Autoconf that is currently parsing the input file, in a format
1835 suitable for @code{m4_version_compare} (@pxref{m4_version_compare}); in
1836 other words, for this release of Autoconf, its value is
1837 @samp{@value{VERSION}}.  One potential use of this macro is for writing
1838 conditional fallbacks based on when a feature was added to Autoconf,
1839 rather than using @code{AC_PREREQ} to require the newer version of
1840 Autoconf.  However, remember that the Autoconf philosophy favors feature
1841 checks over version checks.
1843 You should never expand this macro directly, but instead use
1844 @samp{m4_defn([AC_AUTOCONF_VERSION])}.  This is because some users might
1845 have a beta version of Autoconf installed, with arbitrary letters
1846 included in its version string.  This means it is possible for the
1847 version string to contain the name of a defined macro, such that
1848 expanding @code{AC_AUTOCONF_VERSION} would trigger the expansion of that
1849 macro during rescanning, and change the version string to be different
1850 than what you intended to check.
1851 @end defmac
1853 @node Notices
1854 @section Notices in @command{configure}
1855 @cindex Notices in @command{configure}
1857 The following macros manage version numbers for @command{configure}
1858 scripts.  Using them is optional.
1860 @defmac AC_COPYRIGHT (@var{copyright-notice})
1861 @acindex{COPYRIGHT}
1862 @cindex Copyright Notice
1863 State that, in addition to the Free Software Foundation's copyright on
1864 the Autoconf macros, parts of your @command{configure} are covered by the
1865 @var{copyright-notice}.
1867 The @var{copyright-notice} shows up in both the head of
1868 @command{configure} and in @samp{configure --version}.
1869 @end defmac
1872 @defmac AC_REVISION (@var{revision-info})
1873 @acindex{REVISION}
1874 @cindex Revision
1875 Copy revision stamp @var{revision-info} into the @command{configure}
1876 script, with any dollar signs or double-quotes removed.  This macro lets
1877 you put a revision stamp from @file{configure.ac} into @command{configure}
1878 without @acronym{RCS} or @acronym{CVS} changing it when you check in
1879 @command{configure}.  That way, you can determine easily which revision of
1880 @file{configure.ac} a particular @command{configure} corresponds to.
1882 For example, this line in @file{configure.ac}:
1884 @c The @w prevents RCS from changing the example in the manual.
1885 @example
1886 AC_REVISION([@w{$}Revision: 1.30 $])
1887 @end example
1889 @noindent
1890 produces this in @command{configure}:
1892 @example
1893 #!/bin/sh
1894 # From configure.ac Revision: 1.30
1895 @end example
1896 @end defmac
1899 @node Input
1900 @section Finding @command{configure} Input
1902 @anchor{AC_CONFIG_SRCDIR}
1903 @defmac AC_CONFIG_SRCDIR (@var{unique-file-in-source-dir})
1904 @acindex{CONFIG_SRCDIR}
1905 @var{unique-file-in-source-dir} is some file that is in the package's
1906 source directory; @command{configure} checks for this file's existence to
1907 make sure that the directory that it is told contains the source code in
1908 fact does.  Occasionally people accidentally specify the wrong directory
1909 with @option{--srcdir}; this is a safety check.  @xref{configure
1910 Invocation}, for more information.
1911 @end defmac
1914 @c FIXME: Remove definitively once --install explained.
1916 @c Small packages may store all their macros in @code{aclocal.m4}.  As the
1917 @c set of macros grows, or for maintenance reasons, a maintainer may prefer
1918 @c to split the macros in several files.  In this case, Autoconf must be
1919 @c told which files to load, and in which order.
1921 @c @defmac AC_INCLUDE (@var{file}@dots{})
1922 @c @acindex{INCLUDE}
1923 @c @c FIXME: There is no longer shell globbing.
1924 @c Read the macro definitions that appear in the listed files.  A list of
1925 @c space-separated file names or shell globbing patterns is expected.  The
1926 @c files are read in the order they're listed.
1928 @c Because the order of definition of macros is important (only the last
1929 @c definition of a macro is used), beware that it is @code{AC_INIT} that
1930 @c loads @file{acsite.m4} and @file{aclocal.m4}.  Note that
1931 @c @code{AC_INCLUDE}ing a file before @code{AC_INIT} or within
1932 @c @file{aclocal.m4} is different from doing so after @code{AC_INIT}: in
1933 @c the latter case, non-macro lines from included files may end up in the
1934 @c @file{configure} script, whereas in the former case, they'd be discarded
1935 @c just like any text that appear before @code{AC_INIT}.
1936 @c @end defmac
1938 Packages that do manual configuration or use the @command{install} program
1939 might need to tell @command{configure} where to find some other shell
1940 scripts by calling @code{AC_CONFIG_AUX_DIR}, though the default places
1941 it looks are correct for most cases.
1943 @defmac AC_CONFIG_AUX_DIR (@var{dir})
1944 @acindex{CONFIG_AUX_DIR}
1945 Use the auxiliary build tools (e.g., @file{install-sh},
1946 @file{config.sub}, @file{config.guess}, Cygnus @command{configure},
1947 Automake and Libtool scripts, etc.)@: that are in directory @var{dir}.
1948 These are auxiliary files used in configuration.  @var{dir} can be
1949 either absolute or relative to @file{@var{srcdir}}.  The default is
1950 @file{@var{srcdir}} or @file{@var{srcdir}/..} or
1951 @file{@var{srcdir}/../..}, whichever is the first that contains
1952 @file{install-sh}.  The other files are not checked for, so that using
1953 @code{AC_PROG_INSTALL} does not automatically require distributing the
1954 other auxiliary files.  It checks for @file{install.sh} also, but that
1955 name is obsolete because some @code{make} have a rule that creates
1956 @file{install} from it if there is no makefile.
1958 The auxiliary directory is commonly named @file{build-aux}.
1959 If you need portability to @acronym{DOS} variants, do not name the
1960 auxiliary directory @file{aux}.  @xref{File System Conventions}.
1961 @end defmac
1963 @defmac AC_REQUIRE_AUX_FILE (@var{file})
1964 @acindex{REQUIRE_AUX_FILE}
1965 Declares that @var{file} is expected in the directory defined above.  In
1966 Autoconf proper, this macro does nothing: its sole purpose is to be
1967 traced by third-party tools to produce a list of expected auxiliary
1968 files.  For instance it is called by macros like @code{AC_PROG_INSTALL}
1969 (@pxref{Particular Programs}) or @code{AC_CANONICAL_BUILD}
1970 (@pxref{Canonicalizing}) to register the auxiliary files they need.
1971 @end defmac
1973 Similarly, packages that use @command{aclocal} should declare where
1974 local macros can be found using @code{AC_CONFIG_MACRO_DIR}.
1976 @defmac AC_CONFIG_MACRO_DIR (@var{dir})
1977 @acindex{CONFIG_MACRO_DIR}
1978 Specify @var{dir} as the location of additional local Autoconf macros.
1979 This macro is intended for use by future versions of commands like
1980 @command{autoreconf} that trace macro calls.  It should be called
1981 directly from @file{configure.ac} so that tools that install macros for
1982 @command{aclocal} can find the macros' declarations.
1984 Note that if you use @command{aclocal} from Automake to generate
1985 @file{aclocal.m4}, you must also set @code{ACLOCAL_AMFLAGS = -I
1986 @var{dir}} in your top-level @file{Makefile.am}.  Due to a limitation in
1987 the Autoconf implementation of @command{autoreconf}, these include
1988 directives currently must be set on a single line in @file{Makefile.am},
1989 without any backslash-newlines.
1990 @end defmac
1993 @node Output
1994 @section Outputting Files
1995 @cindex Outputting files
1997 Every Autoconf script, e.g., @file{configure.ac}, should finish by
1998 calling @code{AC_OUTPUT}.  That is the macro that generates and runs
1999 @file{config.status}, which in turn creates the makefiles and any
2000 other files resulting from configuration.  This is the only required
2001 macro besides @code{AC_INIT} (@pxref{Input}).
2003 @anchor{AC_OUTPUT}
2004 @defmac AC_OUTPUT
2005 @acindex{OUTPUT}
2006 @cindex Instantiation
2007 Generate @file{config.status} and launch it.  Call this macro once, at
2008 the end of @file{configure.ac}.
2010 @file{config.status} performs all the configuration actions: all the
2011 output files (see @ref{Configuration Files}, macro
2012 @code{AC_CONFIG_FILES}), header files (see @ref{Configuration Headers},
2013 macro @code{AC_CONFIG_HEADERS}), commands (see @ref{Configuration
2014 Commands}, macro @code{AC_CONFIG_COMMANDS}), links (see
2015 @ref{Configuration Links}, macro @code{AC_CONFIG_LINKS}), subdirectories
2016 to configure (see @ref{Subdirectories}, macro @code{AC_CONFIG_SUBDIRS})
2017 are honored.
2019 The location of your @code{AC_OUTPUT} invocation is the exact point
2020 where configuration actions are taken: any code afterwards is
2021 executed by @code{configure} once @command{config.status} was run.  If
2022 you want to bind actions to @command{config.status} itself
2023 (independently of whether @command{configure} is being run), see
2024 @ref{Configuration Commands, , Running Arbitrary Configuration
2025 Commands}.
2026 @end defmac
2028 Historically, the usage of @code{AC_OUTPUT} was somewhat different.
2029 @xref{Obsolete Macros}, for a description of the arguments that
2030 @code{AC_OUTPUT} used to support.
2033 If you run @command{make} in subdirectories, you should run it using the
2034 @code{make} variable @code{MAKE}.  Most versions of @command{make} set
2035 @code{MAKE} to the name of the @command{make} program plus any options it
2036 was given.  (But many do not include in it the values of any variables
2037 set on the command line, so those are not passed on automatically.)
2038 Some old versions of @command{make} do not set this variable.  The
2039 following macro allows you to use it even with those versions.
2041 @anchor{AC_PROG_MAKE_SET}
2042 @defmac AC_PROG_MAKE_SET
2043 @acindex{PROG_MAKE_SET}
2044 @ovindex SET_MAKE
2045 If the Make command, @code{$MAKE} if set or else @samp{make}, predefines
2046 @code{$(MAKE)}, define output variable @code{SET_MAKE} to be empty.
2047 Otherwise, define @code{SET_MAKE} to a macro definition that sets
2048 @code{$(MAKE)}, such as @samp{MAKE=make}.  Calls @code{AC_SUBST} for
2049 @code{SET_MAKE}.
2050 @end defmac
2052 If you use this macro, place a line like this in each @file{Makefile.in}
2053 that runs @code{MAKE} on other directories:
2055 @example
2056 @@SET_MAKE@@
2057 @end example
2061 @node Configuration Actions
2062 @section Performing Configuration Actions
2063 @cindex Configuration actions
2065 @file{configure} is designed so that it appears to do everything itself,
2066 but there is actually a hidden slave: @file{config.status}.
2067 @file{configure} is in charge of examining your system, but it is
2068 @file{config.status} that actually takes the proper actions based on the
2069 results of @file{configure}.  The most typical task of
2070 @file{config.status} is to @emph{instantiate} files.
2072 This section describes the common behavior of the four standard
2073 instantiating macros: @code{AC_CONFIG_FILES}, @code{AC_CONFIG_HEADERS},
2074 @code{AC_CONFIG_COMMANDS} and @code{AC_CONFIG_LINKS}.  They all
2075 have this prototype:
2077 @c FIXME: Can't use @ovar here, Texinfo 4.0 goes lunatic and emits something
2078 @c awful.
2079 @example
2080 AC_CONFIG_FOOS(@var{tag}@dots{}, [@var{commands}], [@var{init-cmds}])
2081 @end example
2083 @noindent
2084 where the arguments are:
2086 @table @var
2087 @item tag@dots{}
2088 A blank-or-newline-separated list of tags, which are typically the names of
2089 the files to instantiate.
2091 You are encouraged to use literals as @var{tags}.  In particular, you
2092 should avoid
2094 @example
2095 @dots{} && my_foos="$my_foos fooo"
2096 @dots{} && my_foos="$my_foos foooo"
2097 AC_CONFIG_FOOS([$my_foos])
2098 @end example
2100 @noindent
2101 and use this instead:
2103 @example
2104 @dots{} && AC_CONFIG_FOOS([fooo])
2105 @dots{} && AC_CONFIG_FOOS([foooo])
2106 @end example
2108 The macros @code{AC_CONFIG_FILES} and @code{AC_CONFIG_HEADERS} use
2109 special @var{tag} values: they may have the form @samp{@var{output}} or
2110 @samp{@var{output}:@var{inputs}}.  The file @var{output} is instantiated
2111 from its templates, @var{inputs} (defaulting to @samp{@var{output}.in}).
2113 @samp{AC_CONFIG_FILES([Makefile:boiler/top.mk:boiler/bot.mk)]},
2114 for example, asks for
2115 the creation of the file @file{Makefile} that contains the expansion of the
2116 output variables in the concatenation of @file{boiler/top.mk} and
2117 @file{boiler/bot.mk}.
2119 The special value @samp{-} might be used to denote the standard output
2120 when used in @var{output}, or the standard input when used in the
2121 @var{inputs}.  You most probably don't need to use this in
2122 @file{configure.ac}, but it is convenient when using the command line
2123 interface of @file{./config.status}, see @ref{config.status Invocation},
2124 for more details.
2126 The @var{inputs} may be absolute or relative file names.  In the latter
2127 case they are first looked for in the build tree, and then in the source
2128 tree.
2130 @item commands
2131 Shell commands output literally into @file{config.status}, and
2132 associated with a tag that the user can use to tell @file{config.status}
2133 which the commands to run.  The commands are run each time a @var{tag}
2134 request is given to @file{config.status}, typically each time the file
2135 @file{@var{tag}} is created.
2137 The variables set during the execution of @command{configure} are
2138 @emph{not} available here: you first need to set them via the
2139 @var{init-cmds}.  Nonetheless the following variables are precomputed:
2141 @table @code
2142 @item srcdir
2143 The name of the top source directory, assuming that the working
2144 directory is the top build directory.  This
2145 is what the @command{configure} option @option{--srcdir} sets.
2147 @item ac_top_srcdir
2148 The name of the top source directory, assuming that the working
2149 directory is the current build directory.
2152 @item ac_top_build_prefix
2153 The name of the top build directory, assuming that the working
2154 directory is the current build directory.
2155 It can be empty, or else ends with a slash, so that you may concatenate
2158 @item ac_srcdir
2159 The name of the corresponding source directory, assuming that the
2160 working directory is the current build directory.
2161 @end table
2163 @noindent
2164 The @dfn{current} directory refers to the directory (or
2165 pseudo-directory) containing the input part of @var{tags}.  For
2166 instance, running
2168 @example
2169 AC_CONFIG_COMMANDS([deep/dir/out:in/in.in], [@dots{}], [@dots{}])
2170 @end example
2172 @noindent
2173  with @option{--srcdir=../package} produces the following values:
2175 @example
2176 # Argument of --srcdir
2177 srcdir='../package'
2178 # Reversing deep/dir
2179 ac_top_build_prefix='../../'
2180 # Concatenation of $ac_top_build_prefix and srcdir
2181 ac_top_srcdir='../../../package'
2182 # Concatenation of $ac_top_srcdir and deep/dir
2183 ac_srcdir='../../../package/deep/dir'
2184 @end example
2186 @noindent
2187 independently of @samp{in/in.in}.
2189 @item init-cmds
2190 Shell commands output @emph{unquoted} near the beginning of
2191 @file{config.status}, and executed each time @file{config.status} runs
2192 (regardless of the tag).  Because they are unquoted, for example,
2193 @samp{$var} is output as the value of @code{var}.  @var{init-cmds}
2194 is typically used by @file{configure} to give @file{config.status} some
2195 variables it needs to run the @var{commands}.
2197 You should be extremely cautious in your variable names: all the
2198 @var{init-cmds} share the same name space and may overwrite each other
2199 in unpredictable ways.  Sorry@enddots{}
2200 @end table
2202 All these macros can be called multiple times, with different
2203 @var{tag} values, of course!
2206 @node Configuration Files
2207 @section Creating Configuration Files
2208 @cindex Creating configuration files
2209 @cindex Configuration file creation
2211 Be sure to read the previous section, @ref{Configuration Actions}.
2213 @anchor{AC_CONFIG_FILES}
2214 @defmac AC_CONFIG_FILES (@var{file}@dots{}, @ovar{cmds}, @ovar{init-cmds})
2215 @acindex{CONFIG_FILES}
2216 Make @code{AC_OUTPUT} create each @file{@var{file}} by copying an input
2217 file (by default @file{@var{file}.in}), substituting the output variable
2218 values.
2219 @c Before we used to have this feature, which was later rejected
2220 @c because it complicates the writing of makefiles:
2221 @c If the file would be unchanged, it is left untouched, to preserve
2222 @c timestamp.
2223 This macro is one of the instantiating macros; see @ref{Configuration
2224 Actions}.  @xref{Makefile Substitutions}, for more information on using
2225 output variables.  @xref{Setting Output Variables}, for more information
2226 on creating them.  This macro creates the directory that the file is in
2227 if it doesn't exist.  Usually, makefiles are created this way,
2228 but other files, such as @file{.gdbinit}, can be specified as well.
2230 Typical calls to @code{AC_CONFIG_FILES} look like this:
2232 @example
2233 AC_CONFIG_FILES([Makefile src/Makefile man/Makefile X/Imakefile])
2234 AC_CONFIG_FILES([autoconf], [chmod +x autoconf])
2235 @end example
2237 You can override an input file name by appending to @var{file} a
2238 colon-separated list of input files.  Examples:
2240 @example
2241 AC_CONFIG_FILES([Makefile:boiler/top.mk:boiler/bot.mk]
2242                 [lib/Makefile:boiler/lib.mk])
2243 @end example
2245 @noindent
2246 Doing this allows you to keep your file names acceptable to
2247 @acronym{DOS} variants, or
2248 to prepend and/or append boilerplate to the file.
2249 @end defmac
2253 @node Makefile Substitutions
2254 @section Substitutions in Makefiles
2255 @cindex Substitutions in makefiles
2256 @cindex Makefile substitutions
2258 Each subdirectory in a distribution that contains something to be
2259 compiled or installed should come with a file @file{Makefile.in}, from
2260 which @command{configure} creates a file @file{Makefile} in that directory.
2261 To create @file{Makefile}, @command{configure} performs a simple variable
2262 substitution, replacing occurrences of @samp{@@@var{variable}@@} in
2263 @file{Makefile.in} with the value that @command{configure} has determined
2264 for that variable.  Variables that are substituted into output files in
2265 this way are called @dfn{output variables}.  They are ordinary shell
2266 variables that are set in @command{configure}.  To make @command{configure}
2267 substitute a particular variable into the output files, the macro
2268 @code{AC_SUBST} must be called with that variable name as an argument.
2269 Any occurrences of @samp{@@@var{variable}@@} for other variables are
2270 left unchanged.  @xref{Setting Output Variables}, for more information
2271 on creating output variables with @code{AC_SUBST}.
2273 A software package that uses a @command{configure} script should be
2274 distributed with a file @file{Makefile.in}, but no makefile; that
2275 way, the user has to properly configure the package for the local system
2276 before compiling it.
2278 @xref{Makefile Conventions, , Makefile Conventions, standards, The
2279 @acronym{GNU} Coding Standards}, for more information on what to put in
2280 makefiles.
2282 @menu
2283 * Preset Output Variables::     Output variables that are always set
2284 * Installation Directory Variables::  Other preset output variables
2285 * Changed Directory Variables:: Warnings about @file{datarootdir}
2286 * Build Directories::           Supporting multiple concurrent compiles
2287 * Automatic Remaking::          Makefile rules for configuring
2288 @end menu
2290 @node Preset Output Variables
2291 @subsection Preset Output Variables
2292 @cindex Output variables
2294 Some output variables are preset by the Autoconf macros.  Some of the
2295 Autoconf macros set additional output variables, which are mentioned in
2296 the descriptions for those macros.  @xref{Output Variable Index}, for a
2297 complete list of output variables.  @xref{Installation Directory
2298 Variables}, for the list of the preset ones related to installation
2299 directories.  Below are listed the other preset ones.  They all are
2300 precious variables (@pxref{Setting Output Variables},
2301 @code{AC_ARG_VAR}).
2303 @c Just say no to ASCII sorting!  We're humans, not computers.
2304 @c These variables are listed as they would be in a dictionary:
2305 @c actor
2306 @c Actress
2307 @c actress
2309 @defvar CFLAGS
2310 @ovindex CFLAGS
2311 Debugging and optimization options for the C compiler.  If it is not set
2312 in the environment when @command{configure} runs, the default value is set
2313 when you call @code{AC_PROG_CC} (or empty if you don't).  @command{configure}
2314 uses this variable when compiling or linking programs to test for C features.
2316 If a compiler option affects only the behavior of the preprocessor
2317 (e.g., @option{-D @var{name}}), it should be put into @code{CPPFLAGS}
2318 instead.  If it affects only the linker (e.g., @option{-L
2319 @var{directory}}), it should be put into @code{LDFLAGS} instead.  If it
2320 affects only the compiler proper, @code{CFLAGS} is the natural home for
2321 it.  If an option affects multiple phases of the compiler, though,
2322 matters get tricky.  One approach to put such options directly into
2323 @code{CC}, e.g., @code{CC='gcc -m64'}.  Another is to put them into both
2324 @code{CPPFLAGS} and @code{LDFLAGS}, but not into @code{CFLAGS}.
2326 @end defvar
2328 @defvar configure_input
2329 @ovindex configure_input
2330 A comment saying that the file was generated automatically by
2331 @command{configure} and giving the name of the input file.
2332 @code{AC_OUTPUT} adds a comment line containing this variable to the top
2333 of every makefile it creates.  For other files, you should
2334 reference this variable in a comment at the top of each input file.  For
2335 example, an input shell script should begin like this:
2337 @example
2338 #!/bin/sh
2339 # @@configure_input@@
2340 @end example
2342 @noindent
2343 The presence of that line also reminds people editing the file that it
2344 needs to be processed by @command{configure} in order to be used.
2345 @end defvar
2347 @defvar CPPFLAGS
2348 @ovindex CPPFLAGS
2349 Preprocessor options for the C, C++, and Objective C preprocessors and
2350 compilers.  If
2351 it is not set in the environment when @command{configure} runs, the default
2352 value is empty.  @command{configure} uses this variable when preprocessing
2353 or compiling programs to test for C, C++, and Objective C features.
2355 This variable's contents should contain options like @option{-I},
2356 @option{-D}, and @option{-U} that affect only the behavior of the
2357 preprocessor.  Please see the explanation of @code{CFLAGS} for what you
2358 can do if an option affects other phases of the compiler as well.
2360 Currently, @command{configure} always links as part of a single
2361 invocation of the compiler that also preprocesses and compiles, so it
2362 uses this variable also when linking programs.  However, it is unwise to
2363 depend on this behavior because the @acronym{GNU} coding standards do
2364 not require it and many packages do not use @code{CPPFLAGS} when linking
2365 programs.
2367 @xref{Special Chars in Variables}, for limitations that @code{CPPFLAGS}
2368 might run into.
2369 @end defvar
2371 @defvar CXXFLAGS
2372 @ovindex CXXFLAGS
2373 Debugging and optimization options for the C++ compiler.  It acts like
2374 @code{CFLAGS}, but for C++ instead of C.
2375 @end defvar
2377 @defvar DEFS
2378 @ovindex DEFS
2379 @option{-D} options to pass to the C compiler.  If @code{AC_CONFIG_HEADERS}
2380 is called, @command{configure} replaces @samp{@@DEFS@@} with
2381 @option{-DHAVE_CONFIG_H} instead (@pxref{Configuration Headers}).  This
2382 variable is not defined while @command{configure} is performing its tests,
2383 only when creating the output files.  @xref{Setting Output Variables}, for
2384 how to check the results of previous tests.
2385 @end defvar
2387 @defvar ECHO_C
2388 @defvarx ECHO_N
2389 @defvarx ECHO_T
2390 @ovindex ECHO_C
2391 @ovindex ECHO_N
2392 @ovindex ECHO_T
2393 How does one suppress the trailing newline from @command{echo} for
2394 question-answer message pairs?  These variables provide a way:
2396 @example
2397 echo $ECHO_N "And the winner is... $ECHO_C"
2398 sleep 100000000000
2399 echo "$@{ECHO_T@}dead."
2400 @end example
2402 @noindent
2403 Some old and uncommon @command{echo} implementations offer no means to
2404 achieve this, in which case @code{ECHO_T} is set to tab.  You might not
2405 want to use it.
2406 @end defvar
2408 @defvar ERLCFLAGS
2409 @ovindex ERLCFLAGS
2410 Debugging and optimization options for the Erlang compiler.  If it is not set
2411 in the environment when @command{configure} runs, the default value is empty.
2412 @command{configure} uses this variable when compiling
2413 programs to test for Erlang features.
2414 @end defvar
2416 @defvar FCFLAGS
2417 @ovindex FCFLAGS
2418 Debugging and optimization options for the Fortran compiler.  If it
2419 is not set in the environment when @command{configure} runs, the default
2420 value is set when you call @code{AC_PROG_FC} (or empty if you don't).
2421 @command{configure} uses this variable when compiling or linking
2422 programs to test for Fortran features.
2423 @end defvar
2425 @defvar FFLAGS
2426 @ovindex FFLAGS
2427 Debugging and optimization options for the Fortran 77 compiler.  If it
2428 is not set in the environment when @command{configure} runs, the default
2429 value is set when you call @code{AC_PROG_F77} (or empty if you don't).
2430 @command{configure} uses this variable when compiling or linking
2431 programs to test for Fortran 77 features.
2432 @end defvar
2434 @defvar LDFLAGS
2435 @ovindex LDFLAGS
2436 Options for the linker.  If it is not set
2437 in the environment when @command{configure} runs, the default value is empty.
2438 @command{configure} uses this variable when linking programs to test for
2439 C, C++, Objective C, and Fortran features.
2441 This variable's contents should contain options like @option{-s} and
2442 @option{-L} that affect only the behavior of the linker.  Please see the
2443 explanation of @code{CFLAGS} for what you can do if an option also
2444 affects other phases of the compiler.
2446 Don't use this variable to pass library names
2447 (@option{-l}) to the linker; use @code{LIBS} instead.
2448 @end defvar
2450 @defvar LIBS
2451 @ovindex LIBS
2452 @option{-l} options to pass to the linker.  The default value is empty,
2453 but some Autoconf macros may prepend extra libraries to this variable if
2454 those libraries are found and provide necessary functions, see
2455 @ref{Libraries}.  @command{configure} uses this variable when linking
2456 programs to test for C, C++, and Fortran features.
2457 @end defvar
2459 @defvar OBJCFLAGS
2460 @ovindex OBJCFLAGS
2461 Debugging and optimization options for the Objective C compiler.  It
2462 acts like @code{CFLAGS}, but for Objective C instead of C.
2463 @end defvar
2465 @defvar builddir
2466 @ovindex builddir
2467 Rigorously equal to @samp{.}.  Added for symmetry only.
2468 @end defvar
2470 @defvar abs_builddir
2471 @ovindex abs_builddir
2472 Absolute name of @code{builddir}.
2473 @end defvar
2475 @defvar top_builddir
2476 @ovindex top_builddir
2477 The relative name of the top level of the current build tree.  In the
2478 top-level directory, this is the same as @code{builddir}.
2479 @end defvar
2481 @defvar top_build_prefix
2482 @ovindex top_build_prefix
2483 The relative name of the top level of the current build tree with final
2484 slash if nonemtpy.  This is the same as @code{top_builddir}, except that
2485 it contains of zero of more runs of @code{../}, so it should not be
2486 appended with a slash for concatenation.  This helps for @command{make}
2487 implementations that otherwise do not treat @file{./file} and @file{file}
2488 as equal in the toplevel build directory.
2489 @end defvar
2491 @defvar abs_top_builddir
2492 @ovindex abs_top_builddir
2493 Absolute name of @code{top_builddir}.
2494 @end defvar
2496 @defvar srcdir
2497 @ovindex srcdir
2498 The name of the directory that contains the source code for
2499 that makefile.
2500 @end defvar
2502 @defvar abs_srcdir
2503 @ovindex abs_srcdir
2504 Absolute name of @code{srcdir}.
2505 @end defvar
2507 @defvar top_srcdir
2508 @ovindex top_srcdir
2509 The name of the top-level source code directory for the
2510 package.  In the top-level directory, this is the same as @code{srcdir}.
2511 @end defvar
2513 @defvar abs_top_srcdir
2514 @ovindex abs_top_srcdir
2515 Absolute name of @code{top_srcdir}.
2516 @end defvar
2518 @node Installation Directory Variables
2519 @subsection Installation Directory Variables
2520 @cindex Installation directories
2521 @cindex Directories, installation
2523 The following variables specify the directories for
2524 package installation, see @ref{Directory Variables, , Variables for
2525 Installation Directories, standards, The @acronym{GNU} Coding
2526 Standards}, for more information.  Each variable corresponds to an
2527 argument of @command{configure}; trailing slashes are stripped so that
2528 expressions such as @samp{$@{prefix@}/lib} expand with only one slash
2529 between directory names.  See the end of this section for
2530 details on when and how to use these variables.
2532 @defvar bindir
2533 @ovindex bindir
2534 The directory for installing executables that users run.
2535 @end defvar
2537 @defvar datadir
2538 @ovindex datadir
2539 The directory for installing idiosyncratic read-only
2540 architecture-independent data.
2541 @end defvar
2543 @defvar datarootdir
2544 @ovindex datarootdir
2545 The root of the directory tree for read-only architecture-independent
2546 data files.
2547 @end defvar
2549 @defvar docdir
2550 @ovindex docdir
2551 The directory for installing documentation files (other than Info and
2552 man).
2553 @end defvar
2555 @defvar dvidir
2556 @ovindex dvidir
2557 The directory for installing documentation files in DVI format.
2558 @end defvar
2560 @defvar exec_prefix
2561 @ovindex exec_prefix
2562 The installation prefix for architecture-dependent files.  By default
2563 it's the same as @var{prefix}.  You should avoid installing anything
2564 directly to @var{exec_prefix}.  However, the default value for
2565 directories containing architecture-dependent files should be relative
2566 to @var{exec_prefix}.
2567 @end defvar
2569 @defvar htmldir
2570 @ovindex htmldir
2571 The directory for installing HTML documentation.
2572 @end defvar
2574 @defvar includedir
2575 @ovindex includedir
2576 The directory for installing C header files.
2577 @end defvar
2579 @defvar infodir
2580 @ovindex infodir
2581 The directory for installing documentation in Info format.
2582 @end defvar
2584 @defvar libdir
2585 @ovindex libdir
2586 The directory for installing object code libraries.
2587 @end defvar
2589 @defvar libexecdir
2590 @ovindex libexecdir
2591 The directory for installing executables that other programs run.
2592 @end defvar
2594 @defvar localedir
2595 @ovindex localedir
2596 The directory for installing locale-dependent but
2597 architecture-independent data, such as message catalogs.  This directory
2598 usually has a subdirectory per locale.
2599 @end defvar
2601 @defvar localstatedir
2602 @ovindex localstatedir
2603 The directory for installing modifiable single-machine data.
2604 @end defvar
2606 @defvar mandir
2607 @ovindex mandir
2608 The top-level directory for installing documentation in man format.
2609 @end defvar
2611 @defvar oldincludedir
2612 @ovindex oldincludedir
2613 The directory for installing C header files for non-@acronym{GCC} compilers.
2614 @end defvar
2616 @defvar pdfdir
2617 @ovindex pdfdir
2618 The directory for installing PDF documentation.
2619 @end defvar
2621 @defvar prefix
2622 @ovindex prefix
2623 The common installation prefix for all files.  If @var{exec_prefix}
2624 is defined to a different value, @var{prefix} is used only for
2625 architecture-independent files.
2626 @end defvar
2628 @defvar psdir
2629 @ovindex psdir
2630 The directory for installing PostScript documentation.
2631 @end defvar
2633 @defvar sbindir
2634 @ovindex sbindir
2635 The directory for installing executables that system
2636 administrators run.
2637 @end defvar
2639 @defvar sharedstatedir
2640 @ovindex sharedstatedir
2641 The directory for installing modifiable architecture-independent data.
2642 @end defvar
2644 @defvar sysconfdir
2645 @ovindex sysconfdir
2646 The directory for installing read-only single-machine data.
2647 @end defvar
2650 Most of these variables have values that rely on @code{prefix} or
2651 @code{exec_prefix}.  It is deliberate that the directory output
2652 variables keep them unexpanded: typically @samp{@@datarootdir@@} is
2653 replaced by @samp{$@{prefix@}/share}, not @samp{/usr/local/share}, and
2654 @samp{@@datadir@@} is replaced by @samp{$@{datarootdir@}}.
2656 This behavior is mandated by the @acronym{GNU} coding standards, so that when
2657 the user runs:
2659 @table @samp
2660 @item make
2661 she can still specify a different prefix from the one specified to
2662 @command{configure}, in which case, if needed, the package should hard
2663 code dependencies corresponding to the make-specified prefix.
2665 @item make install
2666 she can specify a different installation location, in which case the
2667 package @emph{must} still depend on the location which was compiled in
2668 (i.e., never recompile when @samp{make install} is run).  This is an
2669 extremely important feature, as many people may decide to install all
2670 the files of a package grouped together, and then install links from
2671 the final locations to there.
2672 @end table
2674 In order to support these features, it is essential that
2675 @code{datarootdir} remains being defined as @samp{$@{prefix@}/share} to
2676 depend upon the current value of @code{prefix}.
2678 A corollary is that you should not use these variables except in
2679 makefiles.  For instance, instead of trying to evaluate @code{datadir}
2680 in @file{configure} and hard-coding it in makefiles using
2681 e.g., @samp{AC_DEFINE_UNQUOTED([DATADIR], ["$datadir"], [Data directory.])},
2682 you should add
2683 @option{-DDATADIR='$(datadir)'} to your makefile's definition of
2684 @code{CPPFLAGS} (@code{AM_CPPFLAGS} if you are also using Automake).
2686 Similarly, you should not rely on @code{AC_CONFIG_FILES} to replace
2687 @code{datadir} and friends in your shell scripts and other files; instead,
2688 let @command{make} manage their replacement.  For instance Autoconf
2689 ships templates of its shell scripts ending with @samp{.in}, and uses a
2690 makefile snippet similar to the following to build scripts like
2691 @command{autoheader} and @command{autom4te}:
2693 @example
2694 @group
2695 edit = sed \
2696         -e 's|@@datadir[@@]|$(pkgdatadir)|g' \
2697         -e 's|@@prefix[@@]|$(prefix)|g'
2698 @end group
2700 @group
2701 autoheader autom4te: Makefile
2702         rm -f $@@ $@@.tmp
2703         $(edit) '$(srcdir)/$@@.in' >$@@.tmp
2704         chmod +x $@@.tmp
2705         chmod a-w $@@.tmp
2706         mv $@@.tmp $@@
2707 @end group
2709 @group
2710 autoheader: $(srcdir)/autoheader.in
2711 autom4te: $(srcdir)/autom4te.in
2712 @end group
2713 @end example
2715 Some details are noteworthy:
2717 @table @asis
2718 @item @samp{@@datadir[@@]}
2719 The brackets prevent @command{configure} from replacing
2720 @samp{@@datadir@@} in the Sed expression itself.
2721 Brackets are preferable to a backslash here, since
2722 Posix says @samp{\@@} is not portable.
2724 @item @samp{$(pkgdatadir)}
2725 Don't use @samp{@@pkgdatadir@@}!  Use the matching makefile variable
2726 instead.
2728 @item @samp{/}
2729 Don't use @samp{/} in the Sed expressions that replace file names since
2730 most likely the
2731 variables you use, such as @samp{$(pkgdatadir)}, contain @samp{/}.
2732 Use a shell metacharacter instead, such as @samp{|}.
2734 @item special characters
2735 File names, file name components, and the value of @code{VPATH} should
2736 not contain shell metacharacters or white
2737 space.  @xref{Special Chars in Variables}.
2739 @item dependency on @file{Makefile}
2740 Since @code{edit} uses values that depend on the configuration specific
2741 values (@code{prefix}, etc.)@: and not only on @code{VERSION} and so forth,
2742 the output depends on @file{Makefile}, not @file{configure.ac}.
2744 @item @samp{$@@}
2745 The main rule is generic, and uses @samp{$@@} extensively to
2746 avoid the need for multiple copies of the rule.
2748 @item Separated dependencies and single suffix rules
2749 You can't use them!  The above snippet cannot be (portably) rewritten
2752 @example
2753 autoconf autoheader: Makefile
2754 @group
2755 .in:
2756         rm -f $@@ $@@.tmp
2757         $(edit) $< >$@@.tmp
2758         chmod +x $@@.tmp
2759         mv $@@.tmp $@@
2760 @end group
2761 @end example
2763 @xref{Single Suffix Rules}, for details.
2765 @item @samp{$(srcdir)}
2766 Be sure to specify the name of the source directory,
2767 otherwise the package won't support separated builds.
2768 @end table
2770 For the more specific installation of Erlang libraries, the following variables
2771 are defined:
2773 @defvar ERLANG_INSTALL_LIB_DIR
2774 @ovindex ERLANG_INSTALL_LIB_DIR
2775 @acindex{ERLANG_SUBST_INSTALL_LIB_DIR}
2776 The common parent directory of Erlang library installation directories.
2777 This variable is set by calling the @code{AC_ERLANG_SUBST_INSTALL_LIB_DIR}
2778 macro in @file{configure.ac}.
2779 @end defvar
2781 @defvar ERLANG_INSTALL_LIB_DIR_@var{library}
2782 @ovindex ERLANG_INSTALL_LIB_DIR_@var{library}
2783 @acindex{ERLANG_SUBST_INSTALL_LIB_SUBDIR}
2784 The installation directory for Erlang library @var{library}.
2785 This variable is set by calling the
2786 @samp{AC_ERLANG_SUBST_INSTALL_LIB_SUBDIR(@var{library}, @var{version}}
2787 macro in @file{configure.ac}.
2788 @end defvar
2790 @xref{Erlang Libraries}, for details.
2793 @node Changed Directory Variables
2794 @subsection Changed Directory Variables
2795 @cindex @file{datarootdir}
2797 In Autoconf 2.60, the set of directory variables has changed, and the
2798 defaults of some variables have been adjusted
2799 (@pxref{Installation Directory Variables}) to changes in the
2800 @acronym{GNU} Coding Standards.  Notably, @file{datadir}, @file{infodir}, and
2801 @file{mandir} are now expressed in terms of @file{datarootdir}.  If you are
2802 upgrading from an earlier Autoconf version, you may need to adjust your files
2803 to ensure that the directory variables are substituted correctly
2804 (@pxref{Defining Directories}), and that a definition of @file{datarootdir} is
2805 in place.  For example, in a @file{Makefile.in}, adding
2807 @example
2808 datarootdir = @@datarootdir@@
2809 @end example
2811 @noindent
2812 is usually sufficient.  If you use Automake to create @file{Makefile.in},
2813 it will add this for you.
2815 To help with the transition, Autoconf warns about files that seem to use
2816 @code{datarootdir} without defining it.  In some cases, it then expands
2817 the value of @code{$datarootdir} in substitutions of the directory
2818 variables.  The following example shows such a warning:
2820 @example
2821 $ @kbd{cat configure.ac}
2822 AC_INIT
2823 AC_CONFIG_FILES([Makefile])
2824 AC_OUTPUT
2825 $ @kbd{cat Makefile.in}
2826 prefix = @@prefix@@
2827 datadir = @@datadir@@
2828 $ @kbd{autoconf}
2829 $ @kbd{configure}
2830 configure: creating ./config.status
2831 config.status: creating Makefile
2832 config.status: WARNING:
2833                Makefile.in seems to ignore the --datarootdir setting
2834 $ @kbd{cat Makefile}
2835 prefix = /usr/local
2836 datadir = $@{prefix@}/share
2837 @end example
2839 Usually one can easily change the file to accommodate both older and newer
2840 Autoconf releases:
2842 @example
2843 $ @kbd{cat Makefile.in}
2844 prefix = @@prefix@@
2845 datarootdir = @@datarootdir@@
2846 datadir = @@datadir@@
2847 $ @kbd{configure}
2848 configure: creating ./config.status
2849 config.status: creating Makefile
2850 $ @kbd{cat Makefile}
2851 prefix = /usr/local
2852 datarootdir = $@{prefix@}/share
2853 datadir = $@{datarootdir@}
2854 @end example
2856 @acindex{DATAROOTDIR_CHECKED}
2857 In some cases, however, the checks may not be able to detect that a suitable
2858 initialization of @code{datarootdir} is in place, or they may fail to detect
2859 that such an initialization is necessary in the output file.  If, after
2860 auditing your package, there are still spurious @file{configure} warnings about
2861 @code{datarootdir}, you may add the line
2863 @example
2864 AC_DEFUN([AC_DATAROOTDIR_CHECKED])
2865 @end example
2867 @noindent
2868 to your @file{configure.ac} to disable the warnings.  This is an exception
2869 to the usual rule that you should not define a macro whose name begins with
2870 @code{AC_} (@pxref{Macro Names}).
2874 @node Build Directories
2875 @subsection Build Directories
2876 @cindex Build directories
2877 @cindex Directories, build
2879 You can support compiling a software package for several architectures
2880 simultaneously from the same copy of the source code.  The object files
2881 for each architecture are kept in their own directory.
2883 To support doing this, @command{make} uses the @code{VPATH} variable to
2884 find the files that are in the source directory.  @acronym{GNU} Make
2885 can do this.  Most other recent @command{make} programs can do this as
2886 well, though they may have difficulties and it is often simpler to
2887 recommend @acronym{GNU} @command{make} (@pxref{VPATH and Make}).  Older
2888 @command{make} programs do not support @code{VPATH}; when using them, the
2889 source code must be in the same directory as the object files.
2891 To support @code{VPATH}, each @file{Makefile.in} should contain two
2892 lines that look like:
2894 @example
2895 srcdir = @@srcdir@@
2896 VPATH = @@srcdir@@
2897 @end example
2899 Do not set @code{VPATH} to the value of another variable, for example
2900 @samp{VPATH = $(srcdir)}, because some versions of @command{make} do not do
2901 variable substitutions on the value of @code{VPATH}.
2903 @command{configure} substitutes the correct value for @code{srcdir} when
2904 it produces @file{Makefile}.
2906 Do not use the @code{make} variable @code{$<}, which expands to the
2907 file name of the file in the source directory (found with @code{VPATH}),
2908 except in implicit rules.  (An implicit rule is one such as @samp{.c.o},
2909 which tells how to create a @file{.o} file from a @file{.c} file.)  Some
2910 versions of @command{make} do not set @code{$<} in explicit rules; they
2911 expand it to an empty value.
2913 Instead, Make command lines should always refer to source
2914 files by prefixing them with @samp{$(srcdir)/}.  For example:
2916 @example
2917 time.info: time.texinfo
2918         $(MAKEINFO) '$(srcdir)/time.texinfo'
2919 @end example
2921 @node Automatic Remaking
2922 @subsection Automatic Remaking
2923 @cindex Automatic remaking
2924 @cindex Remaking automatically
2926 You can put rules like the following in the top-level @file{Makefile.in}
2927 for a package to automatically update the configuration information when
2928 you change the configuration files.  This example includes all of the
2929 optional files, such as @file{aclocal.m4} and those related to
2930 configuration header files.  Omit from the @file{Makefile.in} rules for
2931 any of these files that your package does not use.
2933 The @samp{$(srcdir)/} prefix is included because of limitations in the
2934 @code{VPATH} mechanism.
2936 The @file{stamp-} files are necessary because the timestamps of
2937 @file{config.h.in} and @file{config.h} are not changed if remaking
2938 them does not change their contents.  This feature avoids unnecessary
2939 recompilation.  You should include the file @file{stamp-h.in} your
2940 package's distribution, so that @command{make} considers
2941 @file{config.h.in} up to date.  Don't use @command{touch}
2942 (@pxref{Limitations of Usual Tools}); instead, use @command{echo} (using
2943 @command{date} would cause needless differences, hence @acronym{CVS}
2944 conflicts, etc.).
2946 @example
2947 @group
2948 $(srcdir)/configure: configure.ac aclocal.m4
2949         cd '$(srcdir)' && autoconf
2951 # autoheader might not change config.h.in, so touch a stamp file.
2952 $(srcdir)/config.h.in: stamp-h.in
2953 $(srcdir)/stamp-h.in: configure.ac aclocal.m4
2954         cd '$(srcdir)' && autoheader
2955         echo timestamp > '$(srcdir)/stamp-h.in'
2957 config.h: stamp-h
2958 stamp-h: config.h.in config.status
2959         ./config.status
2961 Makefile: Makefile.in config.status
2962         ./config.status
2964 config.status: configure
2965         ./config.status --recheck
2966 @end group
2967 @end example
2969 @noindent
2970 (Be careful if you copy these lines directly into your makefile, as you
2971 need to convert the indented lines to start with the tab character.)
2973 In addition, you should use
2975 @example
2976 AC_CONFIG_FILES([stamp-h], [echo timestamp > stamp-h])
2977 @end example
2979 @noindent
2980 so @file{config.status} ensures that @file{config.h} is considered up to
2981 date.  @xref{Output}, for more information about @code{AC_OUTPUT}.
2983 @xref{config.status Invocation}, for more examples of handling
2984 configuration-related dependencies.
2986 @node Configuration Headers
2987 @section Configuration Header Files
2988 @cindex Configuration Header
2989 @cindex @file{config.h}
2991 When a package contains more than a few tests that define C preprocessor
2992 symbols, the command lines to pass @option{-D} options to the compiler
2993 can get quite long.  This causes two problems.  One is that the
2994 @command{make} output is hard to visually scan for errors.  More
2995 seriously, the command lines can exceed the length limits of some
2996 operating systems.  As an alternative to passing @option{-D} options to
2997 the compiler, @command{configure} scripts can create a C header file
2998 containing @samp{#define} directives.  The @code{AC_CONFIG_HEADERS}
2999 macro selects this kind of output.  Though it can be called anywhere
3000 between @code{AC_INIT} and @code{AC_OUTPUT}, it is customary to call
3001 it right after @code{AC_INIT}.
3003 The package should @samp{#include} the configuration header file before
3004 any other header files, to prevent inconsistencies in declarations (for
3005 example, if it redefines @code{const}).
3007 To provide for VPATH builds, remember to pass the C compiler a @option{-I.}
3008 option (or @option{-I..}; whichever directory contains @file{config.h}).
3009 Even if you use @samp{#include "config.h"}, the preprocessor searches only
3010 the directory of the currently read file, i.e., the source directory, not
3011 the build directory.
3013 With the appropriate @option{-I} option, you can use
3014 @samp{#include <config.h>}.  Actually, it's a good habit to use it,
3015 because in the rare case when the source directory contains another
3016 @file{config.h}, the build directory should be searched first.
3019 @defmac AC_CONFIG_HEADERS (@var{header} @dots{}, @ovar{cmds}, @ovar{init-cmds})
3020 @acindex{CONFIG_HEADERS}
3021 @cvindex HAVE_CONFIG_H
3022 This macro is one of the instantiating macros; see @ref{Configuration
3023 Actions}.  Make @code{AC_OUTPUT} create the file(s) in the
3024 blank-or-newline-separated list @var{header} containing C preprocessor
3025 @code{#define} statements, and replace @samp{@@DEFS@@} in generated
3026 files with @option{-DHAVE_CONFIG_H} instead of the value of @code{DEFS}.
3027 The usual name for @var{header} is @file{config.h}.
3029 If @var{header} already exists and its contents are identical to what
3030 @code{AC_OUTPUT} would put in it, it is left alone.  Doing this allows
3031 making some changes in the configuration without needlessly causing
3032 object files that depend on the header file to be recompiled.
3034 Usually the input file is named @file{@var{header}.in}; however, you can
3035 override the input file name by appending to @var{header} a
3036 colon-separated list of input files.  For example, you might need to make
3037 the input file name acceptable to @acronym{DOS} variants:
3039 @example
3040 AC_CONFIG_HEADERS([config.h:config.hin])
3041 @end example
3043 @end defmac
3045 @defmac AH_HEADER
3046 @ahindex{HEADER}
3047 This macro is defined as the name of the first declared config header
3048 and undefined if no config headers have been declared up to this point.
3049 A third-party macro may, for example, require use of a config header
3050 without invoking AC_CONFIG_HEADERS twice, like this:
3052 @example
3053 AC_CONFIG_COMMANDS_PRE(
3054         [m4_ifndef([AH_HEADER], [AC_CONFIG_HEADERS([config.h])])])
3055 @end example
3057 @end defmac
3059 @xref{Configuration Actions}, for more details on @var{header}.
3061 @menu
3062 * Header Templates::            Input for the configuration headers
3063 * autoheader Invocation::       How to create configuration templates
3064 * Autoheader Macros::           How to specify CPP templates
3065 @end menu
3067 @node Header Templates
3068 @subsection Configuration Header Templates
3069 @cindex Configuration Header Template
3070 @cindex Header templates
3071 @cindex @file{config.h.in}
3073 Your distribution should contain a template file that looks as you want
3074 the final header file to look, including comments, with @code{#undef}
3075 statements which are used as hooks.  For example, suppose your
3076 @file{configure.ac} makes these calls:
3078 @example
3079 AC_CONFIG_HEADERS([conf.h])
3080 AC_CHECK_HEADERS([unistd.h])
3081 @end example
3083 @noindent
3084 Then you could have code like the following in @file{conf.h.in}.  On
3085 systems that have @file{unistd.h}, @command{configure} defines
3086 @samp{HAVE_UNISTD_H} to 1.  On other systems, the whole line is
3087 commented out (in case the system predefines that symbol).
3089 @example
3090 @group
3091 /* Define as 1 if you have unistd.h.  */
3092 #undef HAVE_UNISTD_H
3093 @end group
3094 @end example
3096 Pay attention that @samp{#undef} is in the first column, and there is
3097 nothing after @samp{HAVE_UNISTD_H}, not even white space.  You can
3098 then decode the configuration header using the preprocessor directives:
3100 @example
3101 @group
3102 #include <conf.h>
3104 #ifdef HAVE_UNISTD_H
3105 # include <unistd.h>
3106 #else
3107 /* We are in trouble.  */
3108 #endif
3109 @end group
3110 @end example
3112 The use of old form templates, with @samp{#define} instead of
3113 @samp{#undef} is strongly discouraged.  Similarly with old templates
3114 with comments on the same line as the @samp{#undef}.  Anyway, putting
3115 comments in preprocessor macros has never been a good idea.
3117 Since it is a tedious task to keep a template header up to date, you may
3118 use @command{autoheader} to generate it, see @ref{autoheader Invocation}.
3121 @node autoheader Invocation
3122 @subsection Using @command{autoheader} to Create @file{config.h.in}
3123 @cindex @command{autoheader}
3125 The @command{autoheader} program can create a template file of C
3126 @samp{#define} statements for @command{configure} to use.
3127 It searches for the first invocation of @code{AC_CONFIG_HEADERS} in
3128 @file{configure} sources to determine the name of the template.
3129 (If the first call of @code{AC_CONFIG_HEADERS} specifies more than one
3130 input file name, @command{autoheader} uses the first one.)
3132 It is recommended that only one input file is used.  If you want to append
3133 a boilerplate code, it is preferable to use
3134 @samp{AH_BOTTOM([#include <conf_post.h>])}.
3135 File @file{conf_post.h} is not processed during the configuration then,
3136 which make things clearer.  Analogically, @code{AH_TOP} can be used to
3137 prepend a boilerplate code.
3139 In order to do its job, @command{autoheader} needs you to document all
3140 of the symbols that you might use.  Typically this is done via an
3141 @code{AC_DEFINE} or @code{AC_DEFINE_UNQUOTED} call whose first argument
3142 is a literal symbol and whose third argument describes the symbol
3143 (@pxref{Defining Symbols}).  Alternatively, you can use
3144 @code{AH_TEMPLATE} (@pxref{Autoheader Macros}), or you can supply a
3145 suitable input file for a subsequent configuration header file.
3146 Symbols defined by Autoconf's builtin tests are already documented properly;
3147 you need to document only those that you
3148 define yourself.
3150 You might wonder why @command{autoheader} is needed: after all, why
3151 would @command{configure} need to ``patch'' a @file{config.h.in} to
3152 produce a @file{config.h} instead of just creating @file{config.h} from
3153 scratch?  Well, when everything rocks, the answer is just that we are
3154 wasting our time maintaining @command{autoheader}: generating
3155 @file{config.h} directly is all that is needed.  When things go wrong,
3156 however, you'll be thankful for the existence of @command{autoheader}.
3158 The fact that the symbols are documented is important in order to
3159 @emph{check} that @file{config.h} makes sense.  The fact that there is a
3160 well-defined list of symbols that should be defined (or not) is
3161 also important for people who are porting packages to environments where
3162 @command{configure} cannot be run: they just have to @emph{fill in the
3163 blanks}.
3165 But let's come back to the point: the invocation of @command{autoheader}@dots{}
3167 If you give @command{autoheader} an argument, it uses that file instead
3168 of @file{configure.ac} and writes the header file to the standard output
3169 instead of to @file{config.h.in}.  If you give @command{autoheader} an
3170 argument of @option{-}, it reads the standard input instead of
3171 @file{configure.ac} and writes the header file to the standard output.
3173 @command{autoheader} accepts the following options:
3175 @table @option
3176 @item --help
3177 @itemx -h
3178 Print a summary of the command line options and exit.
3180 @item --version
3181 @itemx -V
3182 Print the version number of Autoconf and exit.
3184 @item --verbose
3185 @itemx -v
3186 Report processing steps.
3188 @item --debug
3189 @itemx -d
3190 Don't remove the temporary files.
3192 @item --force
3193 @itemx -f
3194 Remake the template file even if newer than its input files.
3196 @item --include=@var{dir}
3197 @itemx -I @var{dir}
3198 Append @var{dir} to the include path.  Multiple invocations accumulate.
3200 @item --prepend-include=@var{dir}
3201 @item -B @var{dir}
3202 Prepend @var{dir} to the include path.  Multiple invocations accumulate.
3204 @item --warnings=@var{category}
3205 @itemx -W @var{category}
3206 @evindex WARNINGS
3207 Report the warnings related to @var{category} (which can actually be a
3208 comma separated list).  Current categories include:
3210 @table @samp
3211 @item obsolete
3212 report the uses of obsolete constructs
3214 @item all
3215 report all the warnings
3217 @item none
3218 report none
3220 @item error
3221 treats warnings as errors
3223 @item no-@var{category}
3224 disable warnings falling into @var{category}
3225 @end table
3227 @end table
3231 @node Autoheader Macros
3232 @subsection Autoheader Macros
3233 @cindex Autoheader macros
3235 @command{autoheader} scans @file{configure.ac} and figures out which C
3236 preprocessor symbols it might define.  It knows how to generate
3237 templates for symbols defined by @code{AC_CHECK_HEADERS},
3238 @code{AC_CHECK_FUNCS} etc., but if you @code{AC_DEFINE} any additional
3239 symbol, you must define a template for it.  If there are missing
3240 templates, @command{autoheader} fails with an error message.
3242 The template for a @var{symbol} is created
3243 by @command{autoheader} from
3244 the @var{description} argument to an @code{AC_DEFINE};
3245 see @ref{Defining Symbols}.
3247 For special needs, you can use the following macros.
3250 @defmac AH_TEMPLATE (@var{key}, @var{description})
3251 @ahindex{TEMPLATE}
3252 Tell @command{autoheader} to generate a template for @var{key}.  This macro
3253 generates standard templates just like @code{AC_DEFINE} when a
3254 @var{description} is given.
3256 For example:
3258 @example
3259 AH_TEMPLATE([CRAY_STACKSEG_END],
3260             [Define to one of _getb67, GETB67, getb67
3261              for Cray-2 and Cray-YMP systems.  This
3262              function is required for alloca.c support
3263              on those systems.])
3264 @end example
3266 @noindent
3267 generates the following template, with the description properly
3268 justified.
3270 @example
3271 /* Define to one of _getb67, GETB67, getb67 for Cray-2 and
3272    Cray-YMP systems.  This function is required for alloca.c
3273    support on those systems.  */
3274 #undef CRAY_STACKSEG_END
3275 @end example
3276 @end defmac
3279 @defmac AH_VERBATIM (@var{key}, @var{template})
3280 @ahindex{VERBATIM}
3281 Tell @command{autoheader} to include the @var{template} as-is in the header
3282 template file.  This @var{template} is associated with the @var{key},
3283 which is used to sort all the different templates and guarantee their
3284 uniqueness.  It should be a symbol that can be defined via @code{AC_DEFINE}.
3285 @end defmac
3288 @defmac AH_TOP (@var{text})
3289 @ahindex{TOP}
3290 Include @var{text} at the top of the header template file.
3291 @end defmac
3294 @defmac AH_BOTTOM (@var{text})
3295 @ahindex{BOTTOM}
3296 Include @var{text} at the bottom of the header template file.
3297 @end defmac
3300 Please note that @var{text} gets included ``verbatim'' to the template file,
3301 not to the resulting config header, so it can easily get mangled when the
3302 template is processed.  There is rarely a need for something other than
3304 @example
3305 AH_BOTTOM([#include <custom.h>])
3306 @end example
3310 @node Configuration Commands
3311 @section Running Arbitrary Configuration Commands
3312 @cindex Configuration commands
3313 @cindex Commands for configuration
3315 You can execute arbitrary commands before, during, and after
3316 @file{config.status} is run.  The three following macros accumulate the
3317 commands to run when they are called multiple times.
3318 @code{AC_CONFIG_COMMANDS} replaces the obsolete macro
3319 @code{AC_OUTPUT_COMMANDS}; see @ref{Obsolete Macros}, for details.
3321 @anchor{AC_CONFIG_COMMANDS}
3322 @defmac AC_CONFIG_COMMANDS (@var{tag}@dots{}, @ovar{cmds}, @ovar{init-cmds})
3323 @acindex{CONFIG_COMMANDS}
3324 Specify additional shell commands to run at the end of
3325 @file{config.status}, and shell commands to initialize any variables
3326 from @command{configure}.  Associate the commands with @var{tag}.
3327 Since typically the @var{cmds} create a file, @var{tag} should
3328 naturally be the name of that file.  If needed, the directory hosting
3329 @var{tag} is created.  This macro is one of the instantiating macros;
3330 see @ref{Configuration Actions}.
3332 Here is an unrealistic example:
3333 @example
3334 fubar=42
3335 AC_CONFIG_COMMANDS([fubar],
3336                    [echo this is extra $fubar, and so on.],
3337                    [fubar=$fubar])
3338 @end example
3340 Here is a better one:
3341 @example
3342 AC_CONFIG_COMMANDS([timestamp], [date >timestamp])
3343 @end example
3344 @end defmac
3346 The following two macros look similar, but in fact they are not of the same
3347 breed: they are executed directly by @file{configure}, so you cannot use
3348 @file{config.status} to rerun them.
3350 @c Yet it is good to leave them here.  The user sees them together and
3351 @c decides which best fits their needs.
3353 @defmac AC_CONFIG_COMMANDS_PRE (@var{cmds})
3354 @acindex{CONFIG_COMMANDS_PRE}
3355 Execute the @var{cmds} right before creating @file{config.status}.
3357 This macro presents the last opportunity to call @code{AC_SUBST},
3358 @code{AC_DEFINE}, or @code{AC_CONFIG_FOOS} macros.
3359 @end defmac
3361 @defmac AC_CONFIG_COMMANDS_POST (@var{cmds})
3362 @acindex{CONFIG_COMMANDS_POST}
3363 Execute the @var{cmds} right after creating @file{config.status}.
3364 @end defmac
3369 @node Configuration Links
3370 @section Creating Configuration Links
3371 @cindex Configuration links
3372 @cindex Links for configuration
3374 You may find it convenient to create links whose destinations depend upon
3375 results of tests.  One can use @code{AC_CONFIG_COMMANDS} but the
3376 creation of relative symbolic links can be delicate when the package is
3377 built in a directory different from the source directory.
3379 @anchor{AC_CONFIG_LINKS}
3380 @defmac AC_CONFIG_LINKS (@var{dest}:@var{source}@dots{}, @ovar{cmds}, @
3381   @ovar{init-cmds})
3382 @acindex{CONFIG_LINKS}
3383 @cindex Links
3384 Make @code{AC_OUTPUT} link each of the existing files @var{source} to
3385 the corresponding link name @var{dest}.  Makes a symbolic link if
3386 possible, otherwise a hard link if possible, otherwise a copy.  The
3387 @var{dest} and @var{source} names should be relative to the top level
3388 source or build directory.  This macro is one of the instantiating
3389 macros; see @ref{Configuration Actions}.
3391 For example, this call:
3393 @example
3394 AC_CONFIG_LINKS([host.h:config/$machine.h
3395                 object.h:config/$obj_format.h])
3396 @end example
3398 @noindent
3399 creates in the current directory @file{host.h} as a link to
3400 @file{@var{srcdir}/config/$machine.h}, and @file{object.h} as a
3401 link to @file{@var{srcdir}/config/$obj_format.h}.
3403 The tempting value @samp{.} for @var{dest} is invalid: it makes it
3404 impossible for @samp{config.status} to guess the links to establish.
3406 One can then run:
3407 @example
3408 ./config.status host.h object.h
3409 @end example
3410 @noindent
3411 to create the links.
3412 @end defmac
3416 @node Subdirectories
3417 @section Configuring Other Packages in Subdirectories
3418 @cindex Configure subdirectories
3419 @cindex Subdirectory configure
3421 In most situations, calling @code{AC_OUTPUT} is sufficient to produce
3422 makefiles in subdirectories.  However, @command{configure} scripts
3423 that control more than one independent package can use
3424 @code{AC_CONFIG_SUBDIRS} to run @command{configure} scripts for other
3425 packages in subdirectories.
3427 @defmac AC_CONFIG_SUBDIRS (@var{dir} @dots{})
3428 @acindex{CONFIG_SUBDIRS}
3429 @ovindex subdirs
3430 Make @code{AC_OUTPUT} run @command{configure} in each subdirectory
3431 @var{dir} in the given blank-or-newline-separated list.  Each @var{dir} should
3432 be a literal, i.e., please do not use:
3434 @example
3435 if test "$package_foo_enabled" = yes; then
3436   $my_subdirs="$my_subdirs foo"
3438 AC_CONFIG_SUBDIRS([$my_subdirs])
3439 @end example
3441 @noindent
3442 because this prevents @samp{./configure --help=recursive} from
3443 displaying the options of the package @code{foo}.  Instead, you should
3444 write:
3446 @example
3447 if test "$package_foo_enabled" = yes; then
3448   AC_CONFIG_SUBDIRS([foo])
3450 @end example
3452 If a given @var{dir} is not found, an error is reported: if the
3453 subdirectory is optional, write:
3455 @example
3456 if test -d "$srcdir/foo"; then
3457   AC_CONFIG_SUBDIRS([foo])
3459 @end example
3461 @c NB: Yes, below we mean configure.in, not configure.ac.
3462 If a given @var{dir} contains @command{configure.gnu}, it is run instead
3463 of @command{configure}.  This is for packages that might use a
3464 non-Autoconf script @command{Configure}, which can't be called through a
3465 wrapper @command{configure} since it would be the same file on
3466 case-insensitive file systems.  Likewise, if a @var{dir} contains
3467 @file{configure.in} but no @command{configure}, the Cygnus
3468 @command{configure} script found by @code{AC_CONFIG_AUX_DIR} is used.
3470 The subdirectory @command{configure} scripts are given the same command
3471 line options that were given to this @command{configure} script, with minor
3472 changes if needed, which include:
3474 @itemize @minus
3475 @item
3476 adjusting a relative name for the cache file;
3478 @item
3479 adjusting a relative name for the source directory;
3481 @item
3482 propagating the current value of @code{$prefix}, including if it was
3483 defaulted, and if the default values of the top level and of the subdirectory
3484 @file{configure} differ.
3485 @end itemize
3487 This macro also sets the output variable @code{subdirs} to the list of
3488 directories @samp{@var{dir} @dots{}}.  Make rules can use
3489 this variable to determine which subdirectories to recurse into.
3491 This macro may be called multiple times.
3492 @end defmac
3494 @node Default Prefix
3495 @section Default Prefix
3496 @cindex Install prefix
3497 @cindex Prefix for install
3499 By default, @command{configure} sets the prefix for files it installs to
3500 @file{/usr/local}.  The user of @command{configure} can select a different
3501 prefix using the @option{--prefix} and @option{--exec-prefix} options.
3502 There are two ways to change the default: when creating
3503 @command{configure}, and when running it.
3505 Some software packages might want to install in a directory other than
3506 @file{/usr/local} by default.  To accomplish that, use the
3507 @code{AC_PREFIX_DEFAULT} macro.
3509 @defmac AC_PREFIX_DEFAULT (@var{prefix})
3510 @acindex{PREFIX_DEFAULT}
3511 Set the default installation prefix to @var{prefix} instead of
3512 @file{/usr/local}.
3513 @end defmac
3515 It may be convenient for users to have @command{configure} guess the
3516 installation prefix from the location of a related program that they
3517 have already installed.  If you wish to do that, you can call
3518 @code{AC_PREFIX_PROGRAM}.
3520 @anchor{AC_PREFIX_PROGRAM}
3521 @defmac AC_PREFIX_PROGRAM (@var{program})
3522 @acindex{PREFIX_PROGRAM}
3523 If the user did not specify an installation prefix (using the
3524 @option{--prefix} option), guess a value for it by looking for
3525 @var{program} in @env{PATH}, the way the shell does.  If @var{program}
3526 is found, set the prefix to the parent of the directory containing
3527 @var{program}, else default the prefix as described above
3528 (@file{/usr/local} or @code{AC_PREFIX_DEFAULT}).  For example, if
3529 @var{program} is @code{gcc} and the @env{PATH} contains
3530 @file{/usr/local/gnu/bin/gcc}, set the prefix to @file{/usr/local/gnu}.
3531 @end defmac
3535 @c ======================================================== Existing tests
3537 @node Existing Tests
3538 @chapter Existing Tests
3540 These macros test for particular system features that packages might
3541 need or want to use.  If you need to test for a kind of feature that
3542 none of these macros check for, you can probably do it by calling
3543 primitive test macros with appropriate arguments (@pxref{Writing
3544 Tests}).
3546 These tests print messages telling the user which feature they're
3547 checking for, and what they find.  They cache their results for future
3548 @command{configure} runs (@pxref{Caching Results}).
3550 Some of these macros set output variables.  @xref{Makefile
3551 Substitutions}, for how to get their values.  The phrase ``define
3552 @var{name}'' is used below as a shorthand to mean ``define the C
3553 preprocessor symbol @var{name} to the value 1''.  @xref{Defining
3554 Symbols}, for how to get those symbol definitions into your program.
3556 @menu
3557 * Common Behavior::             Macros' standard schemes
3558 * Alternative Programs::        Selecting between alternative programs
3559 * Files::                       Checking for the existence of files
3560 * Libraries::                   Library archives that might be missing
3561 * Library Functions::           C library functions that might be missing
3562 * Header Files::                Header files that might be missing
3563 * Declarations::                Declarations that may be missing
3564 * Structures::                  Structures or members that might be missing
3565 * Types::                       Types that might be missing
3566 * Compilers and Preprocessors::  Checking for compiling programs
3567 * System Services::             Operating system services
3568 * Posix Variants::              Special kludges for specific Posix variants
3569 * Erlang Libraries::            Checking for the existence of Erlang libraries
3570 @end menu
3572 @node Common Behavior
3573 @section Common Behavior
3574 @cindex Common autoconf behavior
3576 Much effort has been expended to make Autoconf easy to learn.  The most
3577 obvious way to reach this goal is simply to enforce standard interfaces
3578 and behaviors, avoiding exceptions as much as possible.  Because of
3579 history and inertia, unfortunately, there are still too many exceptions
3580 in Autoconf; nevertheless, this section describes some of the common
3581 rules.
3583 @menu
3584 * Standard Symbols::            Symbols defined by the macros
3585 * Default Includes::            Includes used by the generic macros
3586 @end menu
3588 @node Standard Symbols
3589 @subsection Standard Symbols
3590 @cindex Standard symbols
3592 All the generic macros that @code{AC_DEFINE} a symbol as a result of
3593 their test transform their @var{argument} values to a standard alphabet.
3594 First, @var{argument} is converted to upper case and any asterisks
3595 (@samp{*}) are each converted to @samp{P}.  Any remaining characters
3596 that are not alphanumeric are converted to underscores.
3598 For instance,
3600 @example
3601 AC_CHECK_TYPES([struct $Expensive*])
3602 @end example
3604 @noindent
3605 defines the symbol @samp{HAVE_STRUCT__EXPENSIVEP} if the check
3606 succeeds.
3609 @node Default Includes
3610 @subsection Default Includes
3611 @cindex Default includes
3612 @cindex Includes, default
3614 Several tests depend upon a set of header files.  Since these headers
3615 are not universally available, tests actually have to provide a set of
3616 protected includes, such as:
3618 @example
3619 @group
3620 #ifdef TIME_WITH_SYS_TIME
3621 # include <sys/time.h>
3622 # include <time.h>
3623 #else
3624 # ifdef HAVE_SYS_TIME_H
3625 #  include <sys/time.h>
3626 # else
3627 #  include <time.h>
3628 # endif
3629 #endif
3630 @end group
3631 @end example
3633 @noindent
3634 Unless you know exactly what you are doing, you should avoid using
3635 unconditional includes, and check the existence of the headers you
3636 include beforehand (@pxref{Header Files}).
3638 Most generic macros use the following macro to provide the default set
3639 of includes:
3641 @defmac AC_INCLUDES_DEFAULT (@ovar{include-directives})
3642 @acindex{INCLUDES_DEFAULT}
3643 Expand to @var{include-directives} if defined, otherwise to:
3645 @example
3646 @group
3647 #include <stdio.h>
3648 #ifdef HAVE_SYS_TYPES_H
3649 # include <sys/types.h>
3650 #endif
3651 #ifdef HAVE_SYS_STAT_H
3652 # include <sys/stat.h>
3653 #endif
3654 #ifdef STDC_HEADERS
3655 # include <stdlib.h>
3656 # include <stddef.h>
3657 #else
3658 # ifdef HAVE_STDLIB_H
3659 #  include <stdlib.h>
3660 # endif
3661 #endif
3662 #ifdef HAVE_STRING_H
3663 # if !defined STDC_HEADERS && defined HAVE_MEMORY_H
3664 #  include <memory.h>
3665 # endif
3666 # include <string.h>
3667 #endif
3668 #ifdef HAVE_STRINGS_H
3669 # include <strings.h>
3670 #endif
3671 #ifdef HAVE_INTTYPES_H
3672 # include <inttypes.h>
3673 #endif
3674 #ifdef HAVE_STDINT_H
3675 # include <stdint.h>
3676 #endif
3677 #ifdef HAVE_UNISTD_H
3678 # include <unistd.h>
3679 #endif
3680 @end group
3681 @end example
3683 If the default includes are used, then check for the presence of these
3684 headers and their compatibility, i.e., you don't need to run
3685 @code{AC_HEADER_STDC}, nor check for @file{stdlib.h} etc.
3687 These headers are checked for in the same order as they are included.
3688 For instance, on some systems @file{string.h} and @file{strings.h} both
3689 exist, but conflict.  Then @code{HAVE_STRING_H} is defined, not
3690 @code{HAVE_STRINGS_H}.
3691 @end defmac
3693 @node Alternative Programs
3694 @section Alternative Programs
3695 @cindex Programs, checking
3697 These macros check for the presence or behavior of particular programs.
3698 They are used to choose between several alternative programs and to
3699 decide what to do once one has been chosen.  If there is no macro
3700 specifically defined to check for a program you need, and you don't need
3701 to check for any special properties of it, then you can use one of the
3702 general program-check macros.
3704 @menu
3705 * Particular Programs::         Special handling to find certain programs
3706 * Generic Programs::            How to find other programs
3707 @end menu
3709 @node Particular Programs
3710 @subsection Particular Program Checks
3712 These macros check for particular programs---whether they exist, and
3713 in some cases whether they support certain features.
3715 @defmac AC_PROG_AWK
3716 @acindex{PROG_AWK}
3717 @ovindex AWK
3718 Check for @code{gawk}, @code{mawk}, @code{nawk}, and @code{awk}, in that
3719 order, and set output variable @code{AWK} to the first one that is found.
3720 It tries @code{gawk} first because that is reported to be the
3721 best implementation.
3722 @end defmac
3724 @defmac AC_PROG_GREP
3725 @acindex{PROG_GREP}
3726 @ovindex GREP
3727 Look for the best available @code{grep} or @code{ggrep} that accepts the
3728 longest input lines possible, and that supports multiple @option{-e} options.
3729 Set the output variable @code{GREP} to whatever is chosen.
3730 @xref{Limitations of Usual Tools}, for more information about
3731 portability problems with the @command{grep} command family.
3732 @end defmac
3734 @defmac AC_PROG_EGREP
3735 @acindex{PROG_EGREP}
3736 @ovindex EGREP
3737 Check whether @code{$GREP -E} works, or else look for the best available
3738 @code{egrep} or @code{gegrep} that accepts the longest input lines possible.
3739 Set the output variable @code{EGREP} to whatever is chosen.
3740 @end defmac
3742 @defmac AC_PROG_FGREP
3743 @acindex{PROG_FGREP}
3744 @ovindex FGREP
3745 Check whether @code{$GREP -F} works, or else look for the best available
3746 @code{fgrep} or @code{gfgrep} that accepts the longest input lines possible.
3747 Set the output variable @code{FGREP} to whatever is chosen.
3748 @end defmac
3750 @defmac AC_PROG_INSTALL
3751 @acindex{PROG_INSTALL}
3752 @ovindex INSTALL
3753 @ovindex INSTALL_PROGRAM
3754 @ovindex INSTALL_DATA
3755 @ovindex INSTALL_SCRIPT
3756 Set output variable @code{INSTALL} to the name of a @acronym{BSD}-compatible
3757 @command{install} program, if one is found in the current @env{PATH}.
3758 Otherwise, set @code{INSTALL} to @samp{@var{dir}/install-sh -c},
3759 checking the directories specified to @code{AC_CONFIG_AUX_DIR} (or its
3760 default directories) to determine @var{dir} (@pxref{Output}).  Also set
3761 the variables @code{INSTALL_PROGRAM} and @code{INSTALL_SCRIPT} to
3762 @samp{$@{INSTALL@}} and @code{INSTALL_DATA} to @samp{$@{INSTALL@} -m 644}.
3764 @samp{@@INSTALL@@} is special, as its value may vary for different
3765 configuration files.
3767 This macro screens out various instances of @command{install} known not to
3768 work.  It prefers to find a C program rather than a shell script, for
3769 speed.  Instead of @file{install-sh}, it can also use @file{install.sh},
3770 but that name is obsolete because some @command{make} programs have a rule
3771 that creates @file{install} from it if there is no makefile.  Further, this
3772 macro requires @command{install} to be able to install multiple files into a
3773 target directory in a single invocation.
3775 Autoconf comes with a copy of @file{install-sh} that you can use.  If
3776 you use @code{AC_PROG_INSTALL}, you must include either
3777 @file{install-sh} or @file{install.sh} in your distribution; otherwise
3778 @command{configure} produces an error message saying it can't find
3779 them---even if the system you're on has a good @command{install} program.
3780 This check is a safety measure to prevent you from accidentally leaving
3781 that file out, which would prevent your package from installing on
3782 systems that don't have a @acronym{BSD}-compatible @command{install} program.
3784 If you need to use your own installation program because it has features
3785 not found in standard @command{install} programs, there is no reason to use
3786 @code{AC_PROG_INSTALL}; just put the file name of your program into your
3787 @file{Makefile.in} files.
3788 @end defmac
3790 @defmac AC_PROG_MKDIR_P
3791 @acindex{PROG_MKDIR_P}
3792 @ovindex MKDIR_P
3793 Set output variable @code{MKDIR_P} to a program that ensures that for
3794 each argument, a directory named by this argument exists, creating it
3795 and its parent directories if needed, and without race conditions when
3796 two instances of the program attempt to make the same directory at
3797 nearly the same time.
3799 This macro uses the @samp{mkdir -p} command if possible.  Otherwise, it
3800 falls back on invoking @command{install-sh} with the @option{-d} option,
3801 so your package should
3802 contain @file{install-sh} as described under @code{AC_PROG_INSTALL}.
3803 An @file{install-sh} file that predates Autoconf 2.60 or Automake 1.10
3804 is vulnerable to race conditions, so if you want to support parallel
3805 installs from
3806 different packages into the same directory you need to make sure you
3807 have an up-to-date @file{install-sh}.  In particular, be careful about
3808 using @samp{autoreconf -if} if your Automake predates Automake 1.10.
3810 This macro is related to the @code{AS_MKDIR_P} macro (@pxref{Programming
3811 in M4sh}), but it sets an output variable intended for use in other
3812 files, whereas @code{AS_MKDIR_P} is intended for use in scripts like
3813 @command{configure}.  Also, @code{AS_MKDIR_P} does not accept options,
3814 but @code{MKDIR_P} supports the @option{-m} option, e.g., a makefile
3815 might invoke @code{$(MKDIR_P) -m 0 dir} to create an inaccessible
3816 directory, and conversely a makefile should use @code{$(MKDIR_P) --
3817 $(FOO)} if @var{FOO} might yield a value that begins with @samp{-}.
3818 Finally, @code{AS_MKDIR_P} does not check for race condition
3819 vulnerability, whereas @code{AC_PROG_MKDIR_P} does.
3821 @samp{@@MKDIR_P@@} is special, as its value may vary for different
3822 configuration files.
3823 @end defmac
3825 @anchor{AC_PROG_LEX}
3826 @defmac AC_PROG_LEX
3827 @acindex{PROG_LEX}
3828 @ovindex LEX
3829 @ovindex LEXLIB
3830 @cvindex YYTEXT_POINTER
3831 @ovindex LEX_OUTPUT_ROOT
3832 If @code{flex} is found, set output variable @code{LEX} to @samp{flex}
3833 and @code{LEXLIB} to @option{-lfl}, if that library is in a standard
3834 place.  Otherwise set @code{LEX} to @samp{lex} and @code{LEXLIB} to
3835 @option{-ll}.
3837 Define @code{YYTEXT_POINTER} if @code{yytext} defaults to @samp{char *} instead
3838 of to @samp{char []}.  Also set output variable @code{LEX_OUTPUT_ROOT} to
3839 the base of the file name that the lexer generates; usually
3840 @file{lex.yy}, but sometimes something else.  These results vary
3841 according to whether @code{lex} or @code{flex} is being used.
3843 You are encouraged to use Flex in your sources, since it is both more
3844 pleasant to use than plain Lex and the C source it produces is portable.
3845 In order to ensure portability, however, you must either provide a
3846 function @code{yywrap} or, if you don't use it (e.g., your scanner has
3847 no @samp{#include}-like feature), simply include a @samp{%noyywrap}
3848 statement in the scanner's source.  Once this done, the scanner is
3849 portable (unless @emph{you} felt free to use nonportable constructs) and
3850 does not depend on any library.  In this case, and in this case only, it
3851 is suggested that you use this Autoconf snippet:
3853 @example
3854 AC_PROG_LEX
3855 if test "$LEX" != flex; then
3856   LEX="$SHELL $missing_dir/missing flex"
3857   AC_SUBST([LEX_OUTPUT_ROOT], [lex.yy])
3858   AC_SUBST([LEXLIB], [''])
3860 @end example
3862 The shell script @command{missing} can be found in the Automake
3863 distribution.
3865 To ensure backward compatibility, Automake's @code{AM_PROG_LEX} invokes
3866 (indirectly) this macro twice, which causes an annoying but benign
3867 ``@code{AC_PROG_LEX} invoked multiple times'' warning.  Future versions
3868 of Automake will fix this issue; meanwhile, just ignore this message.
3870 As part of running the test, this macro may delete any file in the
3871 configuration directory named @file{lex.yy.c} or @file{lexyy.c}.
3872 @end defmac
3874 @anchor{AC_PROG_LN_S}
3875 @defmac AC_PROG_LN_S
3876 @acindex{PROG_LN_S}
3877 @ovindex LN_S
3878 If @samp{ln -s} works on the current file system (the operating system
3879 and file system support symbolic links), set the output variable
3880 @code{LN_S} to @samp{ln -s}; otherwise, if @samp{ln} works, set
3881 @code{LN_S} to @samp{ln}, and otherwise set it to @samp{cp -p}.
3883 If you make a link in a directory other than the current directory, its
3884 meaning depends on whether @samp{ln} or @samp{ln -s} is used.  To safely
3885 create links using @samp{$(LN_S)}, either find out which form is used
3886 and adjust the arguments, or always invoke @code{ln} in the directory
3887 where the link is to be created.
3889 In other words, it does not work to do:
3890 @example
3891 $(LN_S) foo /x/bar
3892 @end example
3894 Instead, do:
3896 @example
3897 (cd /x && $(LN_S) foo bar)
3898 @end example
3899 @end defmac
3901 @defmac AC_PROG_RANLIB
3902 @acindex{PROG_RANLIB}
3903 @ovindex RANLIB
3904 Set output variable @code{RANLIB} to @samp{ranlib} if @code{ranlib}
3905 is found, and otherwise to @samp{:} (do nothing).
3906 @end defmac
3908 @defmac AC_PROG_SED
3909 @acindex{PROG_SED}
3910 @ovindex SED
3911 Set output variable @code{SED} to a Sed implementation that conforms to
3912 Posix and does not have arbitrary length limits.  Report an error if no
3913 acceptable Sed is found.  @xref{Limitations of Usual Tools}, for more
3914 information about portability problems with Sed.
3915 @end defmac
3917 @defmac AC_PROG_YACC
3918 @acindex{PROG_YACC}
3919 @ovindex YACC
3920 If @code{bison} is found, set output variable @code{YACC} to @samp{bison
3921 -y}.  Otherwise, if @code{byacc} is found, set @code{YACC} to
3922 @samp{byacc}.  Otherwise set @code{YACC} to @samp{yacc}.
3923 @end defmac
3925 @node Generic Programs
3926 @subsection Generic Program and File Checks
3928 These macros are used to find programs not covered by the ``particular''
3929 test macros.  If you need to check the behavior of a program as well as
3930 find out whether it is present, you have to write your own test for it
3931 (@pxref{Writing Tests}).  By default, these macros use the environment
3932 variable @env{PATH}.  If you need to check for a program that might not
3933 be in the user's @env{PATH}, you can pass a modified path to use
3934 instead, like this:
3936 @example
3937 AC_PATH_PROG([INETD], [inetd], [/usr/libexec/inetd],
3938              [$PATH$PATH_SEPARATOR/usr/libexec$PATH_SEPARATOR]dnl
3939 [/usr/sbin$PATH_SEPARATOR/usr/etc$PATH_SEPARATOR/etc])
3940 @end example
3942 You are strongly encouraged to declare the @var{variable} passed to
3943 @code{AC_CHECK_PROG} etc.@: as precious, @xref{Setting Output Variables},
3944 @code{AC_ARG_VAR}, for more details.
3946 @anchor{AC_CHECK_PROG}
3947 @defmac AC_CHECK_PROG (@var{variable}, @var{prog-to-check-for}, @
3948   @var{value-if-found}, @ovar{value-if-not-found}, @dvar{path, $PATH}, @
3949   @ovar{reject})
3950 @acindex{CHECK_PROG}
3951 Check whether program @var{prog-to-check-for} exists in @var{path}.  If
3952 it is found, set @var{variable} to @var{value-if-found}, otherwise to
3953 @var{value-if-not-found}, if given.  Always pass over @var{reject} (an
3954 absolute file name) even if it is the first found in the search path; in
3955 that case, set @var{variable} using the absolute file name of the
3956 @var{prog-to-check-for} found that is not @var{reject}.  If
3957 @var{variable} was already set, do nothing.  Calls @code{AC_SUBST} for
3958 @var{variable}.
3959 @end defmac
3961 @anchor{AC_CHECK_PROGS}
3962 @defmac AC_CHECK_PROGS (@var{variable}, @var{progs-to-check-for}, @
3963   @ovar{value-if-not-found}, @dvar{path, $PATH})
3964 @acindex{CHECK_PROGS}
3965 Check for each program in the blank-separated list
3966 @var{progs-to-check-for} existing in the @var{path}.  If one is found, set
3967 @var{variable} to the name of that program.  Otherwise, continue
3968 checking the next program in the list.  If none of the programs in the
3969 list are found, set @var{variable} to @var{value-if-not-found}; if
3970 @var{value-if-not-found} is not specified, the value of @var{variable}
3971 is not changed.  Calls @code{AC_SUBST} for @var{variable}.
3972 @end defmac
3974 @defmac AC_CHECK_TARGET_TOOL (@var{variable}, @var{prog-to-check-for}, @
3975   @ovar{value-if-not-found}, @dvar{path, $PATH})
3976 @acindex{CHECK_TARGET_TOOL}
3977 Like @code{AC_CHECK_PROG}, but first looks for @var{prog-to-check-for}
3978 with a prefix of the target type as determined by
3979 @code{AC_CANONICAL_TARGET}, followed by a dash (@pxref{Canonicalizing}).
3980 If the tool cannot be found with a prefix, and if the build and target
3981 types are equal, then it is also searched for without a prefix.
3983 As noted in @ref{Specifying Names, , Specifying the system type}, the
3984 target is rarely specified, because most of the time it is the same
3985 as the host: it is the type of system for which any compiler tool in
3986 the package produces code.  What this macro looks for is,
3987 for example, @emph{a tool @r{(assembler, linker, etc.)}@: that the
3988 compiler driver @r{(@command{gcc} for the @acronym{GNU} C Compiler)}
3989 uses to produce objects, archives or executables}.
3990 @end defmac
3992 @defmac AC_CHECK_TOOL (@var{variable}, @var{prog-to-check-for}, @
3993   @ovar{value-if-not-found}, @dvar{path, $PATH})
3994 @acindex{CHECK_TOOL}
3995 Like @code{AC_CHECK_PROG}, but first looks for @var{prog-to-check-for}
3996 with a prefix of the host type as specified by @option{--host}, followed by a
3997 dash.  For example, if the user runs
3998 @samp{configure --build=x86_64-gnu --host=i386-gnu}, then this call:
3999 @example
4000 AC_CHECK_TOOL([RANLIB], [ranlib], [:])
4001 @end example
4002 @noindent
4003 sets @code{RANLIB} to @file{i386-gnu-ranlib} if that program exists in
4004 @var{path}, or otherwise to @samp{ranlib} if that program exists in
4005 @var{path}, or to @samp{:} if neither program exists.
4007 In the future, when cross-compiling this macro will @emph{only}
4008 accept program names that are prefixed with the host type.
4009 For more information, see @ref{Specifying Names, , Specifying the
4010 system type}.
4011 @end defmac
4013 @defmac AC_CHECK_TARGET_TOOLS (@var{variable}, @var{progs-to-check-for}, @
4014   @ovar{value-if-not-found}, @dvar{path, $PATH})
4015 @acindex{CHECK_TARGET_TOOLS}
4016 Like @code{AC_CHECK_TARGET_TOOL}, each of the tools in the list
4017 @var{progs-to-check-for} are checked with a prefix of the target type as
4018 determined by @code{AC_CANONICAL_TARGET}, followed by a dash
4019 (@pxref{Canonicalizing}).  If none of the tools can be found with a
4020 prefix, and if the build and target types are equal, then the first one
4021 without a prefix is used.  If a tool is found, set @var{variable} to
4022 the name of that program.  If none of the tools in the list are found,
4023 set @var{variable} to @var{value-if-not-found}; if @var{value-if-not-found}
4024 is not specified, the value of @var{variable} is not changed.  Calls
4025 @code{AC_SUBST} for @var{variable}.
4026 @end defmac
4028 @defmac AC_CHECK_TOOLS (@var{variable}, @var{progs-to-check-for}, @
4029   @ovar{value-if-not-found}, @dvar{path, $PATH})
4030 @acindex{CHECK_TOOLS}
4031 Like @code{AC_CHECK_TOOL}, each of the tools in the list
4032 @var{progs-to-check-for} are checked with a prefix of the host type as
4033 determined by @code{AC_CANONICAL_HOST}, followed by a dash
4034 (@pxref{Canonicalizing}).  If none of the tools can be found with a
4035 prefix, then the first one without a prefix is used.  If a tool is found,
4036 set @var{variable} to the name of that program.  If none of the tools in
4037 the list are found, set @var{variable} to @var{value-if-not-found}; if
4038 @var{value-if-not-found} is not specified, the value of @var{variable}
4039 is not changed.  Calls @code{AC_SUBST} for @var{variable}.
4041 In the future, when cross-compiling this macro will @emph{not}
4042 accept program names that are not prefixed with the host type.
4043 @end defmac
4045 @anchor{AC_PATH_PROG}
4046 @defmac AC_PATH_PROG (@var{variable}, @var{prog-to-check-for}, @
4047   @ovar{value-if-not-found}, @dvar{path, $PATH})
4048 @acindex{PATH_PROG}
4049 Like @code{AC_CHECK_PROG}, but set @var{variable} to the absolute
4050 name of @var{prog-to-check-for} if found.
4051 @end defmac
4053 @anchor{AC_PATH_PROGS}
4054 @defmac AC_PATH_PROGS (@var{variable}, @var{progs-to-check-for}, @
4055   @ovar{value-if-not-found}, @dvar{path, $PATH})
4056 @acindex{PATH_PROGS}
4057 Like @code{AC_CHECK_PROGS}, but if any of @var{progs-to-check-for}
4058 are found, set @var{variable} to the absolute name of the program
4059 found.
4060 @end defmac
4062 @defmac AC_PATH_PROGS_FEATURE_CHECK (@var{variable}, @
4063   @var{progs-to-check-for}, @var{feature-test}, @
4064   @ovar{action-if-not-found}, @dvar{path, $PATH})
4065 @acindex{PATH_PROGS_FEATURE_CHECK}
4066 This macro was introduced in Autoconf 2.62.  If @var{variable} is not
4067 empty, then set the cache variable @code{$ac_cv_path_@var{variable}} to
4068 its value.  Otherwise, check for each program in the blank-separated
4069 list @var{progs-to-check-for} existing in @var{path}.  For each program
4070 found, execute @var{feature-test} with @code{$ac_path_@var{variable}}
4071 set to the absolute name of the candidate program.  If no invocation of
4072 @var{feature-test} sets the shell variable
4073 @code{$ac_cv_path_@var{variable}}, then @var{action-if-not-found} is
4074 executed.  @var{feature-test} will be run even when
4075 @code{ac_cv_path_@var{variable}} is set, to provide the ability to
4076 choose a better candidate found later in @var{path}; to accept the
4077 current setting and bypass all futher checks, @var{feature-test} can
4078 execute @code{ac_path_@var{variable}_found=:}.
4080 Note that this macro has some subtle differences from
4081 @code{AC_CHECK_PROGS}.  It is designed to be run inside
4082 @code{AC_CACHE_VAL}, therefore, it should have no side effects.  In
4083 particular, @var{variable} is not set to the final value of
4084 @code{ac_cv_path_@var{variable}}, nor is @code{AC_SUBST} automatically
4085 run.  Also, on failure, any action can be performed, whereas
4086 @code{AC_CHECK_PROGS} only performs
4087 @code{@var{variable}=@var{value-if-not-found}}.
4089 Here is an example, similar to what Autoconf uses in its own configure
4090 script.  It will search for an implementation of @command{m4} that
4091 supports the @code{indir} builtin, even if it goes by the name
4092 @command{gm4} or is not the first implementation on @env{PATH}.
4094 @example
4095 AC_CACHE_CHECK([for m4 that supports indir], [ac_cv_path_M4],
4096   [AC_PATH_PROGS_FEATURE_CHECK([M4], [m4 gm4],
4097     [[m4out=`echo 'changequote([,])indir([divnum])' | $ac_path_M4`
4098       test "x$m4out" = x0 \
4099       && ac_cv_path_M4=$ac_path_M4 ac_path_M4_found=:]],
4100     [AC_MSG_ERROR([could not find m4 that supports indir])])])
4101 AC_SUBST([M4], [$ac_cv_path_M4])
4102 @end example
4103 @end defmac
4105 @defmac AC_PATH_TARGET_TOOL (@var{variable}, @var{prog-to-check-for}, @
4106   @ovar{value-if-not-found}, @dvar{path, $PATH})
4107 @acindex{PATH_TARGET_TOOL}
4108 Like @code{AC_CHECK_TARGET_TOOL}, but set @var{variable} to the absolute
4109 name of the program if it is found.
4110 @end defmac
4112 @defmac AC_PATH_TOOL (@var{variable}, @var{prog-to-check-for}, @
4113   @ovar{value-if-not-found}, @dvar{path, $PATH})
4114 @acindex{PATH_TOOL}
4115 Like @code{AC_CHECK_TOOL}, but set @var{variable} to the absolute
4116 name of the program if it is found.
4118 In the future, when cross-compiling this macro will @emph{not}
4119 accept program names that are not prefixed with the host type.
4120 @end defmac
4123 @node Files
4124 @section Files
4125 @cindex File, checking
4127 You might also need to check for the existence of files.  Before using
4128 these macros, ask yourself whether a runtime test might not be a better
4129 solution.  Be aware that, like most Autoconf macros, they test a feature
4130 of the host machine, and therefore, they die when cross-compiling.
4132 @defmac AC_CHECK_FILE (@var{file}, @ovar{action-if-found}, @
4133   @ovar{action-if-not-found})
4134 @acindex{CHECK_FILE}
4135 Check whether file @var{file} exists on the native system.  If it is
4136 found, execute @var{action-if-found}, otherwise do
4137 @var{action-if-not-found}, if given.
4138 @end defmac
4140 @defmac AC_CHECK_FILES (@var{files}, @ovar{action-if-found}, @
4141   @ovar{action-if-not-found})
4142 @acindex{CHECK_FILES}
4143 Executes @code{AC_CHECK_FILE} once for each file listed in @var{files}.
4144 Additionally, defines @samp{HAVE_@var{file}} (@pxref{Standard Symbols})
4145 for each file found.
4146 @end defmac
4149 @node Libraries
4150 @section Library Files
4151 @cindex Library, checking
4153 The following macros check for the presence of certain C, C++, or Fortran
4154 library archive files.
4156 @anchor{AC_CHECK_LIB}
4157 @defmac AC_CHECK_LIB (@var{library}, @var{function}, @
4158   @ovar{action-if-found}, @ovar{action-if-not-found}, @ovar{other-libraries})
4159 @acindex{CHECK_LIB}
4160 Test whether the library @var{library} is available by trying to link
4161 a test program that calls function @var{function} with the library.
4162 @var{function} should be a function provided by the library.
4163 Use the base
4164 name of the library; e.g., to check for @option{-lmp}, use @samp{mp} as
4165 the @var{library} argument.
4167 @var{action-if-found} is a list of shell commands to run if the link
4168 with the library succeeds; @var{action-if-not-found} is a list of shell
4169 commands to run if the link fails.  If @var{action-if-found} is not
4170 specified, the default action prepends @option{-l@var{library}} to
4171 @code{LIBS} and defines @samp{HAVE_LIB@var{library}} (in all
4172 capitals).  This macro is intended to support building @code{LIBS} in
4173 a right-to-left (least-dependent to most-dependent) fashion such that
4174 library dependencies are satisfied as a natural side effect of
4175 consecutive tests.  Linkers are sensitive to library ordering
4176 so the order in which @code{LIBS} is generated is important to reliable
4177 detection of libraries.
4179 If linking with @var{library} results in unresolved symbols that would
4180 be resolved by linking with additional libraries, give those libraries
4181 as the @var{other-libraries} argument, separated by spaces:
4182 e.g., @option{-lXt -lX11}.  Otherwise, this macro fails to detect
4183 that @var{library} is present, because linking the test program
4184 always fails with unresolved symbols.  The @var{other-libraries} argument
4185 should be limited to cases where it is desirable to test for one library
4186 in the presence of another that is not already in @code{LIBS}.
4188 @code{AC_CHECK_LIB} requires some care in usage, and should be avoided
4189 in some common cases.  Many standard functions like @code{gethostbyname}
4190 appear in the standard C library on some hosts, and in special libraries
4191 like @code{nsl} on other hosts.  On some hosts the special libraries
4192 contain variant implementations that you may not want to use.  These
4193 days it is normally better to use @code{AC_SEARCH_LIBS([gethostbyname],
4194 [nsl])} instead of @code{AC_CHECK_LIB([nsl], [gethostbyname])}.
4195 @end defmac
4197 @anchor{AC_SEARCH_LIBS}
4198 @defmac AC_SEARCH_LIBS (@var{function}, @var{search-libs}, @
4199   @ovar{action-if-found}, @ovar{action-if-not-found}, @ovar{other-libraries})
4200 @acindex{SEARCH_LIBS}
4201 Search for a library defining @var{function} if it's not already
4202 available.  This equates to calling
4203 @samp{AC_LINK_IFELSE([AC_LANG_CALL([], [@var{function}])])} first with
4204 no libraries, then for each library listed in @var{search-libs}.
4206 Add @option{-l@var{library}} to @code{LIBS} for the first library found
4207 to contain @var{function}, and run @var{action-if-found}.  If the
4208 function is not found, run @var{action-if-not-found}.
4210 If linking with @var{library} results in unresolved symbols that would
4211 be resolved by linking with additional libraries, give those libraries
4212 as the @var{other-libraries} argument, separated by spaces:
4213 e.g., @option{-lXt -lX11}.  Otherwise, this macro fails to detect
4214 that @var{function} is present, because linking the test program
4215 always fails with unresolved symbols.
4216 @end defmac
4220 @node Library Functions
4221 @section Library Functions
4223 The following macros check for particular C library functions.
4224 If there is no macro specifically defined to check for a function you need,
4225 and you don't need to check for any special properties of
4226 it, then you can use one of the general function-check macros.
4228 @menu
4229 * Function Portability::        Pitfalls with usual functions
4230 * Particular Functions::        Special handling to find certain functions
4231 * Generic Functions::           How to find other functions
4232 @end menu
4234 @node Function Portability
4235 @subsection Portability of C Functions
4236 @cindex Portability of C functions
4237 @cindex C function portability
4239 Most usual functions can either be missing, or be buggy, or be limited
4240 on some architectures.  This section tries to make an inventory of these
4241 portability issues.  By definition, this list always requires
4242 additions.  Please help us keeping it as complete as possible.
4244 @table @asis
4245 @item @code{exit}
4246 @c @fuindex exit
4247 @prindex @code{exit}
4248 On ancient hosts, @code{exit} returned @code{int}.
4249 This is because @code{exit} predates @code{void}, and there was a long
4250 tradition of it returning @code{int}.
4252 On current hosts, the problem more likely is that @code{exit} is not
4253 declared, due to C++ problems of some sort or another.  For this reason
4254 we suggest that test programs not invoke @code{exit}, but return from
4255 @code{main} instead.
4257 @item @code{free}
4258 @c @fuindex free
4259 @prindex @code{free}
4260 The C standard says a call @code{free (NULL)} does nothing, but
4261 some old systems don't support this (e.g., NextStep).
4263 @item @code{isinf}
4264 @itemx @code{isnan}
4265 @c @fuindex isinf
4266 @c @fuindex isnan
4267 @prindex @code{isinf}
4268 @prindex @code{isnan}
4269 The C99 standard says that @code{isinf} and @code{isnan} are
4270 macros.  On some systems just macros are available
4271 (e.g., @acronym{HP-UX} and Solaris 10), on
4272 some systems both macros and functions (e.g., glibc 2.3.2), and on some
4273 systems only functions (e.g., IRIX 6 and Solaris 9).  In some cases
4274 these functions are declared in nonstandard headers like
4275 @code{<sunmath.h>} and defined in non-default libraries like
4276 @option{-lm} or @option{-lsunmath}.
4278 The C99 @code{isinf} and @code{isnan} macros work correctly with
4279 @code{long double} arguments, but pre-C99 systems that use functions
4280 typically assume @code{double} arguments.  On such a system,
4281 @code{isinf} incorrectly returns true for a finite @code{long double}
4282 argument that is outside the range of @code{double}.
4284 To work around this porting mess, you can use code like the following.
4286 @smallexample
4287 #include <math.h>
4289 #ifndef isnan
4290 # define isnan(x) \
4291     (sizeof (x) == sizeof (long double) ? isnan_ld (x) \
4292      : sizeof (x) == sizeof (double) ? isnan_d (x) \
4293      : isnan_f (x))
4294 static inline int isnan_f  (float       x) @{ return x != x; @}
4295 static inline int isnan_d  (double      x) @{ return x != x; @}
4296 static inline int isnan_ld (long double x) @{ return x != x; @}
4297 #endif
4299 #ifndef isinf
4300 # define isinf(x) \
4301     (sizeof (x) == sizeof (long double) ? isinf_ld (x) \
4302      : sizeof (x) == sizeof (double) ? isinf_d (x) \
4303      : isinf_f (x))
4304 static inline int isinf_f  (float       x) @{ return isnan (x - x); @}
4305 static inline int isinf_d  (double      x) @{ return isnan (x - x); @}
4306 static inline int isinf_ld (long double x) @{ return isnan (x - x); @}
4307 #endif
4308 @end smallexample
4310 Use @code{AC_C_INLINE} (@pxref{C Compiler}) so that this code works on
4311 compilers that lack the @code{inline} keyword.  Some optimizing
4312 compilers mishandle these definitions, but systems with that bug
4313 typically have missing or broken @code{isnan} functions anyway, so it's
4314 probably not worth worrying about.
4316 @item @code{malloc}
4317 @c @fuindex malloc
4318 @prindex @code{malloc}
4319 The C standard says a call @code{malloc (0)} is implementation
4320 dependent.  It can return either @code{NULL} or a new non-null pointer.
4321 The latter is more common (e.g., the @acronym{GNU} C Library) but is by
4322 no means universal.  @code{AC_FUNC_MALLOC}
4323 can be used to insist on non-@code{NULL} (@pxref{Particular Functions}).
4325 @item @code{putenv}
4326 @c @fuindex putenv
4327 @prindex @code{putenv}
4328 Posix prefers @code{setenv} to @code{putenv}; among other things,
4329 @code{putenv} is not required of all Posix implementations, but
4330 @code{setenv} is.
4332 Posix specifies that @code{putenv} puts the given string directly in
4333 @code{environ}, but some systems make a copy of it instead (e.g.,
4334 glibc 2.0, or @acronym{BSD}).  And when a copy is made, @code{unsetenv} might
4335 not free it, causing a memory leak (e.g., Free@acronym{BSD} 4).
4337 On some systems @code{putenv ("FOO")} removes @samp{FOO} from the
4338 environment, but this is not standard usage and it dumps core
4339 on some systems (e.g., AIX).
4341 On MinGW, a call @code{putenv ("FOO=")} removes @samp{FOO} from the
4342 environment, rather than inserting it with an empty value.
4344 @item @code{realloc}
4345 @c @fuindex realloc
4346 @prindex @code{realloc}
4347 The C standard says a call @code{realloc (NULL, size)} is equivalent
4348 to @code{malloc (size)}, but some old systems don't support this (e.g.,
4349 NextStep).
4351 @item @code{signal} handler
4352 @c @fuindex signal
4353 @prindex @code{signal}
4354 Normally @code{signal} takes a handler function with a return type of
4355 @code{void}, but some old systems required @code{int} instead.  Any
4356 actual @code{int} value returned is not used; this is only a
4357 difference in the function prototype demanded.
4359 All systems we know of in current use return @code{void}.  The
4360 @code{int} was to support K&R C, where of course @code{void} is not
4361 available.  @code{AC_TYPE_SIGNAL} (@pxref{Particular Types}) can be
4362 used to establish the correct type in all cases.
4364 @item @code{snprintf}
4365 @c @fuindex snprintf
4366 @prindex @code{snprintf}
4367 @c @fuindex vsnprintf
4368 @prindex @code{vsnprintf}
4369 The C99 standard says that if the output array isn't big enough
4370 and if no other errors occur, @code{snprintf} and @code{vsnprintf}
4371 truncate the output and return the number of bytes that ought to have
4372 been produced.  Some older systems return the truncated length (e.g.,
4373 @acronym{GNU} C Library 2.0.x or @sc{irix} 6.5), some a negative value
4374 (e.g., earlier @acronym{GNU} C Library versions), and some the buffer
4375 length without truncation (e.g., 32-bit Solaris 7).  Also, some buggy
4376 older systems ignore the length and overrun the buffer (e.g., 64-bit
4377 Solaris 7).
4379 @item @code{sprintf}
4380 @c @fuindex sprintf
4381 @prindex @code{sprintf}
4382 @c @fuindex vsprintf
4383 @prindex @code{vsprintf}
4384 The C standard says @code{sprintf} and @code{vsprintf} return the
4385 number of bytes written.  On some ancient systems (SunOS 4 for
4386 instance) they return the buffer pointer instead, but these no
4387 longer need to be worried about.
4389 @item @code{sscanf}
4390 @c @fuindex sscanf
4391 @prindex @code{sscanf}
4392 On various old systems, e.g., @acronym{HP-UX} 9, @code{sscanf} requires
4393 that its
4394 input string be writable (though it doesn't actually change it).  This
4395 can be a problem when using @command{gcc} since it normally puts
4396 constant strings in read-only memory (@pxref{Incompatibilities,
4397 Incompatibilities of @acronym{GCC}, , gcc, Using and
4398 Porting the @acronym{GNU} Compiler Collection}).  Apparently in some cases even
4399 having format strings read-only can be a problem.
4401 @item @code{strerror_r}
4402 @c @fuindex strerror_r
4403 @prindex @code{strerror_r}
4404 Posix specifies that @code{strerror_r} returns an @code{int}, but many
4405 systems (e.g., @acronym{GNU} C Library version 2.2.4) provide a
4406 different version returning a @code{char *}.  @code{AC_FUNC_STRERROR_R}
4407 can detect which is in use (@pxref{Particular Functions}).
4409 @item @code{strnlen}
4410 @c @fuindex strnlen
4411 @prindex @code{strnlen}
4412 @acronym{AIX} 4.3 provides a broken version which produces the
4413 following results:
4415 @example
4416 strnlen ("foobar", 0) = 0
4417 strnlen ("foobar", 1) = 3
4418 strnlen ("foobar", 2) = 2
4419 strnlen ("foobar", 3) = 1
4420 strnlen ("foobar", 4) = 0
4421 strnlen ("foobar", 5) = 6
4422 strnlen ("foobar", 6) = 6
4423 strnlen ("foobar", 7) = 6
4424 strnlen ("foobar", 8) = 6
4425 strnlen ("foobar", 9) = 6
4426 @end example
4428 @item @code{sysconf}
4429 @c @fuindex sysconf
4430 @prindex @code{sysconf}
4431 @code{_SC_PAGESIZE} is standard, but some older systems (e.g., @acronym{HP-UX}
4432 9) have @code{_SC_PAGE_SIZE} instead.  This can be tested with
4433 @code{#ifdef}.
4435 @item @code{unlink}
4436 @c @fuindex unlink
4437 @prindex @code{unlink}
4438 The Posix spec says that @code{unlink} causes the given file to be
4439 removed only after there are no more open file handles for it.  Some
4440 non-Posix hosts have trouble with this requirement, though,
4441 and some @acronym{DOS} variants even corrupt the file system.
4443 @item @code{unsetenv}
4444 @c @fuindex unsetenv
4445 @prindex @code{unsetenv}
4446 On MinGW, @code{unsetenv} is not available, but a variable @samp{FOO}
4447 can be removed with a call @code{putenv ("FOO=")}, as described under
4448 @code{putenv} above.
4450 @item @code{va_copy}
4451 @c @fuindex va_copy
4452 @prindex @code{va_copy}
4453 The C99 standard provides @code{va_copy} for copying
4454 @code{va_list} variables.  It may be available in older environments
4455 too, though possibly as @code{__va_copy} (e.g., @command{gcc} in strict
4456 pre-C99 mode).  These can be tested with @code{#ifdef}.  A fallback to
4457 @code{memcpy (&dst, &src, sizeof (va_list))} gives maximum
4458 portability.
4460 @item @code{va_list}
4461 @c @fuindex va_list
4462 @prindex @code{va_list}
4463 @code{va_list} is not necessarily just a pointer.  It can be a
4464 @code{struct} (e.g., @command{gcc} on Alpha), which means @code{NULL} is
4465 not portable.  Or it can be an array (e.g., @command{gcc} in some
4466 PowerPC configurations), which means as a function parameter it can be
4467 effectively call-by-reference and library routines might modify the
4468 value back in the caller (e.g., @code{vsnprintf} in the @acronym{GNU} C Library
4469 2.1).
4471 @item Signed @code{>>}
4472 Normally the C @code{>>} right shift of a signed type replicates the
4473 high bit, giving a so-called ``arithmetic'' shift.  But care should be
4474 taken since Standard C doesn't require that behavior.  On those
4475 few processors without a native arithmetic shift (for instance Cray
4476 vector systems) zero bits may be shifted in, the same as a shift of an
4477 unsigned type.
4479 @item Integer @code{/}
4480 C divides signed integers by truncating their quotient toward zero,
4481 yielding the same result as Fortran.  However, before C99 the standard
4482 allowed C implementations to take the floor or ceiling of the quotient
4483 in some cases.  Hardly any implementations took advantage of this
4484 freedom, though, and it's probably not worth worrying about this issue
4485 nowadays.
4486 @end table
4489 @node Particular Functions
4490 @subsection Particular Function Checks
4491 @cindex Function, checking
4493 These macros check for particular C functions---whether they exist, and
4494 in some cases how they respond when given certain arguments.
4496 @anchor{AC_FUNC_ALLOCA}
4497 @defmac AC_FUNC_ALLOCA
4498 @acindex{FUNC_ALLOCA}
4499 @cvindex C_ALLOCA
4500 @cvindex HAVE_ALLOCA_H
4501 @ovindex ALLOCA
4502 @c @fuindex alloca
4503 @prindex @code{alloca}
4504 @hdrindex{alloca.h}
4505 Check how to get @code{alloca}.  Tries to get a builtin version by
4506 checking for @file{alloca.h} or the predefined C preprocessor macros
4507 @code{__GNUC__} and @code{_AIX}.  If this macro finds @file{alloca.h},
4508 it defines @code{HAVE_ALLOCA_H}.
4510 If those attempts fail, it looks for the function in the standard C
4511 library.  If any of those methods succeed, it defines
4512 @code{HAVE_ALLOCA}.  Otherwise, it sets the output variable
4513 @code{ALLOCA} to @samp{$@{LIBOBJDIR@}alloca.o} and defines
4514 @code{C_ALLOCA} (so programs can periodically call @samp{alloca (0)} to
4515 garbage collect).  This variable is separate from @code{LIBOBJS} so
4516 multiple programs can share the value of @code{ALLOCA} without needing
4517 to create an actual library, in case only some of them use the code in
4518 @code{LIBOBJS}.  The @samp{$@{LIBOBJDIR@}} prefix serves the same
4519 purpose as in @code{LIBOBJS} (@pxref{AC_LIBOBJ vs LIBOBJS}).
4521 This macro does not try to get @code{alloca} from the System V R3
4522 @file{libPW} or the System V R4 @file{libucb} because those libraries
4523 contain some incompatible functions that cause trouble.  Some versions
4524 do not even contain @code{alloca} or contain a buggy version.  If you
4525 still want to use their @code{alloca}, use @code{ar} to extract
4526 @file{alloca.o} from them instead of compiling @file{alloca.c}.
4528 Source files that use @code{alloca} should start with a piece of code
4529 like the following, to declare it properly.
4531 @example
4532 @group
4533 #ifdef HAVE_ALLOCA_H
4534 # include <alloca.h>
4535 #elif defined __GNUC__
4536 # define alloca __builtin_alloca
4537 #elif defined _AIX
4538 # define alloca __alloca
4539 #elif defined _MSC_VER
4540 # include <malloc.h>
4541 # define alloca _alloca
4542 #else
4543 # include <stddef.h>
4544 # ifdef  __cplusplus
4545 extern "C"
4546 # endif
4547 void *alloca (size_t);
4548 #endif
4549 @end group
4550 @end example
4551 @end defmac
4553 @defmac AC_FUNC_CHOWN
4554 @acindex{FUNC_CHOWN}
4555 @cvindex HAVE_CHOWN
4556 @c @fuindex chown
4557 @prindex @code{chown}
4558 If the @code{chown} function is available and works (in particular, it
4559 should accept @option{-1} for @code{uid} and @code{gid}), define
4560 @code{HAVE_CHOWN}.
4561 @end defmac
4563 @anchor{AC_FUNC_CLOSEDIR_VOID}
4564 @defmac AC_FUNC_CLOSEDIR_VOID
4565 @acindex{FUNC_CLOSEDIR_VOID}
4566 @cvindex CLOSEDIR_VOID
4567 @c @fuindex closedir
4568 @prindex @code{closedir}
4569 If the @code{closedir} function does not return a meaningful value,
4570 define @code{CLOSEDIR_VOID}.  Otherwise, callers ought to check its
4571 return value for an error indicator.
4573 Currently this test is implemented by running a test program.  When
4574 cross compiling the pessimistic assumption that @code{closedir} does not
4575 return a meaningful value is made.
4577 This macro is obsolescent, as @code{closedir} returns a meaningful value
4578 on current systems.  New programs need not use this macro.
4579 @end defmac
4581 @defmac AC_FUNC_ERROR_AT_LINE
4582 @acindex{FUNC_ERROR_AT_LINE}
4583 @c @fuindex error_at_line
4584 @prindex @code{error_at_line}
4585 If the @code{error_at_line} function is not found, require an
4586 @code{AC_LIBOBJ} replacement of @samp{error}.
4587 @end defmac
4589 @defmac AC_FUNC_FNMATCH
4590 @acindex{FUNC_FNMATCH}
4591 @c @fuindex fnmatch
4592 @prindex @code{fnmatch}
4593 If the @code{fnmatch} function conforms to Posix, define
4594 @code{HAVE_FNMATCH}.  Detect common implementation bugs, for example,
4595 the bugs in Solaris 2.4.
4597 Unlike the other specific
4598 @code{AC_FUNC} macros, @code{AC_FUNC_FNMATCH} does not replace a
4599 broken/missing @code{fnmatch}.  This is for historical reasons.
4600 See @code{AC_REPLACE_FNMATCH} below.
4602 This macro is obsolescent.  New programs should use Gnulib's
4603 @code{fnmatch-posix} module.  @xref{Gnulib}.
4604 @end defmac
4606 @defmac AC_FUNC_FNMATCH_GNU
4607 @acindex{FUNC_FNMATCH_GNU}
4608 @c @fuindex fnmatch
4609 @prindex @code{fnmatch}
4610 Behave like @code{AC_REPLACE_FNMATCH} (@emph{replace}) but also test
4611 whether @code{fnmatch} supports @acronym{GNU} extensions.  Detect common
4612 implementation bugs, for example, the bugs in the @acronym{GNU} C
4613 Library 2.1.
4615 This macro is obsolescent.  New programs should use Gnulib's
4616 @code{fnmatch-gnu} module.  @xref{Gnulib}.
4617 @end defmac
4619 @anchor{AC_FUNC_FORK}
4620 @defmac AC_FUNC_FORK
4621 @acindex{FUNC_FORK}
4622 @cvindex HAVE_VFORK_H
4623 @cvindex HAVE_WORKING_FORK
4624 @cvindex HAVE_WORKING_VFORK
4625 @cvindex vfork
4626 @c @fuindex fork
4627 @prindex @code{fork}
4628 @c @fuindex vfork
4629 @prindex @code{vfork}
4630 @hdrindex{vfork.h}
4631 This macro checks for the @code{fork} and @code{vfork} functions.  If a
4632 working @code{fork} is found, define @code{HAVE_WORKING_FORK}.  This macro
4633 checks whether @code{fork} is just a stub by trying to run it.
4635 If @file{vfork.h} is found, define @code{HAVE_VFORK_H}.  If a working
4636 @code{vfork} is found, define @code{HAVE_WORKING_VFORK}.  Otherwise,
4637 define @code{vfork} to be @code{fork} for backward compatibility with
4638 previous versions of @command{autoconf}.  This macro checks for several known
4639 errors in implementations of @code{vfork} and considers the system to not
4640 have a working @code{vfork} if it detects any of them.  It is not considered
4641 to be an implementation error if a child's invocation of @code{signal}
4642 modifies the parent's signal handler, since child processes rarely change
4643 their signal handlers.
4645 Since this macro defines @code{vfork} only for backward compatibility with
4646 previous versions of @command{autoconf} you're encouraged to define it
4647 yourself in new code:
4648 @example
4649 @group
4650 #ifndef HAVE_WORKING_VFORK
4651 # define vfork fork
4652 #endif
4653 @end group
4654 @end example
4655 @end defmac
4657 @defmac AC_FUNC_FSEEKO
4658 @acindex{FUNC_FSEEKO}
4659 @cvindex _LARGEFILE_SOURCE
4660 @cvindex HAVE_FSEEKO
4661 @c @fuindex fseeko
4662 @prindex @code{fseeko}
4663 If the @code{fseeko} function is available, define @code{HAVE_FSEEKO}.
4664 Define @code{_LARGEFILE_SOURCE} if necessary to make the prototype
4665 visible on some systems (e.g., glibc 2.2).  Otherwise linkage problems
4666 may occur when compiling with @code{AC_SYS_LARGEFILE} on
4667 largefile-sensitive systems where @code{off_t} does not default to a
4668 64bit entity.
4669 @end defmac
4671 @defmac AC_FUNC_GETGROUPS
4672 @acindex{FUNC_GETGROUPS}
4673 @cvindex HAVE_GETGROUPS
4674 @ovindex GETGROUPS_LIBS
4675 @c @fuindex getgroups
4676 @prindex @code{getgroups}
4677 If the @code{getgroups} function is available and works (unlike on
4678 Ultrix 4.3, where @samp{getgroups (0, 0)} always fails), define
4679 @code{HAVE_GETGROUPS}.  Set @code{GETGROUPS_LIBS} to any libraries
4680 needed to get that function.  This macro runs @code{AC_TYPE_GETGROUPS}.
4681 @end defmac
4683 @anchor{AC_FUNC_GETLOADAVG}
4684 @defmac AC_FUNC_GETLOADAVG
4685 @acindex{FUNC_GETLOADAVG}
4686 @cvindex SVR4
4687 @cvindex DGUX
4688 @cvindex UMAX
4689 @cvindex UMAX4_3
4690 @cvindex HAVE_NLIST_H
4691 @cvindex NLIST_NAME_UNION
4692 @cvindex GETLOADAVG_PRIVILEGED
4693 @cvindex NEED_SETGID
4694 @cvindex C_GETLOADAVG
4695 @ovindex LIBOBJS
4696 @ovindex NEED_SETGID
4697 @ovindex KMEM_GROUP
4698 @ovindex GETLOADAVG_LIBS
4699 @c @fuindex getloadavg
4700 @prindex @code{getloadavg}
4701 Check how to get the system load averages.  To perform its tests
4702 properly, this macro needs the file @file{getloadavg.c}; therefore, be
4703 sure to set the @code{AC_LIBOBJ} replacement directory properly (see
4704 @ref{Generic Functions}, @code{AC_CONFIG_LIBOBJ_DIR}).
4706 If the system has the @code{getloadavg} function, define
4707 @code{HAVE_GETLOADAVG}, and set @code{GETLOADAVG_LIBS} to any libraries
4708 necessary to get that function.  Also add @code{GETLOADAVG_LIBS} to
4709 @code{LIBS}.  Otherwise, require an @code{AC_LIBOBJ} replacement for
4710 @samp{getloadavg} with source code in @file{@var{dir}/getloadavg.c}, and
4711 possibly define several other C preprocessor macros and output
4712 variables:
4714 @enumerate
4715 @item
4716 Define @code{C_GETLOADAVG}.
4718 @item
4719 Define @code{SVR4}, @code{DGUX}, @code{UMAX}, or @code{UMAX4_3} if on
4720 those systems.
4722 @item
4723 @hdrindex{nlist.h}
4724 If @file{nlist.h} is found, define @code{HAVE_NLIST_H}.
4726 @item
4727 If @samp{struct nlist} has an @samp{n_un.n_name} member, define
4728 @code{HAVE_STRUCT_NLIST_N_UN_N_NAME}.  The obsolete symbol
4729 @code{NLIST_NAME_UNION} is still defined, but do not depend upon it.
4731 @item
4732 Programs may need to be installed set-group-ID (or set-user-ID) for
4733 @code{getloadavg} to work.  In this case, define
4734 @code{GETLOADAVG_PRIVILEGED}, set the output variable @code{NEED_SETGID}
4735 to @samp{true} (and otherwise to @samp{false}), and set
4736 @code{KMEM_GROUP} to the name of the group that should own the installed
4737 program.
4738 @end enumerate
4740 The @code{AC_FUNC_GETLOADAVG} macro is obsolescent.  New programs should
4741 use Gnulib's @code{getloadavg} module.  @xref{Gnulib}.
4742 @end defmac
4744 @anchor{AC_FUNC_GETMNTENT}
4745 @defmac AC_FUNC_GETMNTENT
4746 @acindex{FUNC_GETMNTENT}
4747 @cvindex HAVE_GETMNTENT
4748 @c @fuindex getmntent
4749 @prindex @code{getmntent}
4750 Check for @code{getmntent} in the standard C library, and then in the
4751 @file{sun}, @file{seq}, and @file{gen} libraries, for @sc{unicos},
4752 @sc{irix} 4, @sc{ptx}, and UnixWare, respectively.  Then, if
4753 @code{getmntent} is available, define @code{HAVE_GETMNTENT}.
4754 @end defmac
4756 @defmac AC_FUNC_GETPGRP
4757 @acindex{FUNC_GETPGRP}
4758 @cvindex GETPGRP_VOID
4759 @c @fuindex getpgid
4760 @c @fuindex getpgrp
4761 @prindex @code{getpgid}
4762 @prindex @code{getpgrp}
4763 Define @code{GETPGRP_VOID} if it is an error to pass 0 to
4764 @code{getpgrp}; this is the Posix behavior.  On older @acronym{BSD}
4765 systems, you must pass 0 to @code{getpgrp}, as it takes an argument and
4766 behaves like Posix's @code{getpgid}.
4768 @example
4769 #ifdef GETPGRP_VOID
4770   pid = getpgrp ();
4771 #else
4772   pid = getpgrp (0);
4773 #endif
4774 @end example
4776 This macro does not check whether
4777 @code{getpgrp} exists at all; if you need to work in that situation,
4778 first call @code{AC_CHECK_FUNC} for @code{getpgrp}.
4780 This macro is obsolescent, as current systems have a @code{getpgrp}
4781 whose signature conforms to Posix.  New programs need not use this macro.
4782 @end defmac
4784 @defmac AC_FUNC_LSTAT_FOLLOWS_SLASHED_SYMLINK
4785 @acindex{FUNC_LSTAT_FOLLOWS_SLASHED_SYMLINK}
4786 @cvindex LSTAT_FOLLOWS_SLASHED_SYMLINK
4787 @c @fuindex lstat
4788 @prindex @code{lstat}
4789 If @file{link} is a symbolic link, then @code{lstat} should treat
4790 @file{link/} the same as @file{link/.}.  However, many older
4791 @code{lstat} implementations incorrectly ignore trailing slashes.
4793 It is safe to assume that if @code{lstat} incorrectly ignores
4794 trailing slashes, then other symbolic-link-aware functions like
4795 @code{unlink} also incorrectly ignore trailing slashes.
4797 If @code{lstat} behaves properly, define
4798 @code{LSTAT_FOLLOWS_SLASHED_SYMLINK}, otherwise require an
4799 @code{AC_LIBOBJ} replacement of @code{lstat}.
4800 @end defmac
4802 @defmac AC_FUNC_MALLOC
4803 @acindex{FUNC_MALLOC}
4804 @cvindex HAVE_MALLOC
4805 @cvindex malloc
4806 @c @fuindex malloc
4807 @prindex @code{malloc}
4808 If the @code{malloc} function is compatible with the @acronym{GNU} C
4809 library @code{malloc} (i.e., @samp{malloc (0)} returns a valid
4810 pointer), define @code{HAVE_MALLOC} to 1.  Otherwise define
4811 @code{HAVE_MALLOC} to 0, ask for an @code{AC_LIBOBJ} replacement for
4812 @samp{malloc}, and define @code{malloc} to @code{rpl_malloc} so that the
4813 native @code{malloc} is not used in the main project.
4815 Typically, the replacement file @file{malloc.c} should look like (note
4816 the @samp{#undef malloc}):
4818 @verbatim
4819 #include <config.h>
4820 #undef malloc
4822 #include <sys/types.h>
4824 void *malloc ();
4826 /* Allocate an N-byte block of memory from the heap.
4827    If N is zero, allocate a 1-byte block.  */
4829 void *
4830 rpl_malloc (size_t n)
4832   if (n == 0)
4833     n = 1;
4834   return malloc (n);
4836 @end verbatim
4837 @end defmac
4839 @defmac AC_FUNC_MEMCMP
4840 @acindex{FUNC_MEMCMP}
4841 @ovindex LIBOBJS
4842 @c @fuindex memcmp
4843 @prindex @code{memcmp}
4844 If the @code{memcmp} function is not available, or does not work on
4845 8-bit data (like the one on SunOS 4.1.3), or fails when comparing 16
4846 bytes or more and with at least one buffer not starting on a 4-byte
4847 boundary (such as the one on NeXT x86 OpenStep), require an
4848 @code{AC_LIBOBJ} replacement for @samp{memcmp}.
4850 This macro is obsolescent, as current systems have a working
4851 @code{memcmp}.  New programs need not use this macro.
4852 @end defmac
4854 @defmac AC_FUNC_MBRTOWC
4855 @acindex{FUNC_MBRTOWC}
4856 @cvindex HAVE_MBRTOWC
4857 @c @fuindex mbrtowc
4858 @prindex @code{mbrtowc}
4859 Define @code{HAVE_MBRTOWC} to 1 if the function @code{mbrtowc} and the
4860 type @code{mbstate_t} are properly declared.
4861 @end defmac
4863 @defmac AC_FUNC_MKTIME
4864 @acindex{FUNC_MKTIME}
4865 @ovindex LIBOBJS
4866 @c @fuindex mktime
4867 @prindex @code{mktime}
4868 If the @code{mktime} function is not available, or does not work
4869 correctly, require an @code{AC_LIBOBJ} replacement for @samp{mktime}.
4870 For the purposes of this test, @code{mktime} should conform to the
4871 Posix standard and should be the inverse of
4872 @code{localtime}.
4873 @end defmac
4875 @anchor{AC_FUNC_MMAP}
4876 @defmac AC_FUNC_MMAP
4877 @acindex{FUNC_MMAP}
4878 @cvindex HAVE_MMAP
4879 @c @fuindex mmap
4880 @prindex @code{mmap}
4881 If the @code{mmap} function exists and works correctly, define
4882 @code{HAVE_MMAP}.  This checks only private fixed mapping of already-mapped
4883 memory.
4884 @end defmac
4886 @defmac AC_FUNC_OBSTACK
4887 @acindex{FUNC_OBSTACK}
4888 @cvindex HAVE_OBSTACK
4889 @cindex obstack
4890 If the obstacks are found, define @code{HAVE_OBSTACK}, else require an
4891 @code{AC_LIBOBJ} replacement for @samp{obstack}.
4892 @end defmac
4894 @defmac AC_FUNC_REALLOC
4895 @acindex{FUNC_REALLOC}
4896 @cvindex HAVE_REALLOC
4897 @cvindex realloc
4898 @c @fuindex realloc
4899 @prindex @code{realloc}
4900 If the @code{realloc} function is compatible with the @acronym{GNU} C
4901 library @code{realloc} (i.e., @samp{realloc (NULL, 0)} returns a
4902 valid pointer), define @code{HAVE_REALLOC} to 1.  Otherwise define
4903 @code{HAVE_REALLOC} to 0, ask for an @code{AC_LIBOBJ} replacement for
4904 @samp{realloc}, and define @code{realloc} to @code{rpl_realloc} so that
4905 the native @code{realloc} is not used in the main project.  See
4906 @code{AC_FUNC_MALLOC} for details.
4907 @end defmac
4909 @defmac AC_FUNC_SELECT_ARGTYPES
4910 @acindex{FUNC_SELECT_ARGTYPES}
4911 @cvindex SELECT_TYPE_ARG1
4912 @cvindex SELECT_TYPE_ARG234
4913 @cvindex SELECT_TYPE_ARG5
4914 @c @fuindex select
4915 @prindex @code{select}
4916 Determines the correct type to be passed for each of the
4917 @code{select} function's arguments, and defines those types
4918 in @code{SELECT_TYPE_ARG1}, @code{SELECT_TYPE_ARG234}, and
4919 @code{SELECT_TYPE_ARG5} respectively.  @code{SELECT_TYPE_ARG1} defaults
4920 to @samp{int}, @code{SELECT_TYPE_ARG234} defaults to @samp{int *},
4921 and @code{SELECT_TYPE_ARG5} defaults to @samp{struct timeval *}.
4923 This macro is obsolescent, as current systems have a @code{select} whose
4924 signature conforms to Posix.  New programs need not use this macro.
4925 @end defmac
4927 @defmac AC_FUNC_SETPGRP
4928 @acindex{FUNC_SETPGRP}
4929 @cvindex SETPGRP_VOID
4930 @c @fuindex setpgrp
4931 @prindex @code{setpgrp}
4932 If @code{setpgrp} takes no argument (the Posix version), define
4933 @code{SETPGRP_VOID}.  Otherwise, it is the @acronym{BSD} version, which takes
4934 two process IDs as arguments.  This macro does not check whether
4935 @code{setpgrp} exists at all; if you need to work in that situation,
4936 first call @code{AC_CHECK_FUNC} for @code{setpgrp}.
4938 This macro is obsolescent, as current systems have a @code{setpgrp}
4939 whose signature conforms to Posix.  New programs need not use this macro.
4940 @end defmac
4942 @defmac AC_FUNC_STAT
4943 @defmacx AC_FUNC_LSTAT
4944 @acindex{FUNC_STAT}
4945 @acindex{FUNC_LSTAT}
4946 @cvindex HAVE_STAT_EMPTY_STRING_BUG
4947 @cvindex HAVE_LSTAT_EMPTY_STRING_BUG
4948 @c @fuindex stat
4949 @prindex @code{stat}
4950 @c @fuindex lstat
4951 @prindex @code{lstat}
4952 Determine whether @code{stat} or @code{lstat} have the bug that it
4953 succeeds when given the zero-length file name as argument.  The @code{stat}
4954 and @code{lstat} from SunOS 4.1.4 and the Hurd (as of 1998-11-01) do
4955 this.
4957 If it does, then define @code{HAVE_STAT_EMPTY_STRING_BUG} (or
4958 @code{HAVE_LSTAT_EMPTY_STRING_BUG}) and ask for an @code{AC_LIBOBJ}
4959 replacement of it.
4961 These macros are obsolescent, as no current systems have the bug.
4962 New programs need not use these macros.
4963 @end defmac
4965 @anchor{AC_FUNC_STRCOLL}
4966 @defmac AC_FUNC_STRCOLL
4967 @acindex{FUNC_STRCOLL}
4968 @cvindex HAVE_STRCOLL
4969 @c @fuindex strcoll
4970 @prindex @code{strcoll}
4971 If the @code{strcoll} function exists and works correctly, define
4972 @code{HAVE_STRCOLL}.  This does a bit more than
4973 @samp{AC_CHECK_FUNCS(strcoll)}, because some systems have incorrect
4974 definitions of @code{strcoll} that should not be used.
4975 @end defmac
4977 @defmac AC_FUNC_STRERROR_R
4978 @acindex{FUNC_STRERROR_R}
4979 @cvindex HAVE_STRERROR_R
4980 @cvindex HAVE_DECL_STRERROR_R
4981 @cvindex STRERROR_R_CHAR_P
4982 @c @fuindex strerror_r
4983 @prindex @code{strerror_r}
4984 If @code{strerror_r} is available, define @code{HAVE_STRERROR_R}, and if
4985 it is declared, define @code{HAVE_DECL_STRERROR_R}.  If it returns a
4986 @code{char *} message, define @code{STRERROR_R_CHAR_P}; otherwise it
4987 returns an @code{int} error number.  The Thread-Safe Functions option of
4988 Posix requires @code{strerror_r} to return @code{int}, but
4989 many systems (including, for example, version 2.2.4 of the @acronym{GNU} C
4990 Library) return a @code{char *} value that is not necessarily equal to
4991 the buffer argument.
4992 @end defmac
4994 @anchor{AC_FUNC_STRFTIME}
4995 @defmac AC_FUNC_STRFTIME
4996 @acindex{FUNC_STRFTIME}
4997 @cvindex HAVE_STRFTIME
4998 @c @fuindex strftime
4999 @prindex @code{strftime}
5000 Check for @code{strftime} in the @file{intl} library, for SCO Unix.
5001 Then, if @code{strftime} is available, define @code{HAVE_STRFTIME}.
5003 This macro is obsolescent, as no current systems require the @file{intl}
5004 library for @code{strftime}.  New programs need not use this macro.
5005 @end defmac
5007 @defmac AC_FUNC_STRTOD
5008 @acindex{FUNC_STRTOD}
5009 @ovindex POW_LIB
5010 @c @fuindex strtod
5011 @prindex @code{strtod}
5012 If the @code{strtod} function does not exist or doesn't work correctly,
5013 ask for an @code{AC_LIBOBJ} replacement of @samp{strtod}.  In this case,
5014 because @file{strtod.c} is likely to need @samp{pow}, set the output
5015 variable @code{POW_LIB} to the extra library needed.
5016 @end defmac
5018 @defmac AC_FUNC_STRTOLD
5019 @acindex{FUNC_STRTOLD}
5020 @cvindex HAVE_STRTOLD
5021 @prindex @code{strtold}
5022 If the @code{strtold} function exists and conforms to C99, define
5023 @code{HAVE_STRTOLD}.
5024 @end defmac
5026 @defmac AC_FUNC_STRNLEN
5027 @acindex{FUNC_STRNLEN}
5028 @cvindex HAVE_STRNLEN
5029 @c @fuindex strnlen
5030 @prindex @code{strnlen}
5031 If the @code{strnlen} function is not available, or is buggy (like the one
5032 from @acronym{AIX} 4.3), require an @code{AC_LIBOBJ} replacement for it.
5033 @end defmac
5035 @anchor{AC_FUNC_UTIME_NULL}
5036 @defmac AC_FUNC_UTIME_NULL
5037 @acindex{FUNC_UTIME_NULL}
5038 @cvindex HAVE_UTIME_NULL
5039 @c @fuindex utime
5040 @prindex @code{utime}
5041 If @samp{utime (@var{file}, NULL)} sets @var{file}'s timestamp to
5042 the present, define @code{HAVE_UTIME_NULL}.
5044 This macro is obsolescent, as all current systems have a @code{utime}
5045 that behaves this way.  New programs need not use this macro.
5046 @end defmac
5048 @anchor{AC_FUNC_VPRINTF}
5049 @defmac AC_FUNC_VPRINTF
5050 @acindex{FUNC_VPRINTF}
5051 @cvindex HAVE_VPRINTF
5052 @cvindex HAVE_DOPRNT
5053 @c @fuindex vprintf
5054 @prindex @code{vprintf}
5055 If @code{vprintf} is found, define @code{HAVE_VPRINTF}.  Otherwise, if
5056 @code{_doprnt} is found, define @code{HAVE_DOPRNT}.  (If @code{vprintf}
5057 is available, you may assume that @code{vfprintf} and @code{vsprintf}
5058 are also available.)
5060 This macro is obsolescent, as all current systems have @code{vprintf}.
5061 New programs need not use this macro.
5062 @end defmac
5064 @defmac AC_REPLACE_FNMATCH
5065 @acindex{REPLACE_FNMATCH}
5066 @c @fuindex fnmatch
5067 @prindex @code{fnmatch}
5068 @hdrindex{fnmatch.h}
5069 If the @code{fnmatch} function does not conform to Posix (see
5070 @code{AC_FUNC_FNMATCH}), ask for its @code{AC_LIBOBJ} replacement.
5072 The files @file{fnmatch.c}, @file{fnmatch_loop.c}, and @file{fnmatch_.h}
5073 in the @code{AC_LIBOBJ} replacement directory are assumed to contain a
5074 copy of the source code of @acronym{GNU} @code{fnmatch}.  If necessary,
5075 this source code is compiled as an @code{AC_LIBOBJ} replacement, and the
5076 @file{fnmatch_.h} file is linked to @file{fnmatch.h} so that it can be
5077 included in place of the system @code{<fnmatch.h>}.
5079 This macro is obsolescent, as it assumes the use of particular source
5080 files.  New programs should use Gnulib's @code{fnmatch-posix} module,
5081 which provides this macro along with the source files.  @xref{Gnulib}.
5082 @end defmac
5086 @node Generic Functions
5087 @subsection Generic Function Checks
5089 These macros are used to find functions not covered by the ``particular''
5090 test macros.  If the functions might be in libraries other than the
5091 default C library, first call @code{AC_CHECK_LIB} for those libraries.
5092 If you need to check the behavior of a function as well as find out
5093 whether it is present, you have to write your own test for
5094 it (@pxref{Writing Tests}).
5096 @anchor{AC_CHECK_FUNC}
5097 @defmac AC_CHECK_FUNC (@var{function}, @ovar{action-if-found}, @
5098   @ovar{action-if-not-found})
5099 @acindex{CHECK_FUNC}
5100 If C function @var{function} is available, run shell commands
5101 @var{action-if-found}, otherwise @var{action-if-not-found}.  If you just
5102 want to define a symbol if the function is available, consider using
5103 @code{AC_CHECK_FUNCS} instead.  This macro checks for functions with C
5104 linkage even when @code{AC_LANG(C++)} has been called, since C is more
5105 standardized than C++.  (@pxref{Language Choice}, for more information
5106 about selecting the language for checks.)
5107 @end defmac
5109 @anchor{AC_CHECK_FUNCS}
5110 @defmac AC_CHECK_FUNCS (@var{function}@dots{}, @ovar{action-if-found}, @
5111   @ovar{action-if-not-found})
5112 @acindex{CHECK_FUNCS}
5113 @cvindex HAVE_@var{function}
5114 For each @var{function} enumerated in the blank-or-newline-separated argument
5115 list, define @code{HAVE_@var{function}} (in all capitals) if it is available.
5116 If @var{action-if-found} is given, it is additional shell code to
5117 execute when one of the functions is found.  You can give it a value of
5118 @samp{break} to break out of the loop on the first match.  If
5119 @var{action-if-not-found} is given, it is executed when one of the
5120 functions is not found.
5121 @end defmac
5123 @defmac AC_CHECK_FUNCS_ONCE (@var{function}@dots{})
5124 @acindex{CHECK_FUNCS_ONCE}
5125 @cvindex HAVE_@var{function}
5126 For each @var{function} enumerated in the blank-or-newline-separated argument
5127 list, define @code{HAVE_@var{function}} (in all capitals) if it is available.
5128 This is a once-only variant of @code{AC_CHECK_FUNCS}.  It generates the
5129 checking code at most once, so that @command{configure} is smaller and
5130 faster; but the checks cannot be conditionalized and are always done once,
5131 early during the @command{configure} run.
5132 @end defmac
5134 @sp 1
5136 Autoconf follows a philosophy that was formed over the years by those
5137 who have struggled for portability: isolate the portability issues in
5138 specific files, and then program as if you were in a Posix
5139 environment.  Some functions may be missing or unfixable, and your
5140 package must be ready to replace them.
5142 Suitable replacements for many such problem functions are available from
5143 Gnulib (@pxref{Gnulib}).
5145 @defmac AC_LIBOBJ (@var{function})
5146 @acindex{LIBOBJ}
5147 @ovindex LIBOBJS
5148 Specify that @samp{@var{function}.c} must be included in the executables
5149 to replace a missing or broken implementation of @var{function}.
5151 Technically, it adds @samp{@var{function}.$ac_objext} to the output
5152 variable @code{LIBOBJS} if it is not already in, and calls
5153 @code{AC_LIBSOURCE} for @samp{@var{function}.c}.  You should not
5154 directly change @code{LIBOBJS}, since this is not traceable.
5155 @end defmac
5157 @defmac AC_LIBSOURCE (@var{file})
5158 @acindex{LIBSOURCE}
5159 Specify that @var{file} might be needed to compile the project.  If you
5160 need to know what files might be needed by a @file{configure.ac}, you
5161 should trace @code{AC_LIBSOURCE}.  @var{file} must be a literal.
5163 This macro is called automatically from @code{AC_LIBOBJ}, but you must
5164 call it explicitly if you pass a shell variable to @code{AC_LIBOBJ}.  In
5165 that case, since shell variables cannot be traced statically, you must
5166 pass to @code{AC_LIBSOURCE} any possible files that the shell variable
5167 might cause @code{AC_LIBOBJ} to need.  For example, if you want to pass
5168 a variable @code{$foo_or_bar} to @code{AC_LIBOBJ} that holds either
5169 @code{"foo"} or @code{"bar"}, you should do:
5171 @example
5172 AC_LIBSOURCE([foo.c])
5173 AC_LIBSOURCE([bar.c])
5174 AC_LIBOBJ([$foo_or_bar])
5175 @end example
5177 @noindent
5178 There is usually a way to avoid this, however, and you are encouraged to
5179 simply call @code{AC_LIBOBJ} with literal arguments.
5181 Note that this macro replaces the obsolete @code{AC_LIBOBJ_DECL}, with
5182 slightly different semantics: the old macro took the function name,
5183 e.g., @code{foo}, as its argument rather than the file name.
5184 @end defmac
5186 @defmac AC_LIBSOURCES (@var{files})
5187 @acindex{LIBSOURCES}
5188 Like @code{AC_LIBSOURCE}, but accepts one or more @var{files} in a
5189 comma-separated M4 list.  Thus, the above example might be rewritten:
5191 @example
5192 AC_LIBSOURCES([foo.c, bar.c])
5193 AC_LIBOBJ([$foo_or_bar])
5194 @end example
5195 @end defmac
5197 @defmac AC_CONFIG_LIBOBJ_DIR (@var{directory})
5198 @acindex{CONFIG_LIBOBJ_DIR}
5199 Specify that @code{AC_LIBOBJ} replacement files are to be found in
5200 @var{directory}, a name relative to the top level of the
5201 source tree.  The replacement directory defaults to @file{.}, the top
5202 level directory, and the most typical value is @file{lib}, corresponding
5203 to @samp{AC_CONFIG_LIBOBJ_DIR([lib])}.
5205 @command{configure} might need to know the replacement directory for the
5206 following reasons: (i) some checks use the replacement files, (ii) some
5207 macros bypass broken system headers by installing links to the
5208 replacement headers (iii) when used in conjunction with Automake,
5209 within each makefile, @var{directory} is used as a relative path
5210 from @code{$(top_srcdir)} to each object named in @code{LIBOBJS} and
5211 @code{LTLIBOBJS}, etc.
5212 @end defmac
5214 @sp 1
5216 It is common to merely check for the existence of a function, and ask
5217 for its @code{AC_LIBOBJ} replacement if missing.  The following macro is
5218 a convenient shorthand.
5220 @defmac AC_REPLACE_FUNCS (@var{function}@dots{})
5221 @acindex{REPLACE_FUNCS}
5222 @cvindex HAVE_@var{function}
5223 @ovindex LIBOBJS
5224 Like @code{AC_CHECK_FUNCS}, but uses @samp{AC_LIBOBJ(@var{function})} as
5225 @var{action-if-not-found}.  You can declare your replacement function by
5226 enclosing the prototype in @samp{#ifndef HAVE_@var{function}}.  If the
5227 system has the function, it probably declares it in a header file you
5228 should be including, so you shouldn't redeclare it lest your declaration
5229 conflict.
5230 @end defmac
5232 @node Header Files
5233 @section Header Files
5234 @cindex Header, checking
5236 The following macros check for the presence of certain C header files.
5237 If there is no macro specifically defined to check for a header file you need,
5238 and you don't need to check for any special properties of
5239 it, then you can use one of the general header-file check macros.
5241 @menu
5242 * Header Portability::          Collected knowledge on common headers
5243 * Particular Headers::          Special handling to find certain headers
5244 * Generic Headers::             How to find other headers
5245 @end menu
5247 @node Header Portability
5248 @subsection Portability of Headers
5249 @cindex Portability of headers
5250 @cindex Header portability
5252 This section tries to collect knowledge about common headers, and the
5253 problems they cause.  By definition, this list always requires
5254 additions.  Please help us keeping it as complete as possible.
5256 @table @asis
5258 @item @file{limits.h}
5259 C99 says that @file{limits.h} defines @code{LLONG_MIN},
5260 @code{LLONG_MAX}, and @code{ULLONG_MAX}, but many almost-C99
5261 environments (e.g., default @acronym{GCC} 4.0.2 + glibc 2.4) do not
5262 define them.
5264 @item @file{inttypes.h} vs.@: @file{stdint.h}
5265 @hdrindex{inttypes.h}
5266 @hdrindex{stdint.h}
5267 The C99 standard says that @file{inttypes.h} includes
5268 @file{stdint.h}, so there's no need to include @file{stdint.h}
5269 separately in a standard environment.  Some implementations have
5270 @file{inttypes.h} but not @file{stdint.h} (e.g., Solaris 7), but we don't
5271 know of any implementation that has @file{stdint.h} but not
5272 @file{inttypes.h}.
5274 @item @file{linux/irda.h}
5275 @hdrindex{linux/irda.h}
5276 It requires @file{linux/types.h} and @file{sys/socket.h}.
5278 @item @file{linux/random.h}
5279 @hdrindex{linux/random.h}
5280 It requires @file{linux/types.h}.
5282 @item @file{net/if.h}
5283 @hdrindex{net/if.h}
5284 On Darwin, this file requires that @file{sys/socket.h} be included
5285 beforehand.  One should run:
5287 @example
5288 AC_CHECK_HEADERS([sys/socket.h])
5289 AC_CHECK_HEADERS([net/if.h], [], [],
5290 [#include <stdio.h>
5291 #ifdef STDC_HEADERS
5292 # include <stdlib.h>
5293 # include <stddef.h>
5294 #else
5295 # ifdef HAVE_STDLIB_H
5296 #  include <stdlib.h>
5297 # endif
5298 #endif
5299 #ifdef HAVE_SYS_SOCKET_H
5300 # include <sys/socket.h>
5301 #endif
5303 @end example
5305 @item @file{netinet/if_ether.h}
5306 @hdrindex{netinet/if_ether.h}
5307 On Darwin, this file requires that @file{stdio.h} and
5308 @file{sys/socket.h} be included beforehand.  One should run:
5310 @example
5311 AC_CHECK_HEADERS([sys/socket.h])
5312 AC_CHECK_HEADERS([netinet/if_ether.h], [], [],
5313 [#include <stdio.h>
5314 #ifdef STDC_HEADERS
5315 # include <stdlib.h>
5316 # include <stddef.h>
5317 #else
5318 # ifdef HAVE_STDLIB_H
5319 #  include <stdlib.h>
5320 # endif
5321 #endif
5322 #ifdef HAVE_SYS_SOCKET_H
5323 # include <sys/socket.h>
5324 #endif
5326 @end example
5328 @item @file{stdint.h}
5329 See above, item @file{inttypes.h} vs.@: @file{stdint.h}.
5331 @item @file{stdlib.h}
5332 @hdrindex{stdlib.h}
5333 On many systems (e.g., Darwin), @file{stdio.h} is a prerequisite.
5335 @item @file{sys/mount.h}
5336 @hdrindex{sys/mount.h}
5337 On Free@acronym{BSD} 4.8 on ia32 and using gcc version 2.95.4,
5338 @file{sys/params.h} is a prerequisite.
5340 @item @file{sys/ptem.h}
5341 @hdrindex{sys/ptem.h}
5342 On Solaris 8, @file{sys/stream.h} is a prerequisite.
5344 @item @file{sys/socket.h}
5345 @hdrindex{sys/socket.h}
5346 On Darwin, @file{stdlib.h} is a prerequisite.
5348 @item @file{sys/ucred.h}
5349 @hdrindex{sys/ucred.h}
5350 On Tru64 5.1, @file{sys/types.h} is a prerequisite.
5352 @item @file{X11/extensions/scrnsaver.h}
5353 @hdrindex{X11/extensions/scrnsaver.h}
5354 Using XFree86, this header requires @file{X11/Xlib.h}, which is probably
5355 so required that you might not even consider looking for it.
5357 @example
5358 AC_CHECK_HEADERS([X11/extensions/scrnsaver.h], [], [],
5359 [[#include <X11/Xlib.h>
5361 @end example
5362 @end table
5365 @node Particular Headers
5366 @subsection Particular Header Checks
5368 These macros check for particular system header files---whether they
5369 exist, and in some cases whether they declare certain symbols.
5371 @defmac AC_HEADER_ASSERT
5372 @acindex{HEADER_ASSERT}
5373 @cvindex NDEBUG
5374 @hdrindex{assert.h}
5375 Check whether to enable assertions in the style of @file{assert.h}.
5376 Assertions are enabled by default, but the user can override this by
5377 invoking @command{configure} with the @option{--disable-assert} option.
5378 @end defmac
5380 @anchor{AC_HEADER_DIRENT}
5381 @defmac AC_HEADER_DIRENT
5382 @acindex{HEADER_DIRENT}
5383 @cvindex HAVE_DIRENT_H
5384 @cvindex HAVE_NDIR_H
5385 @cvindex HAVE_SYS_DIR_H
5386 @cvindex HAVE_SYS_NDIR_H
5387 @hdrindex{dirent.h}
5388 @hdrindex{sys/ndir.h}
5389 @hdrindex{sys/dir.h}
5390 @hdrindex{ndir.h}
5391 Check for the following header files.  For the first one that is
5392 found and defines @samp{DIR}, define the listed C preprocessor macro:
5394 @multitable {@file{sys/ndir.h}} {@code{HAVE_SYS_NDIR_H}}
5395 @item @file{dirent.h}   @tab @code{HAVE_DIRENT_H}
5396 @item @file{sys/ndir.h} @tab @code{HAVE_SYS_NDIR_H}
5397 @item @file{sys/dir.h}  @tab @code{HAVE_SYS_DIR_H}
5398 @item @file{ndir.h}     @tab @code{HAVE_NDIR_H}
5399 @end multitable
5401 The directory-library declarations in your source code should look
5402 something like the following:
5404 @example
5405 @group
5406 #include <sys/types.h>
5407 #ifdef HAVE_DIRENT_H
5408 # include <dirent.h>
5409 # define NAMLEN(dirent) strlen ((dirent)->d_name)
5410 #else
5411 # define dirent direct
5412 # define NAMLEN(dirent) ((dirent)->d_namlen)
5413 # ifdef HAVE_SYS_NDIR_H
5414 #  include <sys/ndir.h>
5415 # endif
5416 # ifdef HAVE_SYS_DIR_H
5417 #  include <sys/dir.h>
5418 # endif
5419 # ifdef HAVE_NDIR_H
5420 #  include <ndir.h>
5421 # endif
5422 #endif
5423 @end group
5424 @end example
5426 Using the above declarations, the program would declare variables to be
5427 of type @code{struct dirent}, not @code{struct direct}, and would access
5428 the length of a directory entry name by passing a pointer to a
5429 @code{struct dirent} to the @code{NAMLEN} macro.
5431 This macro also checks for the SCO Xenix @file{dir} and @file{x} libraries.
5433 This macro is obsolescent, as all current systems with directory
5434 libraries have @code{<dirent.h>}.  New programs need not use this macro.
5436 Also see @code{AC_STRUCT_DIRENT_D_INO} and
5437 @code{AC_STRUCT_DIRENT_D_TYPE} (@pxref{Particular Structures}).
5438 @end defmac
5440 @anchor{AC_HEADER_MAJOR}
5441 @defmac AC_HEADER_MAJOR
5442 @acindex{HEADER_MAJOR}
5443 @cvindex MAJOR_IN_MKDEV
5444 @cvindex MAJOR_IN_SYSMACROS
5445 @hdrindex{sys/mkdev.h}
5446 @hdrindex{sys/sysmacros.h}
5447 If @file{sys/types.h} does not define @code{major}, @code{minor}, and
5448 @code{makedev}, but @file{sys/mkdev.h} does, define
5449 @code{MAJOR_IN_MKDEV}; otherwise, if @file{sys/sysmacros.h} does, define
5450 @code{MAJOR_IN_SYSMACROS}.
5451 @end defmac
5453 @defmac AC_HEADER_RESOLV
5454 @acindex{HEADER_RESOLV}
5455 @cvindex HAVE_RESOLV_H
5456 @hdrindex{resolv.h}
5457 Checks for header @file{resolv.h}, checking for prerequisites first.
5458 To properly use @file{resolv.h}, your code should contain something like
5459 the following:
5461 @verbatim
5462 #ifdef HAVE_SYS_TYPES_H
5463 #  include <sys/types.h>
5464 #endif
5465 #ifdef HAVE_NETINET_IN_H
5466 #  include <netinet/in.h>   /* inet_ functions / structs */
5467 #endif
5468 #ifdef HAVE_ARPA_NAMESER_H
5469 #  include <arpa/nameser.h> /* DNS HEADER struct */
5470 #endif
5471 #ifdef HAVE_NETDB_H
5472 #  include <netdb.h>
5473 #endif
5474 #include <resolv.h>
5475 @end verbatim
5476 @end defmac
5478 @anchor{AC_HEADER_STAT}
5479 @defmac AC_HEADER_STAT
5480 @acindex{HEADER_STAT}
5481 @cvindex STAT_MACROS_BROKEN
5482 @hdrindex{sys/stat.h}
5483 If the macros @code{S_ISDIR}, @code{S_ISREG}, etc.@: defined in
5484 @file{sys/stat.h} do not work properly (returning false positives),
5485 define @code{STAT_MACROS_BROKEN}.  This is the case on Tektronix UTekV,
5486 Amdahl UTS and Motorola System V/88.
5488 This macro is obsolescent, as no current systems have the bug.
5489 New programs need not use this macro.
5490 @end defmac
5492 @defmac AC_HEADER_STDBOOL
5493 @acindex{HEADER_STDBOOL}
5494 @cvindex HAVE_STDBOOL_H
5495 @cvindex HAVE__BOOL
5496 @hdrindex{stdbool.h}
5497 @hdrindex{system.h}
5498 If @file{stdbool.h} exists and conforms to C99, define
5499 @code{HAVE_STDBOOL_H} to 1; if the type @code{_Bool} is defined, define
5500 @code{HAVE__BOOL} to 1.  To fulfill the C99 requirements, your
5501 @file{system.h} could contain the following code:
5503 @verbatim
5504 #ifdef HAVE_STDBOOL_H
5505 # include <stdbool.h>
5506 #else
5507 # ifndef HAVE__BOOL
5508 #  ifdef __cplusplus
5509 typedef bool _Bool;
5510 #  else
5511 #   define _Bool signed char
5512 #  endif
5513 # endif
5514 # define bool _Bool
5515 # define false 0
5516 # define true 1
5517 # define __bool_true_false_are_defined 1
5518 #endif
5519 @end verbatim
5521 Alternatively you can use the @samp{stdbool} package of Gnulib
5522 (@pxref{Gnulib}); it packages the above code into a replacement header
5523 and contains a few other bells and whistles.
5525 @end defmac
5527 @anchor{AC_HEADER_STDC}
5528 @defmac AC_HEADER_STDC
5529 @acindex{HEADER_STDC}
5530 @cvindex STDC_HEADERS
5531 @hdrindex{stdlib.h}
5532 @hdrindex{stdarg.h}
5533 @hdrindex{string.h}
5534 @hdrindex{float.h}
5535 @hdrindex{ctype.h}
5536 Define @code{STDC_HEADERS} if the system has C header files
5537 conforming to @acronym{ANSI} C89 (@acronym{ISO} C90).
5538 Specifically, this macro checks for @file{stdlib.h}, @file{stdarg.h},
5539 @file{string.h}, and @file{float.h}; if the system has those, it
5540 probably has the rest of the C89 header files.  This macro also
5541 checks whether @file{string.h} declares @code{memchr} (and thus
5542 presumably the other @code{mem} functions), whether @file{stdlib.h}
5543 declare @code{free} (and thus presumably @code{malloc} and other related
5544 functions), and whether the @file{ctype.h} macros work on characters
5545 with the high bit set, as the C standard requires.
5547 If you use this macro, your code can refer to @code{STDC_HEADERS} to
5548 determine whether the system has conforming header files (and probably C
5549 library functions).
5551 This macro is obsolescent, as current systems have conforming header
5552 files.  New programs need not use this macro.
5554 @hdrindex{string.h}
5555 @hdrindex{strings.h}
5556 Nowadays @file{string.h} is part of the C standard and declares functions like
5557 @code{strcpy}, and @file{strings.h} is standardized by Posix and declares
5558 @acronym{BSD} functions like @code{bcopy}; but
5559 historically, string functions were a major sticking point in this area.
5560 If you still want to worry about portability to ancient systems without
5561 standard headers, there is so much variation
5562 that it is probably easier to declare the functions you use than to
5563 figure out exactly what the system header files declare.  Some ancient systems
5564 contained a mix of functions from the C standard and from @acronym{BSD};
5565 some were mostly standard but lacked @samp{memmove}; some defined the
5566 @acronym{BSD} functions as macros in @file{string.h} or
5567 @file{strings.h}; some had only the @acronym{BSD} functions but
5568 @file{string.h}; some declared the memory functions in @file{memory.h},
5569 some in @file{string.h}; etc.  It is probably sufficient to check for
5570 one string function and one memory function; if the library had the
5571 standard versions of those then it probably had most of the others.
5572 If you put the following in @file{configure.ac}:
5574 @example
5575 # This example is obsolescent.
5576 # Nowadays you can omit these macro calls.
5577 AC_HEADER_STDC
5578 AC_CHECK_FUNCS([strchr memcpy])
5579 @end example
5581 @noindent
5582 then, in your code, you can use declarations like this:
5584 @example
5585 @group
5586 /* This example is obsolescent.
5587    Nowadays you can just #include <string.h>.  */
5588 #ifdef STDC_HEADERS
5589 # include <string.h>
5590 #else
5591 # ifndef HAVE_STRCHR
5592 #  define strchr index
5593 #  define strrchr rindex
5594 # endif
5595 char *strchr (), *strrchr ();
5596 # ifndef HAVE_MEMCPY
5597 #  define memcpy(d, s, n) bcopy ((s), (d), (n))
5598 #  define memmove(d, s, n) bcopy ((s), (d), (n))
5599 # endif
5600 #endif
5601 @end group
5602 @end example
5604 @noindent
5605 If you use a function like @code{memchr}, @code{memset}, @code{strtok},
5606 or @code{strspn}, which have no @acronym{BSD} equivalent, then macros don't
5607 suffice to port to ancient hosts; you must provide an implementation of
5608 each function.  An easy
5609 way to incorporate your implementations only when needed (since the ones
5610 in system C libraries may be hand optimized) is to, taking @code{memchr}
5611 for example, put it in @file{memchr.c} and use
5612 @samp{AC_REPLACE_FUNCS([memchr])}.
5613 @end defmac
5615 @defmac AC_HEADER_SYS_WAIT
5616 @acindex{HEADER_SYS_WAIT}
5617 @cvindex HAVE_SYS_WAIT_H
5618 @hdrindex{sys/wait.h}
5619 If @file{sys/wait.h} exists and is compatible with Posix, define
5620 @code{HAVE_SYS_WAIT_H}.  Incompatibility can occur if @file{sys/wait.h}
5621 does not exist, or if it uses the old @acronym{BSD} @code{union wait} instead
5622 of @code{int} to store a status value.  If @file{sys/wait.h} is not
5623 Posix compatible, then instead of including it, define the
5624 Posix macros with their usual interpretations.  Here is an
5625 example:
5627 @example
5628 @group
5629 #include <sys/types.h>
5630 #ifdef HAVE_SYS_WAIT_H
5631 # include <sys/wait.h>
5632 #endif
5633 #ifndef WEXITSTATUS
5634 # define WEXITSTATUS(stat_val) ((unsigned int) (stat_val) >> 8)
5635 #endif
5636 #ifndef WIFEXITED
5637 # define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
5638 #endif
5639 @end group
5640 @end example
5642 @noindent
5643 This macro is obsolescent, as current systems are compatible with Posix.
5644 New programs need not use this macro.
5645 @end defmac
5647 @cvindex _POSIX_VERSION
5648 @hdrindex{unistd.h}
5649 @code{_POSIX_VERSION} is defined when @file{unistd.h} is included on
5650 Posix systems.  If there is no @file{unistd.h}, it is definitely
5651 not a Posix system.  However, some non-Posix systems do
5652 have @file{unistd.h}.
5654 The way to check whether the system supports Posix is:
5656 @example
5657 @group
5658 #ifdef HAVE_UNISTD_H
5659 # include <sys/types.h>
5660 # include <unistd.h>
5661 #endif
5663 #ifdef _POSIX_VERSION
5664 /* Code for Posix systems.  */
5665 #endif
5666 @end group
5667 @end example
5669 @anchor{AC_HEADER_TIME}
5670 @defmac AC_HEADER_TIME
5671 @acindex{HEADER_TIME}
5672 @cvindex TIME_WITH_SYS_TIME
5673 @hdrindex{time.h}
5674 @hdrindex{sys/time.h}
5675 If a program may include both @file{time.h} and @file{sys/time.h},
5676 define @code{TIME_WITH_SYS_TIME}.  On some ancient systems,
5677 @file{sys/time.h} included @file{time.h}, but @file{time.h} was not
5678 protected against multiple inclusion, so programs could not explicitly
5679 include both files.  This macro is useful in programs that use, for
5680 example, @code{struct timeval} as well as
5681 @code{struct tm}.  It is best used in conjunction with
5682 @code{HAVE_SYS_TIME_H}, which can be checked for using
5683 @code{AC_CHECK_HEADERS([sys/time.h])}.
5685 @example
5686 @group
5687 #ifdef TIME_WITH_SYS_TIME
5688 # include <sys/time.h>
5689 # include <time.h>
5690 #else
5691 # ifdef HAVE_SYS_TIME_H
5692 #  include <sys/time.h>
5693 # else
5694 #  include <time.h>
5695 # endif
5696 #endif
5697 @end group
5698 @end example
5700 @noindent
5701 This macro is obsolescent, as current systems can include both files
5702 when they exist.  New programs need not use this macro.
5703 @end defmac
5706 @defmac AC_HEADER_TIOCGWINSZ
5707 @acindex{HEADER_TIOCGWINSZ}
5708 @cvindex GWINSZ_IN_SYS_IOCTL
5709 @hdrindex{sys/ioctl.h}
5710 @hdrindex{termios.h}
5711 @c FIXME: I need clarifications from Jim.
5712 If the use of @code{TIOCGWINSZ} requires @file{<sys/ioctl.h>}, then
5713 define @code{GWINSZ_IN_SYS_IOCTL}.  Otherwise @code{TIOCGWINSZ} can be
5714 found in @file{<termios.h>}.
5716 Use:
5718 @example
5719 @group
5720 #ifdef HAVE_TERMIOS_H
5721 # include <termios.h>
5722 #endif
5724 #ifdef GWINSZ_IN_SYS_IOCTL
5725 # include <sys/ioctl.h>
5726 #endif
5727 @end group
5728 @end example
5729 @end defmac
5731 @node Generic Headers
5732 @subsection Generic Header Checks
5734 These macros are used to find system header files not covered by the
5735 ``particular'' test macros.  If you need to check the contents of a header
5736 as well as find out whether it is present, you have to write your own
5737 test for it (@pxref{Writing Tests}).
5739 @anchor{AC_CHECK_HEADER}
5740 @defmac AC_CHECK_HEADER (@var{header-file}, @ovar{action-if-found}, @
5741   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
5742 @acindex{CHECK_HEADER}
5743 If the system header file @var{header-file} is compilable, execute shell
5744 commands @var{action-if-found}, otherwise execute
5745 @var{action-if-not-found}.  If you just want to define a symbol if the
5746 header file is available, consider using @code{AC_CHECK_HEADERS}
5747 instead.
5749 @var{includes} is a series of include directives, defaulting to
5750 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
5751 prior to the header under test.
5753 For compatibility issues with older versions of Autoconf, please read
5754 below.
5755 @end defmac
5757 @anchor{AC_CHECK_HEADERS}
5758 @defmac AC_CHECK_HEADERS (@var{header-file}@dots{}, @
5759   @ovar{action-if-found}, @ovar{action-if-not-found}, @
5760   @dvar{includes, AC_INCLUDES_DEFAULT})
5761 @acindex{CHECK_HEADERS}
5762 @cvindex HAVE_@var{header}
5763 For each given system header file @var{header-file} in the
5764 blank-separated argument list that exists, define
5765 @code{HAVE_@var{header-file}} (in all capitals).  If @var{action-if-found}
5766 is given, it is additional shell code to execute when one of the header
5767 files is found.  You can give it a value of @samp{break} to break out of
5768 the loop on the first match.  If @var{action-if-not-found} is given, it
5769 is executed when one of the header files is not found.
5771 @var{includes} is a series of include directives, defaulting to
5772 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
5773 prior to the headers under test.
5775 For compatibility issues with older versions of Autoconf, please read
5776 below.
5777 @end defmac
5779 Previous versions of Autoconf merely checked whether the header was
5780 accepted by the preprocessor.  This was changed because the old test was
5781 inappropriate for typical uses.  Headers are typically used to compile,
5782 not merely to preprocess, and the old behavior sometimes accepted
5783 headers that clashed at compile-time.  If you need to check whether a
5784 header is preprocessable, you can use @code{AC_PREPROC_IFELSE}
5785 (@pxref{Running the Preprocessor}).
5787 This scheme, which improves the robustness of the test, also requires
5788 that you make sure that headers that must be included before the
5789 @var{header-file} be part of the @var{includes}, (@pxref{Default
5790 Includes}).  If looking for @file{bar.h}, which requires that
5791 @file{foo.h} be included before if it exists, we suggest the following
5792 scheme:
5794 @verbatim
5795 AC_CHECK_HEADERS([foo.h])
5796 AC_CHECK_HEADERS([bar.h], [], [],
5797 [#ifdef HAVE_FOO_H
5798 # include <foo.h>
5799 # endif
5801 @end verbatim
5803 The following variant generates smaller, faster @command{configure}
5804 files if you do not need the full power of @code{AC_CHECK_HEADERS}.
5806 @defmac AC_CHECK_HEADERS_ONCE (@var{header-file}@dots{})
5807 @acindex{CHECK_HEADERS_ONCE}
5808 @cvindex HAVE_@var{header}
5809 For each given system header file @var{header-file} in the
5810 blank-separated argument list that exists, define
5811 @code{HAVE_@var{header-file}} (in all capitals).
5812 This is a once-only variant of @code{AC_CHECK_HEADERS}.  It generates the
5813 checking code at most once, so that @command{configure} is smaller and
5814 faster; but the checks cannot be conditionalized and are always done once,
5815 early during the @command{configure} run.
5816 @end defmac
5818 @node Declarations
5819 @section Declarations
5820 @cindex Declaration, checking
5822 The following macros check for the declaration of variables and
5823 functions.  If there is no macro specifically defined to check for a
5824 symbol you need, then you can use the general macros (@pxref{Generic
5825 Declarations}) or, for more complex tests, you may use
5826 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}).
5828 @menu
5829 * Particular Declarations::     Macros to check for certain declarations
5830 * Generic Declarations::        How to find other declarations
5831 @end menu
5833 @node Particular Declarations
5834 @subsection Particular Declaration Checks
5836 There are no specific macros for declarations.
5838 @node Generic Declarations
5839 @subsection Generic Declaration Checks
5841 These macros are used to find declarations not covered by the ``particular''
5842 test macros.
5844 @defmac AC_CHECK_DECL (@var{symbol}, @ovar{action-if-found}, @
5845   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
5846 @acindex{CHECK_DECL}
5847 If @var{symbol} (a function, variable, or constant) is not declared in
5848 @var{includes} and a declaration is needed, run the shell commands
5849 @var{action-if-not-found}, otherwise @var{action-if-found}.
5850 @var{includes} is a series of include directives, defaulting to
5851 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
5852 prior to the declaration under test.
5854 This macro actually tests whether @var{symbol} is defined as a macro or
5855 can be used as an r-value, not whether it is really declared, because it
5856 is much safer to avoid
5857 introducing extra declarations when they are not needed.
5858 @end defmac
5860 @anchor{AC_CHECK_DECLS}
5861 @defmac AC_CHECK_DECLS (@var{symbols}, @ovar{action-if-found}, @
5862   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
5863 @acindex{CHECK_DECLS}
5864 @cvindex HAVE_DECL_@var{symbol}
5865 For each of the @var{symbols} (@emph{comma}-separated list), define
5866 @code{HAVE_DECL_@var{symbol}} (in all capitals) to @samp{1} if
5867 @var{symbol} is declared, otherwise to @samp{0}.  If
5868 @var{action-if-not-found} is given, it is additional shell code to
5869 execute when one of the function declarations is needed, otherwise
5870 @var{action-if-found} is executed.
5872 @var{includes} is a series of include directives, defaulting to
5873 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
5874 prior to the declarations under test.
5876 This macro uses an M4 list as first argument:
5877 @example
5878 AC_CHECK_DECLS([strdup])
5879 AC_CHECK_DECLS([strlen])
5880 AC_CHECK_DECLS([malloc, realloc, calloc, free])
5881 AC_CHECK_DECLS([j0], [], [], [[#include <math.h>]])
5882 @end example
5884 Unlike the other @samp{AC_CHECK_*S} macros, when a @var{symbol} is not
5885 declared, @code{HAVE_DECL_@var{symbol}} is defined to @samp{0} instead
5886 of leaving @code{HAVE_DECL_@var{symbol}} undeclared.  When you are
5887 @emph{sure} that the check was performed, use
5888 @code{HAVE_DECL_@var{symbol}} in @code{#if}:
5890 @example
5891 #if !HAVE_DECL_SYMBOL
5892 extern char *symbol;
5893 #endif
5894 @end example
5896 @noindent
5897 If the test may have not been performed, however, because it is safer
5898 @emph{not} to declare a symbol than to use a declaration that conflicts
5899 with the system's one, you should use:
5901 @example
5902 #if defined HAVE_DECL_MALLOC && !HAVE_DECL_MALLOC
5903 void *malloc (size_t *s);
5904 #endif
5905 @end example
5907 @noindent
5908 You fall into the second category only in extreme situations: either
5909 your files may be used without being configured, or they are used during
5910 the configuration.  In most cases the traditional approach is enough.
5911 @end defmac
5913 @defmac AC_CHECK_DECLS_ONCE (@var{symbols})
5914 @acindex{CHECK_DECLS_ONCE}
5915 @cvindex HAVE_DECL_@var{symbol}
5916 For each of the @var{symbols} (@emph{comma}-separated list), define
5917 @code{HAVE_DECL_@var{symbol}} (in all capitals) to @samp{1} if
5918 @var{symbol} is declared in the default include files, otherwise to
5919 @samp{0}.  This is a once-only variant of @code{AC_CHECK_DECLS}.  It
5920 generates the checking code at most once, so that @command{configure} is
5921 smaller and faster; but the checks cannot be conditionalized and are
5922 always done once, early during the @command{configure} run.
5923 @end defmac
5926 @node Structures
5927 @section Structures
5928 @cindex Structure, checking
5930 The following macros check for the presence of certain members in C
5931 structures.  If there is no macro specifically defined to check for a
5932 member you need, then you can use the general structure-member macros
5933 (@pxref{Generic Structures}) or, for more complex tests, you may use
5934 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}).
5936 @menu
5937 * Particular Structures::       Macros to check for certain structure members
5938 * Generic Structures::          How to find other structure members
5939 @end menu
5941 @node Particular Structures
5942 @subsection Particular Structure Checks
5944 The following macros check for certain structures or structure members.
5946 @defmac AC_STRUCT_DIRENT_D_INO
5947 @acindex{STRUCT_DIRENT_D_INO}
5948 @cvindex HAVE_STRUCT_DIRENT_D_INO
5949 Perform all the actions of @code{AC_HEADER_DIRENT} (@pxref{Particular
5950 Headers}).  Then, if @code{struct dirent} contains a @code{d_ino}
5951 member, define @code{HAVE_STRUCT_DIRENT_D_INO}.
5953 @code{HAVE_STRUCT_DIRENT_D_INO} indicates only the presence of
5954 @code{d_ino}, not whether its contents are always reliable.
5955 Traditionally, a zero @code{d_ino} indicated a deleted directory entry,
5956 though current systems hide this detail from the user and never return
5957 zero @code{d_ino} values.
5958 Many current systems report an incorrect @code{d_ino} for a directory
5959 entry that is a mount point.
5960 @end defmac
5962 @defmac AC_STRUCT_DIRENT_D_TYPE
5963 @acindex{STRUCT_DIRENT_D_TYPE}
5964 @cvindex HAVE_STRUCT_DIRENT_D_TYPE
5965 Perform all the actions of @code{AC_HEADER_DIRENT} (@pxref{Particular
5966 Headers}).  Then, if @code{struct dirent} contains a @code{d_type}
5967 member, define @code{HAVE_STRUCT_DIRENT_D_TYPE}.
5968 @end defmac
5970 @anchor{AC_STRUCT_ST_BLOCKS}
5971 @defmac AC_STRUCT_ST_BLOCKS
5972 @acindex{STRUCT_ST_BLOCKS}
5973 @cvindex HAVE_STRUCT_STAT_ST_BLOCKS
5974 @cvindex HAVE_ST_BLOCKS
5975 @ovindex LIBOBJS
5976 If @code{struct stat} contains an @code{st_blocks} member, define
5977 @code{HAVE_STRUCT_STAT_ST_BLOCKS}.  Otherwise, require an
5978 @code{AC_LIBOBJ} replacement of @samp{fileblocks}.  The former name,
5979 @code{HAVE_ST_BLOCKS} is to be avoided, as its support will cease in the
5980 future.
5981 @end defmac
5983 @defmac AC_STRUCT_TM
5984 @acindex{STRUCT_TM}
5985 @cvindex TM_IN_SYS_TIME
5986 @hdrindex{time.h}
5987 @hdrindex{sys/time.h}
5988 If @file{time.h} does not define @code{struct tm}, define
5989 @code{TM_IN_SYS_TIME}, which means that including @file{sys/time.h}
5990 had better define @code{struct tm}.
5992 This macro is obsolescent, as @file{time.h} defines @code{struct tm} in
5993 current systems.  New programs need not use this macro.
5994 @end defmac
5996 @anchor{AC_STRUCT_TIMEZONE}
5997 @defmac AC_STRUCT_TIMEZONE
5998 @acindex{STRUCT_TIMEZONE}
5999 @cvindex HAVE_DECL_TZNAME
6000 @cvindex HAVE_STRUCT_TM_TM_ZONE
6001 @cvindex HAVE_TM_ZONE
6002 @cvindex HAVE_TZNAME
6003 Figure out how to get the current timezone.  If @code{struct tm} has a
6004 @code{tm_zone} member, define @code{HAVE_STRUCT_TM_TM_ZONE} (and the
6005 obsoleted @code{HAVE_TM_ZONE}).  Otherwise, if the external array
6006 @code{tzname} is found, define @code{HAVE_TZNAME}; if it is declared,
6007 define @code{HAVE_DECL_TZNAME}.
6008 @end defmac
6010 @node Generic Structures
6011 @subsection Generic Structure Checks
6013 These macros are used to find structure members not covered by the
6014 ``particular'' test macros.
6016 @defmac AC_CHECK_MEMBER (@var{aggregate}.@var{member}, @
6017   @ovar{action-if-found}, @ovar{action-if-not-found}, @
6018   @dvar{includes, AC_INCLUDES_DEFAULT})
6019 @acindex{CHECK_MEMBER}
6020 Check whether @var{member} is a member of the aggregate @var{aggregate}.
6021 If no @var{includes} are specified, the default includes are used
6022 (@pxref{Default Includes}).
6024 @example
6025 AC_CHECK_MEMBER([struct passwd.pw_gecos], [],
6026                 [AC_MSG_ERROR([We need `passwd.pw_gecos'!])],
6027                 [[#include <pwd.h>]])
6028 @end example
6030 You can use this macro for submembers:
6032 @example
6033 AC_CHECK_MEMBER(struct top.middle.bot)
6034 @end example
6035 @end defmac
6037 @anchor{AC_CHECK_MEMBERS}
6038 @defmac AC_CHECK_MEMBERS (@var{members}, @ovar{action-if-found}, @
6039   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6040 @acindex{CHECK_MEMBERS}
6041 @cvindex HAVE_@var{aggregate}_@var{member}
6042 Check for the existence of each @samp{@var{aggregate}.@var{member}} of
6043 @var{members} using the previous macro.  When @var{member} belongs to
6044 @var{aggregate}, define @code{HAVE_@var{aggregate}_@var{member}} (in all
6045 capitals, with spaces and dots replaced by underscores).  If
6046 @var{action-if-found} is given, it is executed for each of the found
6047 members.  If @var{action-if-not-found} is given, it is executed for each
6048 of the members that could not be found.
6050 @var{includes} is a series of include directives, defaulting to
6051 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
6052 prior to the members under test.
6054 This macro uses M4 lists:
6055 @example
6056 AC_CHECK_MEMBERS([struct stat.st_rdev, struct stat.st_blksize])
6057 @end example
6058 @end defmac
6061 @node Types
6062 @section Types
6063 @cindex Types
6064 @cindex C types
6066 The following macros check for C types, either builtin or typedefs.  If
6067 there is no macro specifically defined to check for a type you need, and
6068 you don't need to check for any special properties of it, then you can
6069 use a general type-check macro.
6071 @menu
6072 * Particular Types::            Special handling to find certain types
6073 * Generic Types::               How to find other types
6074 @end menu
6076 @node Particular Types
6077 @subsection Particular Type Checks
6079 @hdrindex{sys/types.h}
6080 @hdrindex{stdlib.h}
6081 @hdrindex{stdint.h}
6082 @hdrindex{inttypes.h}
6083 These macros check for particular C types in @file{sys/types.h},
6084 @file{stdlib.h}, @file{stdint.h}, @file{inttypes.h} and others, if they
6085 exist.
6087 The Gnulib @code{stdint} module is an alternate way to define many of
6088 these symbols; it is useful if you prefer your code to assume a
6089 C99-or-better environment.  @xref{Gnulib}.
6091 @anchor{AC_TYPE_GETGROUPS}
6092 @defmac AC_TYPE_GETGROUPS
6093 @acindex{TYPE_GETGROUPS}
6094 @cvindex GETGROUPS_T
6095 Define @code{GETGROUPS_T} to be whichever of @code{gid_t} or @code{int}
6096 is the base type of the array argument to @code{getgroups}.
6097 @end defmac
6099 @defmac AC_TYPE_INT8_T
6100 @acindex{TYPE_INT8_T}
6101 @cvindex HAVE_INT8_T
6102 @cvindex int8_t
6103 If @file{stdint.h} or @file{inttypes.h} does not define the type
6104 @code{int8_t}, define @code{int8_t} to a signed
6105 integer type that is exactly 8 bits wide and that uses two's complement
6106 representation, if such a type exists.
6107 If you are worried about porting to hosts that lack such a type, you can
6108 use the results of this macro in C89-or-later code as follows:
6110 @example
6111 #if HAVE_STDINT_H
6112 # include <stdint.h>
6113 #endif
6114 #if defined INT8_MAX || defined int8_t
6115  @emph{code using int8_t}
6116 #else
6117  @emph{complicated alternative using >8-bit 'signed char'}
6118 #endif
6119 @end example
6120 @end defmac
6122 @defmac AC_TYPE_INT16_T
6123 @acindex{TYPE_INT16_T}
6124 @cvindex HAVE_INT16_T
6125 @cvindex int16_t
6126 This is like @code{AC_TYPE_INT8_T}, except for 16-bit integers.
6127 @end defmac
6129 @defmac AC_TYPE_INT32_T
6130 @acindex{TYPE_INT32_T}
6131 @cvindex HAVE_INT32_T
6132 @cvindex int32_t
6133 This is like @code{AC_TYPE_INT8_T}, except for 32-bit integers.
6134 @end defmac
6136 @defmac AC_TYPE_INT64_T
6137 @acindex{TYPE_INT64_T}
6138 @cvindex HAVE_INT64_T
6139 @cvindex int64_t
6140 This is like @code{AC_TYPE_INT8_T}, except for 64-bit integers.
6141 @end defmac
6143 @defmac AC_TYPE_INTMAX_T
6144 @acindex{TYPE_INTMAX_T}
6145 @cvindex HAVE_INTMAX_T
6146 @cvindex intmax_t
6147 If @file{stdint.h} or @file{inttypes.h} defines the type @code{intmax_t},
6148 define @code{HAVE_INTMAX_T}.  Otherwise, define @code{intmax_t} to the
6149 widest signed integer type.
6150 @end defmac
6152 @defmac AC_TYPE_INTPTR_T
6153 @acindex{TYPE_INTPTR_T}
6154 @cvindex HAVE_INTPTR_T
6155 @cvindex intptr_t
6156 If @file{stdint.h} or @file{inttypes.h} defines the type @code{intptr_t},
6157 define @code{HAVE_INTPTR_T}.  Otherwise, define @code{intptr_t} to a
6158 signed integer type wide enough to hold a pointer, if such a type
6159 exists.
6160 @end defmac
6162 @defmac AC_TYPE_LONG_DOUBLE
6163 @acindex{TYPE_LONG_DOUBLE}
6164 @cvindex HAVE_LONG_DOUBLE
6165 If the C compiler supports a working @code{long double} type, define
6166 @code{HAVE_LONG_DOUBLE}.  The @code{long double} type might have the
6167 same range and precision as @code{double}.
6169 This macro is obsolescent, as current C compilers support @code{long
6170 double}.  New programs need not use this macro.
6171 @end defmac
6173 @defmac AC_TYPE_LONG_DOUBLE_WIDER
6174 @acindex{TYPE_LONG_DOUBLE_WIDER}
6175 @cvindex HAVE_LONG_DOUBLE_WIDER
6176 If the C compiler supports a working @code{long double} type with more
6177 range or precision than the @code{double} type, define
6178 @code{HAVE_LONG_DOUBLE_WIDER}.
6179 @end defmac
6181 @defmac AC_TYPE_LONG_LONG_INT
6182 @acindex{TYPE_LONG_LONG_INT}
6183 @cvindex HAVE_LONG_LONG_INT
6184 If the C compiler supports a working @code{long long int} type, define
6185 @code{HAVE_LONG_LONG_INT}.  However, this test does not test
6186 @code{long long int} values in preprocessor @code{#if} expressions,
6187 because too many compilers mishandle such expressions.
6188 @xref{Preprocessor Arithmetic}.
6189 @end defmac
6191 @defmac AC_TYPE_MBSTATE_T
6192 @acindex{TYPE_MBSTATE_T}
6193 @cvindex mbstate_t
6194 @hdrindex{wchar.h}
6195 Define @code{HAVE_MBSTATE_T} if @code{<wchar.h>} declares the
6196 @code{mbstate_t} type.  Also, define @code{mbstate_t} to be a type if
6197 @code{<wchar.h>} does not declare it.
6198 @end defmac
6200 @anchor{AC_TYPE_MODE_T}
6201 @defmac AC_TYPE_MODE_T
6202 @acindex{TYPE_MODE_T}
6203 @cvindex mode_t
6204 Define @code{mode_t} to a suitable type, if standard headers do not
6205 define it.
6206 @end defmac
6208 @anchor{AC_TYPE_OFF_T}
6209 @defmac AC_TYPE_OFF_T
6210 @acindex{TYPE_OFF_T}
6211 @cvindex off_t
6212 Define @code{off_t} to a suitable type, if standard headers do not
6213 define it.
6214 @end defmac
6216 @anchor{AC_TYPE_PID_T}
6217 @defmac AC_TYPE_PID_T
6218 @acindex{TYPE_PID_T}
6219 @cvindex pid_t
6220 Define @code{pid_t} to a suitable type, if standard headers do not
6221 define it.
6222 @end defmac
6224 @anchor{AC_TYPE_SIGNAL}
6225 @defmac AC_TYPE_SIGNAL
6226 @acindex{TYPE_SIGNAL}
6227 @cvindex RETSIGTYPE
6228 @hdrindex{signal.h}
6229 If @file{signal.h} declares @code{signal} as returning a pointer to a
6230 function returning @code{void}, define @code{RETSIGTYPE} to be
6231 @code{void}; otherwise, define it to be @code{int}.
6233 Define signal handlers as returning type @code{RETSIGTYPE}:
6235 @example
6236 @group
6237 RETSIGTYPE
6238 hup_handler ()
6240 @dots{}
6242 @end group
6243 @end example
6244 @end defmac
6246 @anchor{AC_TYPE_SIZE_T}
6247 @defmac AC_TYPE_SIZE_T
6248 @acindex{TYPE_SIZE_T}
6249 @cvindex size_t
6250 Define @code{size_t} to a suitable type, if standard headers do not
6251 define it.
6252 @end defmac
6254 @defmac AC_TYPE_SSIZE_T
6255 @acindex{TYPE_SSIZE_T}
6256 @cvindex ssize_t
6257 Define @code{ssize_t} to a suitable type, if standard headers do not
6258 define it.
6259 @end defmac
6261 @anchor{AC_TYPE_UID_T}
6262 @defmac AC_TYPE_UID_T
6263 @acindex{TYPE_UID_T}
6264 @cvindex uid_t
6265 @cvindex gid_t
6266 Define @code{uid_t} and @code{gid_t} to suitable types, if standard
6267 headers do not define them.
6268 @end defmac
6270 @defmac AC_TYPE_UINT8_T
6271 @acindex{TYPE_UINT8_T}
6272 @cvindex HAVE_UINT8_T
6273 @cvindex uint8_t
6274 If @file{stdint.h} or @file{inttypes.h} does not define the type
6275 @code{uint8_t}, define @code{uint8_t} to an
6276 unsigned integer type that is exactly 8 bits wide, if such a type
6277 exists.
6278 This is like @code{AC_TYPE_INT8_T}, except for unsigned integers.
6279 @end defmac
6281 @defmac AC_TYPE_UINT16_T
6282 @acindex{TYPE_UINT16_T}
6283 @cvindex HAVE_UINT16_T
6284 @cvindex uint16_t
6285 This is like @code{AC_TYPE_UINT8_T}, except for 16-bit integers.
6286 @end defmac
6288 @defmac AC_TYPE_UINT32_T
6289 @acindex{TYPE_UINT32_T}
6290 @cvindex HAVE_UINT32_T
6291 @cvindex uint32_t
6292 This is like @code{AC_TYPE_UINT8_T}, except for 32-bit integers.
6293 @end defmac
6295 @defmac AC_TYPE_UINT64_T
6296 @acindex{TYPE_UINT64_T}
6297 @cvindex HAVE_UINT64_T
6298 @cvindex uint64_t
6299 This is like @code{AC_TYPE_UINT8_T}, except for 64-bit integers.
6300 @end defmac
6302 @defmac AC_TYPE_UINTMAX_T
6303 @acindex{TYPE_UINTMAX_T}
6304 @cvindex HAVE_UINTMAX_T
6305 @cvindex uintmax_t
6306 If @file{stdint.h} or @file{inttypes.h} defines the type @code{uintmax_t},
6307 define @code{HAVE_UINTMAX_T}.  Otherwise, define @code{uintmax_t} to the
6308 widest unsigned integer type.
6309 @end defmac
6311 @defmac AC_TYPE_UINTPTR_T
6312 @acindex{TYPE_UINTPTR_T}
6313 @cvindex HAVE_UINTPTR_T
6314 @cvindex uintptr_t
6315 If @file{stdint.h} or @file{inttypes.h} defines the type @code{uintptr_t},
6316 define @code{HAVE_UINTPTR_T}.  Otherwise, define @code{uintptr_t} to an
6317 unsigned integer type wide enough to hold a pointer, if such a type
6318 exists.
6319 @end defmac
6321 @defmac AC_TYPE_UNSIGNED_LONG_LONG_INT
6322 @acindex{TYPE_UNSIGNED_LONG_LONG_INT}
6323 @cvindex HAVE_UNSIGNED_LONG_LONG_INT
6324 If the C compiler supports a working @code{unsigned long long int} type,
6325 define @code{HAVE_UNSIGNED_LONG_LONG_INT}.  However, this test does not test
6326 @code{unsigned long long int} values in preprocessor @code{#if} expressions,
6327 because too many compilers mishandle such expressions.
6328 @xref{Preprocessor Arithmetic}.
6329 @end defmac
6331 @node Generic Types
6332 @subsection Generic Type Checks
6334 These macros are used to check for types not covered by the ``particular''
6335 test macros.
6337 @defmac AC_CHECK_TYPE (@var{type}, @ovar{action-if-found}, @
6338   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6339 @acindex{CHECK_TYPE}
6340 Check whether @var{type} is defined.  It may be a compiler builtin type
6341 or defined by the @var{includes}.  @var{includes} is a series of include
6342 directives, defaulting to @code{AC_INCLUDES_DEFAULT} (@pxref{Default
6343 Includes}), which are used prior to the type under test.
6345 In C, @var{type} must be a type-name, so that the expression @samp{sizeof
6346 (@var{type})} is valid (but @samp{sizeof ((@var{type}))} is not).  The
6347 same test is applied when compiling for C++, which means that in C++
6348 @var{type} should be a type-id and should not be an anonymous
6349 @samp{struct} or @samp{union}.
6350 @end defmac
6353 @defmac AC_CHECK_TYPES (@var{types}, @ovar{action-if-found}, @
6354   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6355 @acindex{CHECK_TYPES}
6356 @cvindex HAVE_@var{type}
6357 For each @var{type} of the @var{types} that is defined, define
6358 @code{HAVE_@var{type}} (in all capitals).  Each @var{type} must follow
6359 the rules of @code{AC_CHECK_TYPE}.  If no @var{includes} are
6360 specified, the default includes are used (@pxref{Default Includes}).  If
6361 @var{action-if-found} is given, it is additional shell code to execute
6362 when one of the types is found.  If @var{action-if-not-found} is given,
6363 it is executed when one of the types is not found.
6365 This macro uses M4 lists:
6366 @example
6367 AC_CHECK_TYPES([ptrdiff_t])
6368 AC_CHECK_TYPES([unsigned long long int, uintmax_t])
6369 AC_CHECK_TYPES([float_t], [], [], [[#include <math.h>]])
6370 @end example
6372 @end defmac
6374 Autoconf, up to 2.13, used to provide to another version of
6375 @code{AC_CHECK_TYPE}, broken by design.  In order to keep backward
6376 compatibility, a simple heuristic, quite safe but not totally, is
6377 implemented.  In case of doubt, read the documentation of the former
6378 @code{AC_CHECK_TYPE}, see @ref{Obsolete Macros}.
6381 @node Compilers and Preprocessors
6382 @section Compilers and Preprocessors
6383 @cindex Compilers
6384 @cindex Preprocessors
6386 @ovindex EXEEXT
6387 All the tests for compilers (@code{AC_PROG_CC}, @code{AC_PROG_CXX},
6388 @code{AC_PROG_F77}) define the output variable @code{EXEEXT} based on
6389 the output of the compiler, typically to the empty string if
6390 Posix and @samp{.exe} if a @acronym{DOS} variant.
6392 @ovindex OBJEXT
6393 They also define the output variable @code{OBJEXT} based on the
6394 output of the compiler, after @file{.c} files have been excluded, typically
6395 to @samp{o} if Posix, @samp{obj} if a @acronym{DOS} variant.
6397 If the compiler being used does not produce executables, the tests fail.  If
6398 the executables can't be run, and cross-compilation is not enabled, they
6399 fail too.  @xref{Manual Configuration}, for more on support for cross
6400 compiling.
6402 @menu
6403 * Specific Compiler Characteristics::  Some portability issues
6404 * Generic Compiler Characteristics::  Language independent tests and features
6405 * C Compiler::                  Checking its characteristics
6406 * C++ Compiler::                Likewise
6407 * Objective C Compiler::        Likewise
6408 * Erlang Compiler and Interpreter::  Likewise
6409 * Fortran Compiler::            Likewise
6410 @end menu
6412 @node Specific Compiler Characteristics
6413 @subsection Specific Compiler Characteristics
6415 Some compilers exhibit different behaviors.
6417 @table @asis
6418 @item Static/Dynamic Expressions
6419 Autoconf relies on a trick to extract one bit of information from the C
6420 compiler: using negative array sizes.  For instance the following
6421 excerpt of a C source demonstrates how to test whether @samp{int} objects are 4
6422 bytes wide:
6424 @example
6425 static int test_array[sizeof (int) == 4 ? 1 : -1];
6426 @end example
6428 @noindent
6429 To our knowledge, there is a single compiler that does not support this
6430 trick: the @acronym{HP} C compilers (the real ones, not only the
6431 ``bundled'') on @acronym{HP-UX} 11.00.
6432 They incorrectly reject the above program with the diagnostic
6433 ``Variable-length arrays cannot have static storage.''
6434 This bug comes from @acronym{HP} compilers' mishandling of @code{sizeof (int)},
6435 not from the @code{? 1 : -1}, and
6436 Autoconf works around this problem by casting @code{sizeof (int)} to
6437 @code{long int} before comparing it.
6438 @end table
6440 @node Generic Compiler Characteristics
6441 @subsection Generic Compiler Characteristics
6443 @anchor{AC_CHECK_SIZEOF}
6444 @defmac AC_CHECK_SIZEOF (@var{type-or-expr}, @ovar{unused}, @
6445   @dvar{includes, AC_INCLUDES_DEFAULT})
6446 @acindex{CHECK_SIZEOF}
6447 @cvindex SIZEOF_@var{type-or-expr}
6448 Define @code{SIZEOF_@var{type-or-expr}} (@pxref{Standard Symbols}) to be
6449 the size in bytes of @var{type-or-expr}, which may be either a type or
6450 an expression returning a value that has a size.  If the expression
6451 @samp{sizeof (@var{type-or-expr})} is invalid, the result is 0.
6452 @var{includes} is a series of include directives, defaulting to
6453 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
6454 prior to the expression under test.
6456 This macro now works even when cross-compiling.  The @var{unused}
6457 argument was used when cross-compiling.
6459 For example, the call
6461 @example
6462 AC_CHECK_SIZEOF([int *])
6463 @end example
6465 @noindent
6466 defines @code{SIZEOF_INT_P} to be 8 on DEC Alpha AXP systems.
6467 @end defmac
6469 @defmac AC_CHECK_ALIGNOF (@var{type}, @dvar{includes, AC_INCLUDES_DEFAULT})
6470 @acindex{CHECK_ALIGNOF}
6471 @cvindex ALIGNOF_@var{type}
6472 Define @code{ALIGNOF_@var{type}} (@pxref{Standard Symbols}) to be the
6473 alignment in bytes of @var{type}.  @samp{@var{type} y;} must be valid as
6474 a structure member declaration.  If @samp{type} is unknown, the result
6475 is 0.  If no @var{includes} are specified, the default includes are used
6476 (@pxref{Default Includes}).
6477 @end defmac
6479 @defmac AC_COMPUTE_INT (@var{var}, @var{expression}, @
6480   @dvar{includes, AC_INCLUDES_DEFAULT}, @ovar{action-if-fails})
6481 @acindex{COMPUTE_INT}
6482 Store into the shell variable @var{var} the value of the integer
6483 @var{expression}.  The
6484 value should fit in an initializer in a C variable of type @code{signed
6485 long}.  To support cross compilation (in which case, the macro only works on
6486 hosts that use twos-complement arithmetic), it should be possible to evaluate
6487 the expression at compile-time.  If no @var{includes} are specified, the
6488 default includes are used (@pxref{Default Includes}).
6490 Execute @var{action-if-fails} if the value cannot be determined correctly.
6491 @end defmac
6493 @defmac AC_LANG_WERROR
6494 @acindex{LANG_WERROR}
6495 Normally Autoconf ignores warnings generated by the compiler, linker, and
6496 preprocessor.  If this macro is used, warnings count as fatal
6497 errors for the current language.  This macro is useful when the
6498 results of configuration are used where warnings are unacceptable; for
6499 instance, if parts of a program are built with the @acronym{GCC}
6500 @option{-Werror}
6501 option.  If the whole program is built using @option{-Werror} it is
6502 often simpler to put @option{-Werror} in the compiler flags (@code{CFLAGS},
6503 etc.).
6504 @end defmac
6506 @defmac AC_OPENMP
6507 @acindex{OPENMP}
6508 @cvindex _OPENMP
6509 @ovindex OPENMP_CFLAGS
6510 @ovindex OPENMP_CXXFLAGS
6511 @ovindex OPENMP_FFLAGS
6512 @ovindex OPENMP_FCFLAGS
6513 OpenMP (@url{http://www.openmp.org/}) specifies extensions of C, C++,
6514 and Fortran that simplify optimization of shared memory parallelism,
6515 which is a common problem on multicore CPUs.
6517 If the current language is C, the macro @code{AC_OPENMP} sets the
6518 variable @code{OPENMP_CFLAGS} to the C compiler flags needed for
6519 supporting OpenMP@.  @code{OPENMP_CFLAGS} is set to empty if the
6520 compiler already supports OpenMP, if it has no way to activate OpenMP
6521 support, or if the user rejects OpenMP support by invoking
6522 @samp{configure} with the @samp{--disable-openmp} option.
6524 @code{OPENMP_CFLAGS} needs to be used when compiling programs, when
6525 preprocessing program source, and when linking programs.  Therefore you
6526 need to add @code{$(OPENMP_CFLAGS)} to the @code{CFLAGS} of C programs
6527 that use OpenMP@.  If you preprocess OpenMP-specific C code, you also
6528 need to add @code{$(OPENMP_CFLAGS)} to @code{CPPFLAGS}.  The presence of
6529 OpenMP support is revealed at compile time by the preprocessor macro
6530 @code{_OPENMP}.
6532 Linking a program with @code{OPENMP_CFLAGS} typically adds one more
6533 shared library to the program's dependencies, so its use is recommended
6534 only on programs that actually require OpenMP.
6536 If the current language is C++, @code{AC_OPENMP} sets the variable
6537 @code{OPENMP_CXXFLAGS}, suitably for the C++ compiler.  The same remarks
6538 hold as for C.
6540 If the current language is Fortran 77 or Fortran, @code{AC_OPENMP} sets
6541 the variable @code{OPENMP_FFLAGS} or @code{OPENMP_FCFLAGS},
6542 respectively.  Similar remarks as for C hold, except that
6543 @code{CPPFLAGS} is not used for Fortran, and no preprocessor macro
6544 signals OpenMP support.
6545 @end defmac
6547 @node C Compiler
6548 @subsection C Compiler Characteristics
6550 The following macros provide ways to find and exercise a C Compiler.
6551 There are a few constructs that ought to be avoided, but do not deserve
6552 being checked for, since they can easily be worked around.
6554 @table @asis
6555 @item Don't use lines containing solitary backslashes
6556 They tickle a bug in the @acronym{HP-UX} C compiler (checked on
6557 @acronym{HP-UX} 10.20,
6558 11.00, and 11i).  When given the following source:
6560 @example
6561 #ifdef __STDC__
6563 * A comment with backslash-newlines in it.  %@{ %@} *\
6566 char str[] = "\\
6567 " A string with backslash-newlines in it %@{ %@} \\
6569 char apostrophe = '\\
6573 #endif
6574 @end example
6576 @noindent
6577 the compiler incorrectly fails with the diagnostics ``Non-terminating
6578 comment at end of file'' and ``Missing @samp{#endif} at end of file.''
6579 Removing the lines with solitary backslashes solves the problem.
6581 @item Don't compile several files at once if output matters to you
6582 Some compilers, such as @acronym{HP}'s, report names of files being
6583 compiled when given more than one file operand.  For instance:
6585 @example
6586 $ @kbd{cc a.c b.c}
6587 a.c:
6588 b.c:
6589 @end example
6591 @noindent
6592 This can cause problems if you observe the output of the compiler to
6593 detect failures.  Invoking @samp{cc -c a.c && cc -c b.c && cc -o c a.o
6594 b.o} solves the issue.
6596 @item Don't rely on @code{#error} failing
6597 The @sc{irix} C compiler does not fail when #error is preprocessed; it
6598 simply emits a diagnostic and continues, exiting successfully.  So,
6599 instead of an error directive like @code{#error "Unsupported word size"}
6600 it is more portable to use an invalid directive like @code{#Unsupported
6601 word size} in Autoconf tests.  In ordinary source code, @code{#error} is
6602 OK, since installers with inadequate compilers like @sc{irix} can simply
6603 examine these compilers' diagnostic output.
6605 @item Don't rely on correct @code{#line} support
6606 On Solaris, @command{c89} (at least Sun C 5.3 through 5.8)
6607 diagnoses @code{#line} directives whose line
6608 numbers are greater than 32767.  Nothing in Posix
6609 makes this invalid.  That is why Autoconf stopped issuing
6610 @code{#line} directives.
6611 @end table
6613 @defmac AC_PROG_CC (@ovar{compiler-search-list})
6614 @acindex{PROG_CC}
6615 @ovindex CC
6616 @ovindex CFLAGS
6617 Determine a C compiler to use.  If @code{CC} is not already set in the
6618 environment, check for @code{gcc} and @code{cc}, then for other C
6619 compilers.  Set output variable @code{CC} to the name of the compiler
6620 found.
6622 This macro may, however, be invoked with an optional first argument
6623 which, if specified, must be a blank-separated list of C compilers to
6624 search for.  This just gives the user an opportunity to specify an
6625 alternative search list for the C compiler.  For example, if you didn't
6626 like the default order, then you could invoke @code{AC_PROG_CC} like
6627 this:
6629 @example
6630 AC_PROG_CC([gcc cl cc])
6631 @end example
6633 If the C compiler does not handle function prototypes correctly by
6634 default, try to add an option to output variable @code{CC} to make it
6635 so.  This macro tries various options that select standard-conformance
6636 modes on various systems.
6638 After calling this macro you can check whether the C compiler has been
6639 set to accept @acronym{ANSI} C89 (@acronym{ISO} C90); if not, the shell
6640 variable
6641 @code{ac_cv_prog_cc_c89} is set to @samp{no}.  See also
6642 @code{AC_C_PROTOTYPES} below.
6644 If using the @acronym{GNU} C compiler, set shell variable @code{GCC} to
6645 @samp{yes}.  If output variable @code{CFLAGS} was not already set, set
6646 it to @option{-g -O2} for the @acronym{GNU} C compiler (@option{-O2} on systems
6647 where @acronym{GCC} does not accept @option{-g}), or @option{-g} for
6648 other compilers.
6649 @end defmac
6651 @anchor{AC_PROG_CC_C_O}
6652 @defmac AC_PROG_CC_C_O
6653 @acindex{PROG_CC_C_O}
6654 @cvindex NO_MINUS_C_MINUS_O
6655 If the C compiler does not accept the @option{-c} and @option{-o} options
6656 simultaneously, define @code{NO_MINUS_C_MINUS_O}.  This macro actually
6657 tests both the compiler found by @code{AC_PROG_CC}, and, if different,
6658 the first @code{cc} in the path.  The test fails if one fails.  This
6659 macro was created for @acronym{GNU} Make to choose the default C compilation
6660 rule.
6661 @end defmac
6664 @defmac AC_PROG_CPP
6665 @acindex{PROG_CPP}
6666 @ovindex CPP
6667 Set output variable @code{CPP} to a command that runs the
6668 C preprocessor.  If @samp{$CC -E} doesn't work, @file{/lib/cpp} is used.
6669 It is only portable to run @code{CPP} on files with a @file{.c}
6670 extension.
6672 Some preprocessors don't indicate missing include files by the error
6673 status.  For such preprocessors an internal variable is set that causes
6674 other macros to check the standard error from the preprocessor and
6675 consider the test failed if any warnings have been reported.
6676 For most preprocessors, though, warnings do not cause include-file
6677 tests to fail unless @code{AC_PROG_CPP_WERROR} is also specified.
6678 @end defmac
6680 @defmac AC_PROG_CPP_WERROR
6681 @acindex{PROG_CPP_WERROR}
6682 @ovindex CPP
6683 This acts like @code{AC_PROG_CPP}, except it treats warnings from the
6684 preprocessor as errors even if the preprocessor exit status indicates
6685 success.  This is useful for avoiding headers that generate mandatory
6686 warnings, such as deprecation notices.
6687 @end defmac
6690 The following macros check for C compiler or machine architecture
6691 features.  To check for characteristics not listed here, use
6692 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}) or
6693 @code{AC_RUN_IFELSE} (@pxref{Runtime}).
6695 @defmac AC_PROG_CC_STDC
6696 @acindex{PROG_CC_STDC}
6697 If the C compiler cannot compile @acronym{ISO} Standard C (currently
6698 C99), try to add an option to output variable @code{CC} to make it work.
6699 If the compiler does not support C99, fall back to supporting
6700 @acronym{ANSI} C89 (@acronym{ISO} C90).
6702 After calling this macro you can check whether the C compiler has been
6703 set to accept Standard C; if not, the shell variable
6704 @code{ac_cv_prog_cc_stdc} is set to @samp{no}.
6705 @end defmac
6707 @defmac AC_PROG_CC_C89
6708 @acindex{PROG_CC_C89}
6709 If the C compiler is not in @acronym{ANSI} C89 (@acronym{ISO} C90) mode by
6710 default, try to add an option to output variable @code{CC} to make it
6711 so.  This macro tries various options that select @acronym{ANSI} C89 on
6712 some system or another.  It considers the compiler to be in
6713 @acronym{ANSI} C89 mode if it handles function prototypes correctly.
6715 After calling this macro you can check whether the C compiler has been
6716 set to accept @acronym{ANSI} C89; if not, the shell variable
6717 @code{ac_cv_prog_cc_c89} is set to @samp{no}.
6719 This macro is called automatically by @code{AC_PROG_CC}.
6720 @end defmac
6722 @defmac AC_PROG_CC_C99
6723 @acindex{PROG_CC_C99}
6724 If the C compiler is not in C99 mode by default, try to add an
6725 option to output variable @code{CC} to make it so.  This macro tries
6726 various options that select C99 on some system or another.  It
6727 considers the compiler to be in C99 mode if it handles @code{_Bool},
6728 @code{//} comments, flexible array members, @code{inline}, signed and
6729 unsigned @code{long long int}, mixed code and declarations, named
6730 initialization of structs,
6731 @code{restrict}, @code{va_copy}, varargs macros, variable declarations
6732 in @code{for} loops, and variable length arrays.
6734 After calling this macro you can check whether the C compiler has been
6735 set to accept C99; if not, the shell variable
6736 @code{ac_cv_prog_cc_c99} is set to @samp{no}.
6737 @end defmac
6739 @defmac AC_C_BACKSLASH_A
6740 @acindex{C_BACKSLASH_A}
6741 @cvindex HAVE_C_BACKSLASH_A
6742 Define @samp{HAVE_C_BACKSLASH_A} to 1 if the C compiler understands
6743 @samp{\a}.
6745 This macro is obsolescent, as current C compilers understand @samp{\a}.
6746 New programs need not use this macro.
6747 @end defmac
6749 @anchor{AC_C_BIGENDIAN}
6750 @defmac AC_C_BIGENDIAN (@ovar{action-if-true}, @ovar{action-if-false}, @
6751   @ovar{action-if-unknown}, @ovar{action-if-universal})
6752 @acindex{C_BIGENDIAN}
6753 @cvindex WORDS_BIGENDIAN
6754 @cindex Endianness
6755 If words are stored with the most significant byte first (like Motorola
6756 and SPARC CPUs), execute @var{action-if-true}.  If words are stored with
6757 the least significant byte first (like Intel and VAX CPUs), execute
6758 @var{action-if-false}.
6760 This macro runs a test-case if endianness cannot be determined from the
6761 system header files.  When cross-compiling, the test-case is not run but
6762 grep'ed for some magic values.  @var{action-if-unknown} is executed if
6763 the latter case fails to determine the byte sex of the host system.
6765 In some cases a single run of a compiler can generate code for multiple
6766 architectures.  This can happen, for example, when generating Mac OS X
6767 universal binary files, which work on both PowerPC and Intel
6768 architectures.  In this case, the different variants might be for
6769 different architectures whose endiannesses differ.  If
6770 @command{configure} detects this, it executes @var{action-if-universal}
6771 instead of @var{action-if-unknown}.
6773 The default for @var{action-if-true} is to define
6774 @samp{WORDS_BIGENDIAN}.  The default for @var{action-if-false} is to do
6775 nothing.  The default for @var{action-if-unknown} is to
6776 abort configure and tell the installer how to bypass this test.
6777 And finally, the default for @var{action-if-universal} is to define
6778 @samp{WORDS_BIGENDIAN} or not, depending on the architecture that the
6779 code is being generated for.
6781 If you use this macro without specifying @var{action-if-universal}, you
6782 should also use @code{AC_CONFIG_HEADERS}; otherwise
6783 @samp{WORDS_BIGENDIAN} may be set incorrectly for Mac OS X universal
6784 binary files.
6785 @end defmac
6787 @anchor{AC_C_CONST}
6788 @defmac AC_C_CONST
6789 @acindex{C_CONST}
6790 @cvindex const
6791 If the C compiler does not fully support the @code{const} keyword,
6792 define @code{const} to be empty.  Some C compilers that do
6793 not define @code{__STDC__} do support @code{const}; some compilers that
6794 define @code{__STDC__} do not completely support @code{const}.  Programs
6795 can simply use @code{const} as if every C compiler supported it; for
6796 those that don't, the makefile or configuration header file
6797 defines it as empty.
6799 Occasionally installers use a C++ compiler to compile C code, typically
6800 because they lack a C compiler.  This causes problems with @code{const},
6801 because C and C++ treat @code{const} differently.  For example:
6803 @example
6804 const int foo;
6805 @end example
6807 @noindent
6808 is valid in C but not in C++.  These differences unfortunately cannot be
6809 papered over by defining @code{const} to be empty.
6811 If @command{autoconf} detects this situation, it leaves @code{const} alone,
6812 as this generally yields better results in practice.  However, using a
6813 C++ compiler to compile C code is not recommended or supported, and
6814 installers who run into trouble in this area should get a C compiler
6815 like @acronym{GCC} to compile their C code.
6817 This macro is obsolescent, as current C compilers support @code{const}.
6818 New programs need not use this macro.
6819 @end defmac
6821 @defmac AC_C_RESTRICT
6822 @acindex{C_RESTRICT}
6823 @cvindex restrict
6824 If the C compiler recognizes a variant spelling for the @code{restrict}
6825 keyword (@code{__restrict}, @code{__restrict__}, or @code{_Restrict}),
6826 then define @code{restrict} to that; this is more likely to do the right
6827 thing with compilers that support language variants where plain
6828 @code{restrict} is not a keyword.  Otherwise, if the C compiler
6829 recognizes the @code{restrict} keyword, don't do anything.
6830 Otherwise, define @code{restrict} to be empty.
6831 Thus, programs may simply use @code{restrict} as if every C compiler
6832 supported it; for those that do not, the makefile
6833 or configuration header defines it away.
6835 Although support in C++ for the @code{restrict} keyword is not
6836 required, several C++ compilers do accept the keyword.
6837 This macro works for them, too.
6838 @end defmac
6840 @defmac AC_C_VOLATILE
6841 @acindex{C_VOLATILE}
6842 @cvindex volatile
6843 If the C compiler does not understand the keyword @code{volatile},
6844 define @code{volatile} to be empty.  Programs can simply use
6845 @code{volatile} as if every C compiler supported it; for those that do
6846 not, the makefile or configuration header defines it as
6847 empty.
6849 If the correctness of your program depends on the semantics of
6850 @code{volatile}, simply defining it to be empty does, in a sense, break
6851 your code.  However, given that the compiler does not support
6852 @code{volatile}, you are at its mercy anyway.  At least your
6853 program compiles, when it wouldn't before.
6854 @xref{Volatile Objects}, for more about @code{volatile}.
6856 In general, the @code{volatile} keyword is a standard C feature, so
6857 you might expect that @code{volatile} is available only when
6858 @code{__STDC__} is defined.  However, Ultrix 4.3's native compiler does
6859 support volatile, but does not define @code{__STDC__}.
6861 This macro is obsolescent, as current C compilers support @code{volatile}.
6862 New programs need not use this macro.
6863 @end defmac
6865 @anchor{AC_C_INLINE}
6866 @defmac AC_C_INLINE
6867 @acindex{C_INLINE}
6868 @cvindex inline
6869 If the C compiler supports the keyword @code{inline}, do nothing.
6870 Otherwise define @code{inline} to @code{__inline__} or @code{__inline}
6871 if it accepts one of those, otherwise define @code{inline} to be empty.
6872 @end defmac
6874 @anchor{AC_C_CHAR_UNSIGNED}
6875 @defmac AC_C_CHAR_UNSIGNED
6876 @acindex{C_CHAR_UNSIGNED}
6877 @cvindex __CHAR_UNSIGNED__
6878 If the C type @code{char} is unsigned, define @code{__CHAR_UNSIGNED__},
6879 unless the C compiler predefines it.
6880 @end defmac
6882 @defmac AC_C_STRINGIZE
6883 @acindex{C_STRINGIZE}
6884 @cvindex HAVE_STRINGIZE
6885 If the C preprocessor supports the stringizing operator, define
6886 @code{HAVE_STRINGIZE}.  The stringizing operator is @samp{#} and is
6887 found in macros such as this:
6889 @example
6890 #define x(y) #y
6891 @end example
6893 This macro is obsolescent, as current C compilers support the
6894 stringizing operator.  New programs need not use this macro.
6895 @end defmac
6897 @defmac AC_C_FLEXIBLE_ARRAY_MEMBER
6898 @acindex{C_FLEXIBLE_ARRAY_MEMBER}
6899 @cvindex FLEXIBLE_ARRAY_MEMBER
6900 If the C compiler supports flexible array members, define
6901 @code{FLEXIBLE_ARRAY_MEMBER} to nothing; otherwise define it to 1.
6902 That way, a declaration like this:
6904 @example
6905 struct s
6906   @{
6907     size_t n_vals;
6908     double val[FLEXIBLE_ARRAY_MEMBER];
6909   @};
6910 @end example
6912 @noindent
6913 will let applications use the ``struct hack'' even with compilers that
6914 do not support flexible array members.  To allocate and use such an
6915 object, you can use code like this:
6917 @example
6918 size_t i;
6919 size_t n = compute_value_count ();
6920 struct s *p =
6921    malloc (offsetof (struct s, val)
6922            + n * sizeof (double));
6923 p->n_vals = n;
6924 for (i = 0; i < n; i++)
6925   p->val[i] = compute_value (i);
6926 @end example
6927 @end defmac
6929 @defmac AC_C_VARARRAYS
6930 @acindex{C_VARARRAYS}
6931 @cvindex HAVE_C_VARARRAYS
6932 If the C compiler supports variable-length arrays, define
6933 @code{HAVE_C_VARARRAYS}.  A variable-length array is an array of automatic
6934 storage duration whose length is determined at run time, when the array
6935 is declared.
6936 @end defmac
6938 @defmac AC_C_TYPEOF
6939 @acindex{C_TYPEOF}
6940 @cvindex HAVE_TYPEOF
6941 @cvindex typeof
6942 If the C compiler supports @acronym{GCC}'s @code{typeof} syntax either
6943 directly or
6944 through a different spelling of the keyword (e.g., @code{__typeof__}),
6945 define @code{HAVE_TYPEOF}.  If the support is available only through a
6946 different spelling, define @code{typeof} to that spelling.
6947 @end defmac
6949 @defmac AC_C_PROTOTYPES
6950 @acindex{C_PROTOTYPES}
6951 @cvindex PROTOTYPES
6952 @cvindex __PROTOTYPES
6953 @cvindex PARAMS
6954 If function prototypes are understood by the compiler (as determined by
6955 @code{AC_PROG_CC}), define @code{PROTOTYPES} and @code{__PROTOTYPES}.
6956 Defining @code{__PROTOTYPES} is for the benefit of
6957 header files that cannot use macros that infringe on user name space.
6959 This macro is obsolescent, as current C compilers support prototypes.
6960 New programs need not use this macro.
6961 @end defmac
6963 @anchor{AC_PROG_GCC_TRADITIONAL}
6964 @defmac AC_PROG_GCC_TRADITIONAL
6965 @acindex{PROG_GCC_TRADITIONAL}
6966 @ovindex CC
6967 Add @option{-traditional} to output variable @code{CC} if using the
6968 @acronym{GNU} C compiler and @code{ioctl} does not work properly without
6969 @option{-traditional}.  That usually happens when the fixed header files
6970 have not been installed on an old system.
6972 This macro is obsolescent, since current versions of the @acronym{GNU} C
6973 compiler fix the header files automatically when installed.
6974 @end defmac
6977 @node C++ Compiler
6978 @subsection C++ Compiler Characteristics
6981 @defmac AC_PROG_CXX (@ovar{compiler-search-list})
6982 @acindex{PROG_CXX}
6983 @ovindex CXX
6984 @ovindex CXXFLAGS
6985 Determine a C++ compiler to use.  Check whether the environment variable
6986 @code{CXX} or @code{CCC} (in that order) is set; if so, then set output
6987 variable @code{CXX} to its value.
6989 Otherwise, if the macro is invoked without an argument, then search for
6990 a C++ compiler under the likely names (first @code{g++} and @code{c++}
6991 then other names).  If none of those checks succeed, then as a last
6992 resort set @code{CXX} to @code{g++}.
6994 This macro may, however, be invoked with an optional first argument
6995 which, if specified, must be a blank-separated list of C++ compilers to
6996 search for.  This just gives the user an opportunity to specify an
6997 alternative search list for the C++ compiler.  For example, if you
6998 didn't like the default order, then you could invoke @code{AC_PROG_CXX}
6999 like this:
7001 @example
7002 AC_PROG_CXX([gcc cl KCC CC cxx cc++ xlC aCC c++ g++])
7003 @end example
7005 If using the @acronym{GNU} C++ compiler, set shell variable @code{GXX} to
7006 @samp{yes}.  If output variable @code{CXXFLAGS} was not already set, set
7007 it to @option{-g -O2} for the @acronym{GNU} C++ compiler (@option{-O2} on
7008 systems where G++ does not accept @option{-g}), or @option{-g} for other
7009 compilers.
7010 @end defmac
7012 @defmac AC_PROG_CXXCPP
7013 @acindex{PROG_CXXCPP}
7014 @ovindex CXXCPP
7015 Set output variable @code{CXXCPP} to a command that runs the C++
7016 preprocessor.  If @samp{$CXX -E} doesn't work, @file{/lib/cpp} is used.
7017 It is portable to run @code{CXXCPP} only on files with a @file{.c},
7018 @file{.C}, @file{.cc}, or @file{.cpp} extension.
7020 Some preprocessors don't indicate missing include files by the error
7021 status.  For such preprocessors an internal variable is set that causes
7022 other macros to check the standard error from the preprocessor and
7023 consider the test failed if any warnings have been reported.  However,
7024 it is not known whether such broken preprocessors exist for C++.
7025 @end defmac
7027 @defmac AC_PROG_CXX_C_O
7028 @acindex{PROG_CXX_C_O}
7029 @cvindex CXX_NO_MINUS_C_MINUS_O
7030 Test whether the C++ compiler accepts the options @option{-c} and
7031 @option{-o} simultaneously, and define @code{CXX_NO_MINUS_C_MINUS_O},
7032 if it does not.
7033 @end defmac
7036 @node Objective C Compiler
7037 @subsection Objective C Compiler Characteristics
7040 @defmac AC_PROG_OBJC (@ovar{compiler-search-list})
7041 @acindex{PROG_OBJC}
7042 @ovindex OBJC
7043 @ovindex OBJCFLAGS
7044 Determine an Objective C compiler to use.  If @code{OBJC} is not already
7045 set in the environment, check for Objective C compilers.  Set output
7046 variable @code{OBJC} to the name of the compiler found.
7048 This macro may, however, be invoked with an optional first argument
7049 which, if specified, must be a blank-separated list of Objective C compilers to
7050 search for.  This just gives the user an opportunity to specify an
7051 alternative search list for the Objective C compiler.  For example, if you
7052 didn't like the default order, then you could invoke @code{AC_PROG_OBJC}
7053 like this:
7055 @example
7056 AC_PROG_OBJC([gcc objcc objc])
7057 @end example
7059 If using the @acronym{GNU} Objective C compiler, set shell variable
7060 @code{GOBJC} to @samp{yes}.  If output variable @code{OBJCFLAGS} was not
7061 already set, set it to @option{-g -O2} for the @acronym{GNU} Objective C
7062 compiler (@option{-O2} on systems where @command{gcc} does not accept
7063 @option{-g}), or @option{-g} for other compilers.
7064 @end defmac
7066 @defmac AC_PROG_OBJCPP
7067 @acindex{PROG_OBJCPP}
7068 @ovindex OBJCPP
7069 Set output variable @code{OBJCPP} to a command that runs the Objective C
7070 preprocessor.  If @samp{$OBJC -E} doesn't work, @file{/lib/cpp} is used.
7071 @end defmac
7074 @node Erlang Compiler and Interpreter
7075 @subsection Erlang Compiler and Interpreter Characteristics
7076 @cindex Erlang
7078 Autoconf defines the following macros for determining paths to the essential
7079 Erlang/OTP programs:
7081 @defmac AC_ERLANG_PATH_ERLC (@ovar{value-if-not-found}, @dvar{path, $PATH})
7082 @acindex{ERLANG_PATH_ERLC}
7083 @ovindex ERLC
7084 @ovindex ERLCFLAGS
7085 Determine an Erlang compiler to use.  If @code{ERLC} is not already set in the
7086 environment, check for @command{erlc}.  Set output variable @code{ERLC} to the
7087 complete path of the compiler command found.  In addition, if @code{ERLCFLAGS}
7088 is not set in the environment, set it to an empty value.
7090 The two optional arguments have the same meaning as the two last arguments of
7091 macro @code{AC_PROG_PATH} for looking for the @command{erlc} program.  For
7092 example, to look for @command{erlc} only in the @file{/usr/lib/erlang/bin}
7093 directory:
7095 @example
7096 AC_ERLANG_PATH_ERLC([not found], [/usr/lib/erlang/bin])
7097 @end example
7098 @end defmac
7100 @defmac AC_ERLANG_NEED_ERLC (@dvar{path, $PATH})
7101 @acindex{ERLANG_NEED_ERLC}
7102 A simplified variant of the @code{AC_ERLANG_PATH_ERLC} macro, that prints an
7103 error message and exits the @command{configure} script if the @command{erlc}
7104 program is not found.
7105 @end defmac
7107 @defmac AC_ERLANG_PATH_ERL (@ovar{value-if-not-found}, @dvar{path, $PATH})
7108 @acindex{ERLANG_PATH_ERL}
7109 @ovindex ERL
7110 Determine an Erlang interpreter to use.  If @code{ERL} is not already
7111 set in the
7112 environment, check for @command{erl}.  Set output variable @code{ERL} to the
7113 complete path of the interpreter command found.
7115 The two optional arguments have the same meaning as the two last arguments of
7116 macro @code{AC_PROG_PATH} for looking for the @command{erl} program.  For
7117 example, to look for @command{erl} only in the @file{/usr/lib/erlang/bin}
7118 directory:
7120 @example
7121 AC_ERLANG_PATH_ERL([not found], [/usr/lib/erlang/bin])
7122 @end example
7123 @end defmac
7125 @defmac AC_ERLANG_NEED_ERL (@dvar{path, $PATH})
7126 @acindex{ERLANG_NEED_ERL}
7127 A simplified variant of the @code{AC_ERLANG_PATH_ERL} macro, that prints an
7128 error message and exits the @command{configure} script if the @command{erl}
7129 program is not found.
7130 @end defmac
7133 @node Fortran Compiler
7134 @subsection Fortran Compiler Characteristics
7135 @cindex Fortran
7136 @cindex F77
7138 The Autoconf Fortran support is divided into two categories: legacy
7139 Fortran 77 macros (@code{F77}), and modern Fortran macros (@code{FC}).
7140 The former are intended for traditional Fortran 77 code, and have output
7141 variables like @code{F77}, @code{FFLAGS}, and @code{FLIBS}.  The latter
7142 are for newer programs that can (or must) compile under the newer
7143 Fortran standards, and have output variables like @code{FC},
7144 @code{FCFLAGS}, and @code{FCLIBS}.
7146 Except for two new macros @code{AC_FC_SRCEXT} and
7147 @code{AC_FC_FREEFORM} (see below), the @code{FC} and @code{F77} macros
7148 behave almost identically, and so they are documented together in this
7149 section.
7152 @defmac AC_PROG_F77 (@ovar{compiler-search-list})
7153 @acindex{PROG_F77}
7154 @ovindex F77
7155 @ovindex FFLAGS
7156 Determine a Fortran 77 compiler to use.  If @code{F77} is not already
7157 set in the environment, then check for @code{g77} and @code{f77}, and
7158 then some other names.  Set the output variable @code{F77} to the name
7159 of the compiler found.
7161 This macro may, however, be invoked with an optional first argument
7162 which, if specified, must be a blank-separated list of Fortran 77
7163 compilers to search for.  This just gives the user an opportunity to
7164 specify an alternative search list for the Fortran 77 compiler.  For
7165 example, if you didn't like the default order, then you could invoke
7166 @code{AC_PROG_F77} like this:
7168 @example
7169 AC_PROG_F77([fl32 f77 fort77 xlf g77 f90 xlf90])
7170 @end example
7172 If using @code{g77} (the @acronym{GNU} Fortran 77 compiler), then
7173 set the shell variable @code{G77} to @samp{yes}.
7174 If the output variable @code{FFLAGS} was not already set in the
7175 environment, then set it to @option{-g -02} for @code{g77} (or @option{-O2}
7176 where @code{g77} does not accept @option{-g}).  Otherwise, set
7177 @code{FFLAGS} to @option{-g} for all other Fortran 77 compilers.
7178 @end defmac
7180 @defmac AC_PROG_FC (@ovar{compiler-search-list}, @ovar{dialect})
7181 @acindex{PROG_FC}
7182 @ovindex FC
7183 @ovindex FCFLAGS
7184 Determine a Fortran compiler to use.  If @code{FC} is not already set in
7185 the environment, then @code{dialect} is a hint to indicate what Fortran
7186 dialect to search for; the default is to search for the newest available
7187 dialect.  Set the output variable @code{FC} to the name of the compiler
7188 found.
7190 By default, newer dialects are preferred over older dialects, but if
7191 @code{dialect} is specified then older dialects are preferred starting
7192 with the specified dialect.  @code{dialect} can currently be one of
7193 Fortran 77, Fortran 90, or Fortran 95.  However, this is only a hint of
7194 which compiler @emph{name} to prefer (e.g., @code{f90} or @code{f95}),
7195 and no attempt is made to guarantee that a particular language standard
7196 is actually supported.  Thus, it is preferable that you avoid the
7197 @code{dialect} option, and use AC_PROG_FC only for code compatible with
7198 the latest Fortran standard.
7200 This macro may, alternatively, be invoked with an optional first argument
7201 which, if specified, must be a blank-separated list of Fortran
7202 compilers to search for, just as in @code{AC_PROG_F77}.
7204 If the output variable @code{FCFLAGS} was not already set in the
7205 environment, then set it to @option{-g -02} for @acronym{GNU} @code{g77} (or
7206 @option{-O2} where @code{g77} does not accept @option{-g}).  Otherwise,
7207 set @code{FCFLAGS} to @option{-g} for all other Fortran compilers.
7208 @end defmac
7210 @defmac AC_PROG_F77_C_O
7211 @defmacx AC_PROG_FC_C_O
7212 @acindex{PROG_F77_C_O}
7213 @acindex{PROG_FC_C_O}
7214 @cvindex F77_NO_MINUS_C_MINUS_O
7215 @cvindex FC_NO_MINUS_C_MINUS_O
7216 Test whether the Fortran compiler accepts the options @option{-c} and
7217 @option{-o} simultaneously, and define @code{F77_NO_MINUS_C_MINUS_O} or
7218 @code{FC_NO_MINUS_C_MINUS_O}, respectively, if it does not.
7219 @end defmac
7221 The following macros check for Fortran compiler characteristics.
7222 To check for characteristics not listed here, use
7223 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}) or
7224 @code{AC_RUN_IFELSE} (@pxref{Runtime}), making sure to first set the
7225 current language to Fortran 77 or Fortran via @code{AC_LANG([Fortran 77])}
7226 or @code{AC_LANG(Fortran)} (@pxref{Language Choice}).
7229 @defmac AC_F77_LIBRARY_LDFLAGS
7230 @defmacx AC_FC_LIBRARY_LDFLAGS
7231 @acindex{F77_LIBRARY_LDFLAGS}
7232 @ovindex FLIBS
7233 @acindex{FC_LIBRARY_LDFLAGS}
7234 @ovindex FCLIBS
7235 Determine the linker flags (e.g., @option{-L} and @option{-l}) for the
7236 @dfn{Fortran intrinsic and runtime libraries} that are required to
7237 successfully link a Fortran program or shared library.  The output
7238 variable @code{FLIBS} or @code{FCLIBS} is set to these flags (which
7239 should be included after @code{LIBS} when linking).
7241 This macro is intended to be used in those situations when it is
7242 necessary to mix, e.g., C++ and Fortran source code in a single
7243 program or shared library (@pxref{Mixing Fortran 77 With C and C++, , ,
7244 automake, @acronym{GNU} Automake}).
7246 For example, if object files from a C++ and Fortran compiler must be
7247 linked together, then the C++ compiler/linker must be used for linking
7248 (since special C++-ish things need to happen at link time like calling
7249 global constructors, instantiating templates, enabling exception
7250 support, etc.).
7252 However, the Fortran intrinsic and runtime libraries must be linked in
7253 as well, but the C++ compiler/linker doesn't know by default how to add
7254 these Fortran 77 libraries.  Hence, this macro was created to determine
7255 these Fortran libraries.
7257 The macros @code{AC_F77_DUMMY_MAIN} and @code{AC_FC_DUMMY_MAIN} or
7258 @code{AC_F77_MAIN} and @code{AC_FC_MAIN} are probably also necessary to
7259 link C/C++ with Fortran; see below.
7260 @end defmac
7262 @defmac AC_F77_DUMMY_MAIN (@ovar{action-if-found}, @ovar{action-if-not-found})
7263 @defmacx AC_FC_DUMMY_MAIN (@ovar{action-if-found}, @ovar{action-if-not-found})
7264 @acindex{F77_DUMMY_MAIN}
7265 @cvindex F77_DUMMY_MAIN
7266 With many compilers, the Fortran libraries detected by
7267 @code{AC_F77_LIBRARY_LDFLAGS} or @code{AC_FC_LIBRARY_LDFLAGS} provide
7268 their own @code{main} entry function that initializes things like
7269 Fortran I/O, and which then calls a user-provided entry function named
7270 (say) @code{MAIN__} to run the user's program.  The
7271 @code{AC_F77_DUMMY_MAIN} and @code{AC_FC_DUMMY_MAIN} or
7272 @code{AC_F77_MAIN} and @code{AC_FC_MAIN} macros figure out how to deal with
7273 this interaction.
7275 When using Fortran for purely numerical functions (no I/O, etc.)@: often
7276 one prefers to provide one's own @code{main} and skip the Fortran
7277 library initializations.  In this case, however, one may still need to
7278 provide a dummy @code{MAIN__} routine in order to prevent linking errors
7279 on some systems.  @code{AC_F77_DUMMY_MAIN} or @code{AC_FC_DUMMY_MAIN}
7280 detects whether any such routine is @emph{required} for linking, and
7281 what its name is; the shell variable @code{F77_DUMMY_MAIN} or
7282 @code{FC_DUMMY_MAIN} holds this name, @code{unknown} when no solution
7283 was found, and @code{none} when no such dummy main is needed.
7285 By default, @var{action-if-found} defines @code{F77_DUMMY_MAIN} or
7286 @code{FC_DUMMY_MAIN} to the name of this routine (e.g., @code{MAIN__})
7287 @emph{if} it is required.  @var{action-if-not-found} defaults to
7288 exiting with an error.
7290 In order to link with Fortran routines, the user's C/C++ program should
7291 then include the following code to define the dummy main if it is
7292 needed:
7294 @example
7295 #ifdef F77_DUMMY_MAIN
7296 #  ifdef __cplusplus
7297      extern "C"
7298 #  endif
7299    int F77_DUMMY_MAIN() @{ return 1; @}
7300 #endif
7301 @end example
7303 (Replace @code{F77} with @code{FC} for Fortran instead of Fortran 77.)
7305 Note that this macro is called automatically from @code{AC_F77_WRAPPERS}
7306 or @code{AC_FC_WRAPPERS}; there is generally no need to call it
7307 explicitly unless one wants to change the default actions.
7308 @end defmac
7310 @defmac AC_F77_MAIN
7311 @defmacx AC_FC_MAIN
7312 @acindex{F77_MAIN}
7313 @cvindex F77_MAIN
7314 @acindex{FC_MAIN}
7315 @cvindex FC_MAIN
7316 As discussed above, many Fortran libraries allow you to provide an entry
7317 point called (say) @code{MAIN__} instead of the usual @code{main}, which
7318 is then called by a @code{main} function in the Fortran libraries that
7319 initializes things like Fortran I/O@.  The
7320 @code{AC_F77_MAIN} and @code{AC_FC_MAIN} macros detect whether it is
7321 @emph{possible} to utilize such an alternate main function, and defines
7322 @code{F77_MAIN} and @code{FC_MAIN} to the name of the function.  (If no
7323 alternate main function name is found, @code{F77_MAIN} and @code{FC_MAIN} are
7324 simply defined to @code{main}.)
7326 Thus, when calling Fortran routines from C that perform things like I/O,
7327 one should use this macro and declare the "main" function like so:
7329 @example
7330 #ifdef __cplusplus
7331   extern "C"
7332 #endif
7333 int F77_MAIN(int argc, char *argv[]);
7334 @end example
7336 (Again, replace @code{F77} with @code{FC} for Fortran instead of Fortran 77.)
7337 @end defmac
7339 @defmac AC_F77_WRAPPERS
7340 @defmacx AC_FC_WRAPPERS
7341 @acindex{F77_WRAPPERS}
7342 @cvindex F77_FUNC
7343 @cvindex F77_FUNC_
7344 @acindex{FC_WRAPPERS}
7345 @cvindex FC_FUNC
7346 @cvindex FC_FUNC_
7347 Defines C macros @code{F77_FUNC (name, NAME)}, @code{FC_FUNC (name, NAME)},
7348 @code{F77_FUNC_(name, NAME)}, and @code{FC_FUNC_(name, NAME)} to properly
7349 mangle the names of C/C++ identifiers, and identifiers with underscores,
7350 respectively, so that they match the name-mangling scheme used by the
7351 Fortran compiler.
7353 Fortran is case-insensitive, and in order to achieve this the Fortran
7354 compiler converts all identifiers into a canonical case and format.  To
7355 call a Fortran subroutine from C or to write a C function that is
7356 callable from Fortran, the C program must explicitly use identifiers in
7357 the format expected by the Fortran compiler.  In order to do this, one
7358 simply wraps all C identifiers in one of the macros provided by
7359 @code{AC_F77_WRAPPERS} or @code{AC_FC_WRAPPERS}.  For example, suppose
7360 you have the following Fortran 77 subroutine:
7362 @example
7363       subroutine foobar (x, y)
7364       double precision x, y
7365       y = 3.14159 * x
7366       return
7367       end
7368 @end example
7370 You would then declare its prototype in C or C++ as:
7372 @example
7373 #define FOOBAR_F77 F77_FUNC (foobar, FOOBAR)
7374 #ifdef __cplusplus
7375 extern "C"  /* prevent C++ name mangling */
7376 #endif
7377 void FOOBAR_F77(double *x, double *y);
7378 @end example
7380 Note that we pass both the lowercase and uppercase versions of the
7381 function name to @code{F77_FUNC} so that it can select the right one.
7382 Note also that all parameters to Fortran 77 routines are passed as
7383 pointers (@pxref{Mixing Fortran 77 With C and C++, , , automake, @acronym{GNU}
7384 Automake}).
7386 (Replace @code{F77} with @code{FC} for Fortran instead of Fortran 77.)
7388 Although Autoconf tries to be intelligent about detecting the
7389 name-mangling scheme of the Fortran compiler, there may be Fortran
7390 compilers that it doesn't support yet.  In this case, the above code
7391 generates a compile-time error, but some other behavior
7392 (e.g., disabling Fortran-related features) can be induced by checking
7393 whether @code{F77_FUNC} or @code{FC_FUNC} is defined.
7395 Now, to call that routine from a C program, we would do something like:
7397 @example
7399     double x = 2.7183, y;
7400     FOOBAR_F77 (&x, &y);
7402 @end example
7404 If the Fortran identifier contains an underscore (e.g., @code{foo_bar}),
7405 you should use @code{F77_FUNC_} or @code{FC_FUNC_} instead of
7406 @code{F77_FUNC} or @code{FC_FUNC} (with the same arguments).  This is
7407 because some Fortran compilers mangle names differently if they contain
7408 an underscore.
7409 @end defmac
7411 @defmac AC_F77_FUNC (@var{name}, @ovar{shellvar})
7412 @defmacx AC_FC_FUNC (@var{name}, @ovar{shellvar})
7413 @acindex{F77_FUNC}
7414 @acindex{FC_FUNC}
7415 Given an identifier @var{name}, set the shell variable @var{shellvar} to
7416 hold the mangled version @var{name} according to the rules of the
7417 Fortran linker (see also @code{AC_F77_WRAPPERS} or
7418 @code{AC_FC_WRAPPERS}).  @var{shellvar} is optional; if it is not
7419 supplied, the shell variable is simply @var{name}.  The purpose of
7420 this macro is to give the caller a way to access the name-mangling
7421 information other than through the C preprocessor as above, for example,
7422 to call Fortran routines from some language other than C/C++.
7423 @end defmac
7425 @defmac AC_FC_SRCEXT (@var{ext}, @ovar{action-if-success}, @
7426   @ovar{action-if-failure})
7427 @acindex{FC_SRCEXT}
7428 By default, the @code{FC} macros perform their tests using a @file{.f}
7429 extension for source-code files.  Some compilers, however, only enable
7430 newer language features for appropriately named files, e.g., Fortran 90
7431 features only for @file{.f90} files.  On the other hand, some other
7432 compilers expect all source files to end in @file{.f} and require
7433 special flags to support other file name extensions.  The
7434 @code{AC_FC_SRCEXT} macro deals with both of these issues.
7436 The @code{AC_FC_SRCEXT} tries to get the @code{FC} compiler to accept files
7437 ending with the extension .@var{ext} (i.e., @var{ext} does @emph{not}
7438 contain the dot).  If any special compiler flags are needed for this, it
7439 stores them in the output variable @code{FCFLAGS_}@var{ext}.  This
7440 extension and these flags are then used for all subsequent @code{FC} tests
7441 (until @code{AC_FC_SRCEXT} is called again).
7443 For example, you would use @code{AC_FC_SRCEXT(f90)} to employ the
7444 @file{.f90} extension in future tests, and it would set a
7445 @code{FCFLAGS_f90} output variable with any extra flags that are needed
7446 to compile such files.
7448 The @code{FCFLAGS_}@var{ext} can @emph{not} be simply absorbed into
7449 @code{FCFLAGS}, for two reasons based on the limitations of some
7450 compilers.  First, only one @code{FCFLAGS_}@var{ext} can be used at a
7451 time, so files with different extensions must be compiled separately.
7452 Second, @code{FCFLAGS_}@var{ext} must appear @emph{immediately} before
7453 the source-code file name when compiling.  So, continuing the example
7454 above, you might compile a @file{foo.f90} file in your makefile with the
7455 command:
7457 @example
7458 foo.o: foo.f90
7459      $(FC) -c $(FCFLAGS) $(FCFLAGS_f90) '$(srcdir)/foo.f90'
7460 @end example
7462 If @code{AC_FC_SRCEXT} succeeds in compiling files with the @var{ext}
7463 extension, it calls @var{action-if-success} (defaults to nothing).  If
7464 it fails, and cannot find a way to make the @code{FC} compiler accept such
7465 files, it calls @var{action-if-failure} (defaults to exiting with an
7466 error message).
7468 @end defmac
7470 @defmac AC_FC_FREEFORM (@ovar{action-if-success}, @ovar{action-if-failure})
7471 @acindex{FC_FREEFORM}
7473 The @code{AC_FC_FREEFORM} tries to ensure that the Fortran compiler
7474 (@code{$FC}) allows free-format source code (as opposed to the older
7475 fixed-format style from Fortran 77).  If necessary, it may add some
7476 additional flags to @code{FCFLAGS}.
7478 This macro is most important if you are using the default @file{.f}
7479 extension, since many compilers interpret this extension as indicating
7480 fixed-format source unless an additional flag is supplied.  If you
7481 specify a different extension with @code{AC_FC_SRCEXT}, such as
7482 @file{.f90} or @file{.f95}, then @code{AC_FC_FREEFORM} ordinarily
7483 succeeds without modifying @code{FCFLAGS}.
7485 If @code{AC_FC_FREEFORM} succeeds in compiling free-form source, it
7486 calls @var{action-if-success} (defaults to nothing).  If it fails, it
7487 calls @var{action-if-failure} (defaults to exiting with an error
7488 message).
7489 @end defmac
7491 @node System Services
7492 @section System Services
7494 The following macros check for operating system services or capabilities.
7496 @anchor{AC_PATH_X}
7497 @defmac AC_PATH_X
7498 @acindex{PATH_X}
7499 @evindex XMKMF
7500 @cindex X Window System
7501 Try to locate the X Window System include files and libraries.  If the
7502 user gave the command line options @option{--x-includes=@var{dir}} and
7503 @option{--x-libraries=@var{dir}}, use those directories.
7505 If either or both were not given, get the missing values by running
7506 @code{xmkmf} (or an executable pointed to by the @code{XMKMF}
7507 environment variable) on a trivial @file{Imakefile} and examining the
7508 makefile that it produces.  Setting @code{XMKMF} to @samp{false}
7509 disables this method.
7511 If this method fails to find the X Window System, @command{configure}
7512 looks for the files in several directories where they often reside.
7513 If either method is successful, set the shell variables
7514 @code{x_includes} and @code{x_libraries} to their locations, unless they
7515 are in directories the compiler searches by default.
7517 If both methods fail, or the user gave the command line option
7518 @option{--without-x}, set the shell variable @code{no_x} to @samp{yes};
7519 otherwise set it to the empty string.
7520 @end defmac
7522 @anchor{AC_PATH_XTRA}
7523 @defmac AC_PATH_XTRA
7524 @acindex{PATH_XTRA}
7525 @ovindex X_CFLAGS
7526 @ovindex X_LIBS
7527 @ovindex X_EXTRA_LIBS
7528 @ovindex X_PRE_LIBS
7529 @cvindex X_DISPLAY_MISSING
7530 An enhanced version of @code{AC_PATH_X}.  It adds the C compiler flags
7531 that X needs to output variable @code{X_CFLAGS}, and the X linker flags
7532 to @code{X_LIBS}.  Define @code{X_DISPLAY_MISSING} if X is not
7533 available.
7535 This macro also checks for special libraries that some systems need in
7536 order to compile X programs.  It adds any that the system needs to
7537 output variable @code{X_EXTRA_LIBS}.  And it checks for special X11R6
7538 libraries that need to be linked with before @option{-lX11}, and adds
7539 any found to the output variable @code{X_PRE_LIBS}.
7541 @c This is an incomplete kludge.  Make a real way to do it.
7542 @c If you need to check for other X functions or libraries yourself, then
7543 @c after calling this macro, add the contents of @code{X_EXTRA_LIBS} to
7544 @c @code{LIBS} temporarily, like this: (FIXME - add example)
7545 @end defmac
7547 @anchor{AC_SYS_INTERPRETER}
7548 @defmac AC_SYS_INTERPRETER
7549 @acindex{SYS_INTERPRETER}
7550 Check whether the system supports starting scripts with a line of the
7551 form @samp{#!/bin/sh} to select the interpreter to use for the script.
7552 After running this macro, shell code in @file{configure.ac} can check
7553 the shell variable @code{interpval}; it is set to @samp{yes}
7554 if the system supports @samp{#!}, @samp{no} if not.
7555 @end defmac
7557 @defmac AC_SYS_LARGEFILE
7558 @acindex{SYS_LARGEFILE}
7559 @cvindex _FILE_OFFSET_BITS
7560 @cvindex _LARGE_FILES
7561 @ovindex CC
7562 @cindex Large file support
7563 @cindex LFS
7564 Arrange for
7565 @uref{http://www.unix-systems.org/@/version2/@/whatsnew/@/lfs20mar.html,
7566 large-file support}.  On some hosts, one must use special compiler
7567 options to build programs that can access large files.  Append any such
7568 options to the output variable @code{CC}.  Define
7569 @code{_FILE_OFFSET_BITS} and @code{_LARGE_FILES} if necessary.
7571 Large-file support can be disabled by configuring with the
7572 @option{--disable-largefile} option.
7574 If you use this macro, check that your program works even when
7575 @code{off_t} is wider than @code{long int}, since this is common when
7576 large-file support is enabled.  For example, it is not correct to print
7577 an arbitrary @code{off_t} value @code{X} with @code{printf ("%ld",
7578 (long int) X)}.
7580 The LFS introduced the @code{fseeko} and @code{ftello} functions to
7581 replace their C counterparts @code{fseek} and @code{ftell} that do not
7582 use @code{off_t}.  Take care to use @code{AC_FUNC_FSEEKO} to make their
7583 prototypes available when using them and large-file support is
7584 enabled.
7585 @end defmac
7587 @anchor{AC_SYS_LONG_FILE_NAMES}
7588 @defmac AC_SYS_LONG_FILE_NAMES
7589 @acindex{SYS_LONG_FILE_NAMES}
7590 @cvindex HAVE_LONG_FILE_NAMES
7591 If the system supports file names longer than 14 characters, define
7592 @code{HAVE_LONG_FILE_NAMES}.
7593 @end defmac
7595 @defmac AC_SYS_POSIX_TERMIOS
7596 @acindex{SYS_POSIX_TERMIOS}
7597 @cindex Posix termios headers
7598 @cindex termios Posix headers
7599 Check to see if the Posix termios headers and functions are available on the
7600 system.  If so, set the shell variable @code{ac_cv_sys_posix_termios} to
7601 @samp{yes}.  If not, set the variable to @samp{no}.
7602 @end defmac
7604 @node Posix Variants
7605 @section Posix Variants
7607 The following macro makes it possible to use features of Posix that are
7608 extensions to C, as well as platform extensions not defined by Posix.
7610 @anchor{AC_USE_SYSTEM_EXTENSIONS}
7611 @defmac AC_USE_SYSTEM_EXTENSIONS
7612 @acindex{USE_SYSTEM_EXTENSIONS}
7613 @cvindex _ALL_SOURCE
7614 @cvindex _GNU_SOURCE
7615 @cvindex _MINIX
7616 @cvindex _POSIX_1_SOURCE
7617 @cvindex _POSIX_PTHREAD_SEMANTICS
7618 @cvindex _POSIX_SOURCE
7619 @cvindex _TANDEM_SOURCE
7620 @cvindex __EXTENSIONS__
7621 This macro was introduced in Autoconf 2.60.  If possible, enable
7622 extensions to C or Posix on hosts that normally disable the extensions,
7623 typically due to standards-conformance namespace issues.  This should be
7624 called before any macros that run the C compiler.  The following
7625 preprocessor macros are defined where appropriate:
7627 @table @code
7628 @item _GNU_SOURCE
7629 Enable extensions on @acronym{GNU}/Linux.
7630 @item __EXTENSIONS__
7631 Enable general extensions on Solaris.
7632 @item _POSIX_PTHREAD_SEMANTICS
7633 Enable threading extensions on Solaris.
7634 @item _TANDEM_SOURCE
7635 Enable extensions for the @acronym{HP} NonStop platform.
7636 @item _ALL_SOURCE
7637 Enable extensions for @acronym{AIX} 3, and for Interix.
7638 @item _POSIX_SOURCE
7639 Enable Posix functions for Minix.
7640 @item _POSIX_1_SOURCE
7641 Enable additional Posix functions for Minix.
7642 @item _MINIX
7643 Identify Minix platform.  This particular preprocessor macro is
7644 obsolescent, and may be removed in a future release of Autoconf.
7645 @end table
7646 @end defmac
7649 @node Erlang Libraries
7650 @section Erlang Libraries
7651 @cindex Erlang, Library, checking
7653 The following macros check for an installation of Erlang/OTP, and for the
7654 presence of certain Erlang libraries.  All those macros require the
7655 configuration of an Erlang interpreter and an Erlang compiler
7656 (@pxref{Erlang Compiler and Interpreter}).
7658 @defmac AC_ERLANG_SUBST_ROOT_DIR
7659 @acindex{ERLANG_SUBST_ROOT_DIR}
7660 @ovindex ERLANG_ROOT_DIR
7662 Set the output variable @code{ERLANG_ROOT_DIR} to the path to the base
7663 directory in which Erlang/OTP is installed (as returned by Erlang's
7664 @code{code:root_dir/0} function).  The result of this test is cached if
7665 caching is enabled when running @command{configure}.
7666 @end defmac
7668 @defmac AC_ERLANG_SUBST_LIB_DIR
7669 @acindex{ERLANG_SUBST_LIB_DIR}
7670 @ovindex ERLANG_LIB_DIR
7672 Set the output variable @code{ERLANG_LIB_DIR} to the path of the library
7673 directory of Erlang/OTP (as returned by Erlang's
7674 @code{code:lib_dir/0} function), which subdirectories each contain an installed
7675 Erlang/OTP library.  The result of this test is cached if caching is enabled
7676 when running @command{configure}.
7677 @end defmac
7679 @defmac AC_ERLANG_CHECK_LIB (@var{library}, @ovar{action-if-found}, @
7680   @ovar{action-if-not-found})
7681 @acindex{ERLANG_CHECK_LIB}
7682 @ovindex ERLANG_LIB_DIR_@var{library}
7683 @ovindex ERLANG_LIB_VER_@var{library}
7685 Test whether the Erlang/OTP library @var{library} is installed by
7686 calling Erlang's @code{code:lib_dir/1} function.  The result of this
7687 test is cached if caching is enabled when running @command{configure}.
7688 @var{action-if-found} is a list of shell commands to run if the library
7689 is installed; @var{action-if-not-found} is a list of shell commands to
7690 run if it is not.  Additionally, if the library is installed, the output
7691 variable @samp{ERLANG_LIB_DIR_@var{library}} is set to the path to the
7692 library installation directory, and the output variable
7693 @samp{ERLANG_LIB_VER_@var{library}} is set to the version number that is
7694 part of the subdirectory name, if it is in the standard form
7695 (@code{@var{library}-@var{version}}).  If the directory name does not
7696 have a version part, @samp{ERLANG_LIB_VER_@var{library}} is set to the
7697 empty string.  If the library is not installed,
7698 @samp{ERLANG_LIB_DIR_@var{library}} and
7699 @samp{ERLANG_LIB_VER_@var{library}} are set to @code{"not found"}.  For
7700 example, to check if library @code{stdlib} is installed:
7702 @example
7703 AC_ERLANG_CHECK_LIB([stdlib],
7704   [echo "stdlib version \"$ERLANG_LIB_VER_stdlib\""
7705    echo "is installed in \"$ERLANG_LIB_DIR_stdlib\""],
7706   [AC_MSG_ERROR([stdlib was not found!])])
7707 @end example
7708 @end defmac
7710 In addition to the above macros, which test installed Erlang libraries, the
7711 following macros determine the paths to the directories into which newly built
7712 Erlang libraries are to be installed:
7714 @defmac AC_ERLANG_SUBST_INSTALL_LIB_DIR
7715 @acindex{ERLANG_SUBST_INSTALL_LIB_DIR}
7716 @ovindex ERLANG_INSTALL_LIB_DIR
7718 Set the @code{ERLANG_INSTALL_LIB_DIR} output variable to the directory into
7719 which every built Erlang library should be installed in a separate
7720 subdirectory.
7721 If this variable is not set in the environment when @command{configure} runs,
7722 its default value is @code{$ERLANG_LIB_DIR}, which value is set by the
7723 @code{AC_ERLANG_SUBST_LIB_DIR} macro.
7724 @end defmac
7726 @defmac AC_ERLANG_SUBST_INSTALL_LIB_SUBDIR (@var{library}, @var{version})
7727 @acindex{ERLANG_SUBST_INSTALL_LIB_SUBDIR}
7728 @ovindex ERLANG_INSTALL_LIB_DIR_@var{library}
7730 Set the @samp{ERLANG_INSTALL_LIB_DIR_@var{library}} output variable to the
7731 directory into which the built Erlang library @var{library} version
7732 @var{version} should be installed.  If this variable is not set in the
7733 environment when @command{configure} runs, its default value is
7734 @samp{$ERLANG_INSTALL_LIB_DIR/@var{library}-@var{version}}, the value of the
7735 @code{ERLANG_INSTALL_LIB_DIR} variable being set by the
7736 @code{AC_ERLANG_SUBST_INSTALL_LIB_DIR} macro.
7737 @end defmac
7743 @c ========================================================= Writing Tests
7745 @node Writing Tests
7746 @chapter Writing Tests
7748 If the existing feature tests don't do something you need, you have to
7749 write new ones.  These macros are the building blocks.  They provide
7750 ways for other macros to check whether various kinds of features are
7751 available and report the results.
7753 This chapter contains some suggestions and some of the reasons why the
7754 existing tests are written the way they are.  You can also learn a lot
7755 about how to write Autoconf tests by looking at the existing ones.  If
7756 something goes wrong in one or more of the Autoconf tests, this
7757 information can help you understand the assumptions behind them, which
7758 might help you figure out how to best solve the problem.
7760 These macros check the output of the compiler system of the current
7761 language (@pxref{Language Choice}).  They do not cache the results of
7762 their tests for future use (@pxref{Caching Results}), because they don't
7763 know enough about the information they are checking for to generate a
7764 cache variable name.  They also do not print any messages, for the same
7765 reason.  The checks for particular kinds of features call these macros
7766 and do cache their results and print messages about what they're
7767 checking for.
7769 When you write a feature test that could be applicable to more than one
7770 software package, the best thing to do is encapsulate it in a new macro.
7771 @xref{Writing Autoconf Macros}, for how to do that.
7773 @menu
7774 * Language Choice::             Selecting which language to use for testing
7775 * Writing Test Programs::       Forging source files for compilers
7776 * Running the Preprocessor::    Detecting preprocessor symbols
7777 * Running the Compiler::        Detecting language or header features
7778 * Running the Linker::          Detecting library features
7779 * Runtime::                     Testing for runtime features
7780 * Systemology::                 A zoology of operating systems
7781 * Multiple Cases::              Tests for several possible values
7782 @end menu
7784 @node Language Choice
7785 @section Language Choice
7786 @cindex Language
7788 Autoconf-generated @command{configure} scripts check for the C compiler and
7789 its features by default.  Packages that use other programming languages
7790 (maybe more than one, e.g., C and C++) need to test features of the
7791 compilers for the respective languages.  The following macros determine
7792 which programming language is used in the subsequent tests in
7793 @file{configure.ac}.
7795 @anchor{AC_LANG}
7796 @defmac AC_LANG (@var{language})
7797 Do compilation tests using the compiler, preprocessor, and file
7798 extensions for the specified @var{language}.
7800 Supported languages are:
7802 @table @samp
7803 @item C
7804 Do compilation tests using @code{CC} and @code{CPP} and use extension
7805 @file{.c} for test programs.  Use compilation flags: @code{CPPFLAGS} with
7806 @code{CPP}, and both @code{CPPFLAGS} and @code{CFLAGS} with @code{CC}.
7808 @item C++
7809 Do compilation tests using @code{CXX} and @code{CXXCPP} and use
7810 extension @file{.C} for test programs.  Use compilation flags:
7811 @code{CPPFLAGS} with @code{CXXCPP}, and both @code{CPPFLAGS} and
7812 @code{CXXFLAGS} with @code{CXX}.
7814 @item Fortran 77
7815 Do compilation tests using @code{F77} and use extension @file{.f} for
7816 test programs.  Use compilation flags: @code{FFLAGS}.
7818 @item Fortran
7819 Do compilation tests using @code{FC} and use extension @file{.f} (or
7820 whatever has been set by @code{AC_FC_SRCEXT}) for test programs.  Use
7821 compilation flags: @code{FCFLAGS}.
7823 @item Erlang
7824 @ovindex ERLC
7825 @ovindex ERL
7826 @ovindex ERLCFLAGS
7827 Compile and execute tests using @code{ERLC} and @code{ERL} and use extension
7828 @file{.erl} for test Erlang modules.  Use compilation flags: @code{ERLCFLAGS}.
7830 @item Objective C
7831 Do compilation tests using @code{OBJC} and @code{OBJCPP} and use
7832 extension @file{.m} for test programs.  Use compilation flags:
7833 @code{CPPFLAGS} with @code{OBJCPP}, and both @code{CPPFLAGS} and
7834 @code{OBJCFLAGS} with @code{OBJC}.
7835 @end table
7836 @end defmac
7838 @anchor{AC_LANG_PUSH}
7839 @defmac AC_LANG_PUSH (@var{language})
7840 @acindex{LANG_PUSH}
7841 Remember the current language (as set by @code{AC_LANG}) on a stack, and
7842 then select the @var{language}.  Use this macro and @code{AC_LANG_POP}
7843 in macros that need to temporarily switch to a particular language.
7844 @end defmac
7846 @defmac AC_LANG_POP (@ovar{language})
7847 @acindex{LANG_POP}
7848 Select the language that is saved on the top of the stack, as set by
7849 @code{AC_LANG_PUSH}, and remove it from the stack.
7851 If given, @var{language} specifies the language we just @emph{quit}.  It
7852 is a good idea to specify it when it's known (which should be the
7853 case@dots{}), since Autoconf detects inconsistencies.
7855 @example
7856 AC_LANG_PUSH([Fortran 77])
7857 # Perform some tests on Fortran 77.
7858 # @dots{}
7859 AC_LANG_POP([Fortran 77])
7860 @end example
7861 @end defmac
7863 @defmac AC_LANG_ASSERT (@var{language})
7864 @acindex{LANG_ASSERT} Check statically that the current language is
7865 @var{language}.  You should use this in your language specific macros
7866 to avoid that they be called with an inappropriate language.
7868 This macro runs only at @command{autoconf} time, and incurs no cost at
7869 @command{configure} time.  Sadly enough and because Autoconf is a two
7870 layer language @footnote{Because M4 is not aware of Sh code,
7871 especially conditionals, some optimizations that look nice statically
7872 may produce incorrect results at runtime.}, the macros
7873 @code{AC_LANG_PUSH} and @code{AC_LANG_POP} cannot be ``optimizing'',
7874 therefore as much as possible you ought to avoid using them to wrap
7875 your code, rather, require from the user to run the macro with a
7876 correct current language, and check it with @code{AC_LANG_ASSERT}.
7877 And anyway, that may help the user understand she is running a Fortran
7878 macro while expecting a result about her Fortran 77 compiler@dots{}
7879 @end defmac
7882 @defmac AC_REQUIRE_CPP
7883 @acindex{REQUIRE_CPP}
7884 Ensure that whichever preprocessor would currently be used for tests has
7885 been found.  Calls @code{AC_REQUIRE} (@pxref{Prerequisite Macros}) with an
7886 argument of either @code{AC_PROG_CPP} or @code{AC_PROG_CXXCPP},
7887 depending on which language is current.
7888 @end defmac
7891 @node Writing Test Programs
7892 @section Writing Test Programs
7894 Autoconf tests follow a common scheme: feed some program with some
7895 input, and most of the time, feed a compiler with some source file.
7896 This section is dedicated to these source samples.
7898 @menu
7899 * Guidelines::                  General rules for writing test programs
7900 * Test Functions::              Avoiding pitfalls in test programs
7901 * Generating Sources::          Source program boilerplate
7902 @end menu
7904 @node Guidelines
7905 @subsection Guidelines for Test Programs
7907 The most important rule to follow when writing testing samples is:
7909 @center @emph{Look for realism.}
7911 This motto means that testing samples must be written with the same
7912 strictness as real programs are written.  In particular, you should
7913 avoid ``shortcuts'' and simplifications.
7915 Don't just play with the preprocessor if you want to prepare a
7916 compilation.  For instance, using @command{cpp} to check whether a header is
7917 functional might let your @command{configure} accept a header which
7918 causes some @emph{compiler} error.  Do not hesitate to check a header with
7919 other headers included before, especially required headers.
7921 Make sure the symbols you use are properly defined, i.e., refrain for
7922 simply declaring a function yourself instead of including the proper
7923 header.
7925 Test programs should not write to standard output.  They
7926 should exit with status 0 if the test succeeds, and with status 1
7927 otherwise, so that success
7928 can be distinguished easily from a core dump or other failure;
7929 segmentation violations and other failures produce a nonzero exit
7930 status.  Unless you arrange for @code{exit} to be declared, test
7931 programs should @code{return}, not @code{exit}, from @code{main},
7932 because on many systems @code{exit} is not declared by default.
7934 Test programs can use @code{#if} or @code{#ifdef} to check the values of
7935 preprocessor macros defined by tests that have already run.  For
7936 example, if you call @code{AC_HEADER_STDBOOL}, then later on in
7937 @file{configure.ac} you can have a test program that includes
7938 @file{stdbool.h} conditionally:
7940 @example
7941 @group
7942 #ifdef HAVE_STDBOOL_H
7943 # include <stdbool.h>
7944 #endif
7945 @end group
7946 @end example
7948 Both @code{#if HAVE_STDBOOL_H} and @code{#ifdef HAVE_STDBOOL_H} will
7949 work with any standard C compiler.  Some developers prefer @code{#if}
7950 because it is easier to read, while others prefer @code{#ifdef} because
7951 it avoids diagnostics with picky compilers like @acronym{GCC} with the
7952 @option{-Wundef} option.
7954 If a test program needs to use or create a data file, give it a name
7955 that starts with @file{conftest}, such as @file{conftest.data}.  The
7956 @command{configure} script cleans up by running @samp{rm -f -r conftest*}
7957 after running test programs and if the script is interrupted.
7959 @node Test Functions
7960 @subsection Test Functions
7962 These days it's safe to assume support for function prototypes
7963 (introduced in C89).
7965 Functions that test programs declare should also be conditionalized for
7966 C++, which requires @samp{extern "C"} prototypes.  Make sure to not
7967 include any header files containing clashing prototypes.
7969 @example
7970 #ifdef __cplusplus
7971 extern "C"
7972 #endif
7973 void *valloc (size_t);
7974 @end example
7976 If a test program calls a function with invalid parameters (just to see
7977 whether it exists), organize the program to ensure that it never invokes
7978 that function.  You can do this by calling it in another function that is
7979 never invoked.  You can't do it by putting it after a call to
7980 @code{exit}, because @acronym{GCC} version 2 knows that @code{exit}
7981 never returns
7982 and optimizes out any code that follows it in the same block.
7984 If you include any header files, be sure to call the functions
7985 relevant to them with the correct number of arguments, even if they are
7986 just 0, to avoid compilation errors due to prototypes.  @acronym{GCC}
7987 version 2
7988 has internal prototypes for several functions that it automatically
7989 inlines; for example, @code{memcpy}.  To avoid errors when checking for
7990 them, either pass them the correct number of arguments or redeclare them
7991 with a different return type (such as @code{char}).
7994 @node Generating Sources
7995 @subsection Generating Sources
7997 Autoconf provides a set of macros that can be used to generate test
7998 source files.  They are written to be language generic, i.e., they
7999 actually depend on the current language (@pxref{Language Choice}) to
8000 ``format'' the output properly.
8003 @defmac AC_LANG_CONFTEST (@var{source})
8004 @acindex{LANG_CONFTEST}
8005 Save the @var{source} text in the current test source file:
8006 @file{conftest.@var{extension}} where the @var{extension} depends on the
8007 current language.
8009 Note that the @var{source} is evaluated exactly once, like regular
8010 Autoconf macro arguments, and therefore (i) you may pass a macro
8011 invocation, (ii) if not, be sure to double quote if needed.
8012 @end defmac
8014 @defmac AC_LANG_SOURCE (@var{source})
8015 @acindex{LANG_SOURCE}
8016 Expands into the @var{source}, with the definition of
8017 all the @code{AC_DEFINE} performed so far.
8018 @end defmac
8020 For instance executing (observe the double quotation!):
8022 @example
8023 AC_INIT([Hello], [1.0], [bug-hello@@example.org])
8024 AC_DEFINE([HELLO_WORLD], ["Hello, World\n"],
8025   [Greetings string.])
8026 AC_LANG(C)
8027 AC_LANG_CONFTEST(
8028    [AC_LANG_SOURCE([[const char hw[] = "Hello, World\n";]])])
8029 gcc -E -dD -o - conftest.c
8030 @end example
8032 @noindent
8033 results in:
8035 @example
8036 @dots{}
8037 # 1 "conftest.c"
8039 #define PACKAGE_NAME "Hello"
8040 #define PACKAGE_TARNAME "hello"
8041 #define PACKAGE_VERSION "1.0"
8042 #define PACKAGE_STRING "Hello 1.0"
8043 #define PACKAGE_BUGREPORT "bug-hello@@example.org"
8044 #define HELLO_WORLD "Hello, World\n"
8046 const char hw[] = "Hello, World\n";
8047 @end example
8049 When the test language is Fortran or Erlang, the @code{AC_DEFINE} definitions
8050 are not automatically translated into constants in the source code by this
8051 macro.
8053 @defmac AC_LANG_PROGRAM (@var{prologue}, @var{body})
8054 @acindex{LANG_PROGRAM}
8055 Expands into a source file which consists of the @var{prologue}, and
8056 then @var{body} as body of the main function (e.g., @code{main} in
8057 C).  Since it uses @code{AC_LANG_SOURCE}, the features of the latter are
8058 available.
8059 @end defmac
8061 For instance:
8063 @example
8064 AC_INIT([Hello], [1.0], [bug-hello@@example.org])
8065 AC_DEFINE([HELLO_WORLD], ["Hello, World\n"],
8066   [Greetings string.])
8067 AC_LANG_CONFTEST(
8068 [AC_LANG_PROGRAM([[const char hw[] = "Hello, World\n";]],
8069                  [[fputs (hw, stdout);]])])
8070 gcc -E -dD -o - conftest.c
8071 @end example
8073 @noindent
8074 results in:
8076 @example
8077 @dots{}
8078 # 1 "conftest.c"
8080 #define PACKAGE_NAME "Hello"
8081 #define PACKAGE_TARNAME "hello"
8082 #define PACKAGE_VERSION "1.0"
8083 #define PACKAGE_STRING "Hello 1.0"
8084 #define PACKAGE_BUGREPORT "bug-hello@@example.org"
8085 #define HELLO_WORLD "Hello, World\n"
8087 const char hw[] = "Hello, World\n";
8089 main ()
8091 fputs (hw, stdout);
8092   ;
8093   return 0;
8095 @end example
8097 In Erlang tests, the created source file is that of an Erlang module called
8098 @code{conftest} (@file{conftest.erl}).  This module defines and exports
8099 at least
8100 one @code{start/0} function, which is called to perform the test.  The
8101 @var{prologue} is optional code that is inserted between the module header and
8102 the @code{start/0} function definition.  @var{body} is the body of the
8103 @code{start/0} function without the final period (@pxref{Runtime}, about
8104 constraints on this function's behavior).
8106 For instance:
8108 @example
8109 AC_INIT([Hello], [1.0], [bug-hello@@example.org])
8110 AC_LANG(Erlang)
8111 AC_LANG_CONFTEST(
8112 [AC_LANG_PROGRAM([[-define(HELLO_WORLD, "Hello, world!").]],
8113                  [[io:format("~s~n", [?HELLO_WORLD])]])])
8114 cat conftest.erl
8115 @end example
8117 @noindent
8118 results in:
8120 @example
8121 -module(conftest).
8122 -export([start/0]).
8123 -define(HELLO_WORLD, "Hello, world!").
8124 start() ->
8125 io:format("~s~n", [?HELLO_WORLD])
8127 @end example
8129 @defmac AC_LANG_CALL (@var{prologue}, @var{function})
8130 @acindex{LANG_CALL}
8131 Expands into a source file which consists of the @var{prologue}, and
8132 then a call to the @var{function} as body of the main function (e.g.,
8133 @code{main} in C).  Since it uses @code{AC_LANG_PROGRAM}, the feature
8134 of the latter are available.
8136 This function will probably be replaced in the future by a version
8137 which would enable specifying the arguments.  The use of this macro is
8138 not encouraged, as it violates strongly the typing system.
8140 This macro cannot be used for Erlang tests.
8141 @end defmac
8143 @defmac AC_LANG_FUNC_LINK_TRY (@var{function})
8144 @acindex{LANG_FUNC_LINK_TRY}
8145 Expands into a source file which uses the @var{function} in the body of
8146 the main function (e.g., @code{main} in C).  Since it uses
8147 @code{AC_LANG_PROGRAM}, the features of the latter are available.
8149 As @code{AC_LANG_CALL}, this macro is documented only for completeness.
8150 It is considered to be severely broken, and in the future will be
8151 removed in favor of actual function calls (with properly typed
8152 arguments).
8154 This macro cannot be used for Erlang tests.
8155 @end defmac
8157 @node Running the Preprocessor
8158 @section Running the Preprocessor
8160 Sometimes one might need to run the preprocessor on some source file.
8161 @emph{Usually it is a bad idea}, as you typically need to @emph{compile}
8162 your project, not merely run the preprocessor on it; therefore you
8163 certainly want to run the compiler, not the preprocessor.  Resist the
8164 temptation of following the easiest path.
8166 Nevertheless, if you need to run the preprocessor, then use
8167 @code{AC_PREPROC_IFELSE}.
8169 The macros described in this section cannot be used for tests in Erlang or
8170 Fortran, since those languages require no preprocessor.
8172 @anchor{AC_PREPROC_IFELSE}
8173 @defmac AC_PREPROC_IFELSE (@var{input}, @ovar{action-if-true}, @
8174   @ovar{action-if-false})
8175 @acindex{PREPROC_IFELSE}
8176 Run the preprocessor of the current language (@pxref{Language Choice})
8177 on the @var{input}, run the shell commands @var{action-if-true} on
8178 success, @var{action-if-false} otherwise.  The @var{input} can be made
8179 by @code{AC_LANG_PROGRAM} and friends.
8181 This macro uses @code{CPPFLAGS}, but not @code{CFLAGS}, because
8182 @option{-g}, @option{-O}, etc.@: are not valid options to many C
8183 preprocessors.
8185 It is customary to report unexpected failures with
8186 @code{AC_MSG_FAILURE}.
8187 @end defmac
8189 For instance:
8191 @example
8192 AC_INIT([Hello], [1.0], [bug-hello@@example.org])
8193 AC_DEFINE([HELLO_WORLD], ["Hello, World\n"],
8194   [Greetings string.])
8195 AC_PREPROC_IFELSE(
8196    [AC_LANG_PROGRAM([[const char hw[] = "Hello, World\n";]],
8197                     [[fputs (hw, stdout);]])],
8198    [AC_MSG_RESULT([OK])],
8199    [AC_MSG_FAILURE([unexpected preprocessor failure])])
8200 @end example
8202 @noindent
8203 results in:
8205 @example
8206 checking for gcc... gcc
8207 checking for C compiler default output file name... a.out
8208 checking whether the C compiler works... yes
8209 checking whether we are cross compiling... no
8210 checking for suffix of executables...
8211 checking for suffix of object files... o
8212 checking whether we are using the GNU C compiler... yes
8213 checking whether gcc accepts -g... yes
8214 checking for gcc option to accept ISO C89... none needed
8215 checking how to run the C preprocessor... gcc -E
8217 @end example
8219 @sp 1
8221 The macro @code{AC_TRY_CPP} (@pxref{Obsolete Macros}) used to play the
8222 role of @code{AC_PREPROC_IFELSE}, but double quotes its argument, making
8223 it impossible to use it to elaborate sources.  You are encouraged to
8224 get rid of your old use of the macro @code{AC_TRY_CPP} in favor of
8225 @code{AC_PREPROC_IFELSE}, but, in the first place, are you sure you need
8226 to run the @emph{preprocessor} and not the compiler?
8228 @anchor{AC_EGREP_HEADER}
8229 @defmac AC_EGREP_HEADER (@var{pattern}, @var{header-file}, @
8230   @var{action-if-found}, @ovar{action-if-not-found})
8231 @acindex{EGREP_HEADER}
8232 If the output of running the preprocessor on the system header file
8233 @var{header-file} matches the extended regular expression
8234 @var{pattern}, execute shell commands @var{action-if-found}, otherwise
8235 execute @var{action-if-not-found}.
8236 @end defmac
8238 @anchor{AC_EGREP_CPP}
8239 @defmac AC_EGREP_CPP (@var{pattern}, @var{program}, @
8240   @ovar{action-if-found}, @ovar{action-if-not-found})
8241 @acindex{EGREP_CPP}
8242 @var{program} is the text of a C or C++ program, on which shell
8243 variable, back quote, and backslash substitutions are performed.  If the
8244 output of running the preprocessor on @var{program} matches the
8245 extended regular expression @var{pattern}, execute shell commands
8246 @var{action-if-found}, otherwise execute @var{action-if-not-found}.
8247 @end defmac
8251 @node Running the Compiler
8252 @section Running the Compiler
8254 To check for a syntax feature of the current language's (@pxref{Language
8255 Choice}) compiler, such as whether it recognizes a certain keyword, or
8256 simply to try some library feature, use @code{AC_COMPILE_IFELSE} to try
8257 to compile a small program that uses that feature.
8259 @defmac AC_COMPILE_IFELSE (@var{input}, @ovar{action-if-true}, @
8260   @ovar{action-if-false})
8261 @acindex{COMPILE_IFELSE}
8262 Run the compiler and compilation flags of the current language
8263 (@pxref{Language Choice}) on the @var{input}, run the shell commands
8264 @var{action-if-true} on success, @var{action-if-false} otherwise.  The
8265 @var{input} can be made by @code{AC_LANG_PROGRAM} and friends.
8267 It is customary to report unexpected failures with
8268 @code{AC_MSG_FAILURE}.  This macro does not try to link; use
8269 @code{AC_LINK_IFELSE} if you need to do that (@pxref{Running the
8270 Linker}).
8271 @end defmac
8273 @ovindex ERL
8274 For tests in Erlang, the @var{input} must be the source code of a module named
8275 @code{conftest}.  @code{AC_COMPILE_IFELSE} generates a @file{conftest.beam}
8276 file that can be interpreted by the Erlang virtual machine (@code{ERL}).  It is
8277 recommended to use @code{AC_LANG_PROGRAM} to specify the test program,
8278 to ensure that the Erlang module has the right name.
8280 @node Running the Linker
8281 @section Running the Linker
8283 To check for a library, a function, or a global variable, Autoconf
8284 @command{configure} scripts try to compile and link a small program that
8285 uses it.  This is unlike Metaconfig, which by default uses @code{nm} or
8286 @code{ar} on the C library to try to figure out which functions are
8287 available.  Trying to link with the function is usually a more reliable
8288 approach because it avoids dealing with the variations in the options
8289 and output formats of @code{nm} and @code{ar} and in the location of the
8290 standard libraries.  It also allows configuring for cross-compilation or
8291 checking a function's runtime behavior if needed.  On the other hand,
8292 it can be slower than scanning the libraries once, but accuracy is more
8293 important than speed.
8295 @code{AC_LINK_IFELSE} is used to compile test programs to test for
8296 functions and global variables.  It is also used by @code{AC_CHECK_LIB}
8297 to check for libraries (@pxref{Libraries}), by adding the library being
8298 checked for to @code{LIBS} temporarily and trying to link a small
8299 program.
8301 @anchor{AC_LINK_IFELSE}
8302 @defmac AC_LINK_IFELSE (@var{input}, @ovar{action-if-true}, @
8303   @ovar{action-if-false})
8304 @acindex{LINK_IFELSE}
8305 Run the compiler (and compilation flags) and the linker of the current
8306 language (@pxref{Language Choice}) on the @var{input}, run the shell
8307 commands @var{action-if-true} on success, @var{action-if-false}
8308 otherwise.  The @var{input} can be made by @code{AC_LANG_PROGRAM} and
8309 friends.
8311 @code{LDFLAGS} and @code{LIBS} are used for linking, in addition to the
8312 current compilation flags.
8314 It is customary to report unexpected failures with
8315 @code{AC_MSG_FAILURE}.  This macro does not try to execute the program;
8316 use @code{AC_RUN_IFELSE} if you need to do that (@pxref{Runtime}).
8317 @end defmac
8319 The @code{AC_LINK_IFELSE} macro cannot be used for Erlang tests, since Erlang
8320 programs are interpreted and do not require linking.
8324 @node Runtime
8325 @section Checking Runtime Behavior
8327 Sometimes you need to find out how a system performs at runtime, such
8328 as whether a given function has a certain capability or bug.  If you
8329 can, make such checks when your program runs instead of when it is
8330 configured.  You can check for things like the machine's endianness when
8331 your program initializes itself.
8333 If you really need to test for a runtime behavior while configuring,
8334 you can write a test program to determine the result, and compile and
8335 run it using @code{AC_RUN_IFELSE}.  Avoid running test programs if
8336 possible, because this prevents people from configuring your package for
8337 cross-compiling.
8339 @anchor{AC_RUN_IFELSE}
8340 @defmac AC_RUN_IFELSE (@var{input}, @ovar{action-if-true}, @
8341   @ovar{action-if-false}, @ovar{action-if-cross-compiling})
8342 @acindex{RUN_IFELSE}
8343 If @var{program} compiles and links successfully and returns an exit
8344 status of 0 when executed, run shell commands @var{action-if-true}.
8345 Otherwise, run shell commands @var{action-if-false}.
8347 The @var{input} can be made by @code{AC_LANG_PROGRAM} and friends.
8348 @code{LDFLAGS} and @code{LIBS} are used for linking, in addition to the
8349 compilation flags of the current language (@pxref{Language Choice}).
8351 If the compiler being used does not produce executables that run on the
8352 system where @command{configure} is being run, then the test program is
8353 not run.  If the optional shell commands @var{action-if-cross-compiling}
8354 are given, they are run instead.  Otherwise, @command{configure} prints
8355 an error message and exits.
8357 In the @var{action-if-false} section, the failing exit status is
8358 available in the shell variable @samp{$?}.  This exit status might be
8359 that of a failed compilation, or it might be that of a failed program
8360 execution.
8362 It is customary to report unexpected failures with
8363 @code{AC_MSG_FAILURE}.
8364 @end defmac
8366 Try to provide a pessimistic default value to use when cross-compiling
8367 makes runtime tests impossible.  You do this by passing the optional
8368 last argument to @code{AC_RUN_IFELSE}.  @command{autoconf} prints a
8369 warning message when creating @command{configure} each time it
8370 encounters a call to @code{AC_RUN_IFELSE} with no
8371 @var{action-if-cross-compiling} argument given.  You may ignore the
8372 warning, though users cannot configure your package for
8373 cross-compiling.  A few of the macros distributed with Autoconf produce
8374 this warning message.
8376 To configure for cross-compiling you can also choose a value for those
8377 parameters based on the canonical system name (@pxref{Manual
8378 Configuration}).  Alternatively, set up a test results cache file with
8379 the correct values for the host system (@pxref{Caching Results}).
8381 @ovindex cross_compiling
8382 To provide a default for calls of @code{AC_RUN_IFELSE} that are embedded
8383 in other macros, including a few of the ones that come with Autoconf,
8384 you can test whether the shell variable @code{cross_compiling} is set to
8385 @samp{yes}, and then use an alternate method to get the results instead
8386 of calling the macros.
8388 It is also permissible to temporarily assign to @code{cross_compiling}
8389 in order to force tests to behave as though they are in a
8390 cross-compilation environment, particularly since this provides a way to
8391 test your @var{action-if-cross-compiling} even when you are not using a
8392 cross-compiler.
8394 @example
8395 # We temporarily set cross-compile mode to force AC_COMPUTE_INT
8396 # to use the slow link-only method
8397 save_cross_compiling=$cross_compiling
8398 cross_compiling=yes
8399 AC_COMPUTE_INT([@dots{}])
8400 cross_compiling=$save_cross_compiling
8401 @end example
8403 A C or C++ runtime test should be portable.
8404 @xref{Portable C and C++}.
8406 Erlang tests must exit themselves the Erlang VM by calling the @code{halt/1}
8407 function: the given status code is used to determine the success of the test
8408 (status is @code{0}) or its failure (status is different than @code{0}), as
8409 explained above.  It must be noted that data output through the standard output
8410 (e.g., using @code{io:format/2}) may be truncated when halting the VM.
8411 Therefore, if a test must output configuration information, it is recommended
8412 to create and to output data into the temporary file named @file{conftest.out},
8413 using the functions of module @code{file}.  The @code{conftest.out} file is
8414 automatically deleted by the @code{AC_RUN_IFELSE} macro.  For instance, a
8415 simplified implementation of Autoconf's @code{AC_ERLANG_SUBST_LIB_DIR}
8416 macro is:
8418 @example
8419 AC_INIT([LibdirTest], [1.0], [bug-libdirtest@@example.org])
8420 AC_ERLANG_NEED_ERL
8421 AC_LANG(Erlang)
8422 AC_RUN_IFELSE(
8423   [AC_LANG_PROGRAM([], [dnl
8424     file:write_file("conftest.out", code:lib_dir()),
8425     halt(0)])],
8426   [echo "code:lib_dir() returned: `cat conftest.out`"],
8427   [AC_MSG_FAILURE([test Erlang program execution failed])])
8428 @end example
8431 @node Systemology
8432 @section Systemology
8433 @cindex Systemology
8435 This section aims at presenting some systems and pointers to
8436 documentation.  It may help you addressing particular problems reported
8437 by users.
8439 @uref{http://www.opengroup.org/susv3, Posix-conforming systems} are
8440 derived from the @uref{http://www.bell-labs.com/history/unix/, Unix
8441 operating system}.
8443 The @uref{http://bhami.com/rosetta.html, Rosetta Stone for Unix}
8444 contains a table correlating the features of various Posix-conforming
8445 systems.  @uref{http://www.levenez.com/unix/, Unix History} is a
8446 simplified diagram of how many Unix systems were derived from each
8447 other.
8449 @uref{http://heirloom.sourceforge.net/, The Heirloom Project}
8450 provides some variants of traditional implementations of Unix utilities.
8452 @table @asis
8453 @item Darwin
8454 @cindex Darwin
8455 Darwin is also known as Mac OS X@.  Beware that the file system @emph{can} be
8456 case-preserving, but case insensitive.  This can cause nasty problems,
8457 since for instance the installation attempt for a package having an
8458 @file{INSTALL} file can result in @samp{make install} report that
8459 nothing was to be done!
8461 That's all dependent on whether the file system is a UFS (case
8462 sensitive) or HFS+ (case preserving).  By default Apple wants you to
8463 install the OS on HFS+.  Unfortunately, there are some pieces of
8464 software which really need to be built on UFS@.  We may want to rebuild
8465 Darwin to have both UFS and HFS+ available (and put the /local/build
8466 tree on the UFS).
8468 @item @acronym{QNX} 4.25
8469 @cindex @acronym{QNX} 4.25
8470 @c FIXME: Please, if you feel like writing something more precise,
8471 @c it'd be great.  In particular, I can't understand the difference with
8472 @c QNX Neutrino.
8473 @acronym{QNX} is a realtime operating system running on Intel architecture
8474 meant to be scalable from the small embedded systems to the hundred
8475 processor super-computer.  It claims to be Posix certified.  More
8476 information is available on the
8477 @uref{http://www.qnx.com/, @acronym{QNX} home page}.
8479 @item Tru64
8480 @cindex Tru64
8481 @uref{http://h30097.www3.hp.com/@/docs/,
8482 Documentation of several versions of Tru64} is available in different
8483 formats.
8485 @item Unix version 7
8486 @cindex Unix version 7
8487 @cindex V7
8488 Officially this was called the ``Seventh Edition'' of ``the @sc{unix}
8489 time-sharing system'' but we use the more-common name ``Unix version 7''.
8490 Documentation is available in the
8491 @uref{http://plan9.bell-labs.com/@/7thEdMan/, Unix Seventh Edition Manual}.
8492 Previous versions of Unix are called ``Unix version 6'', etc., but
8493 they were not as widely used.
8494 @end table
8497 @node Multiple Cases
8498 @section Multiple Cases
8500 Some operations are accomplished in several possible ways, depending on
8501 the OS variant.  Checking for them essentially requires a ``case
8502 statement''.  Autoconf does not directly provide one; however, it is
8503 easy to simulate by using a shell variable to keep track of whether a
8504 way to perform the operation has been found yet.
8506 Here is an example that uses the shell variable @code{fstype} to keep
8507 track of whether the remaining cases need to be checked.
8509 @example
8510 @group
8511 AC_MSG_CHECKING([how to get file system type])
8512 fstype=no
8513 # The order of these tests is important.
8514 AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <sys/statvfs.h>
8515 #include <sys/fstyp.h>]])],
8516                   [AC_DEFINE([FSTYPE_STATVFS], [1],
8517                      [Define if statvfs exists.])
8518                    fstype=SVR4])
8519 if test $fstype = no; then
8520   AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <sys/statfs.h>
8521 #include <sys/fstyp.h>]])],
8522                   [AC_DEFINE([FSTYPE_USG_STATFS], [1],
8523                      [Define if USG statfs.])
8524                    fstype=SVR3])
8526 if test $fstype = no; then
8527   AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <sys/statfs.h>
8528 #include <sys/vmount.h>]])]),
8529                   [AC_DEFINE([FSTYPE_AIX_STATFS], [1],
8530                      [Define if AIX statfs.])
8531                    fstype=AIX])
8533 # (more cases omitted here)
8534 AC_MSG_RESULT([$fstype])
8535 @end group
8536 @end example
8538 @c ====================================================== Results of Tests.
8540 @node Results
8541 @chapter Results of Tests
8543 Once @command{configure} has determined whether a feature exists, what can
8544 it do to record that information?  There are four sorts of things it can
8545 do: define a C preprocessor symbol, set a variable in the output files,
8546 save the result in a cache file for future @command{configure} runs, and
8547 print a message letting the user know the result of the test.
8549 @menu
8550 * Defining Symbols::            Defining C preprocessor symbols
8551 * Setting Output Variables::    Replacing variables in output files
8552 * Special Chars in Variables::  Characters to beware of in variables
8553 * Caching Results::             Speeding up subsequent @command{configure} runs
8554 * Printing Messages::           Notifying @command{configure} users
8555 @end menu
8557 @node Defining Symbols
8558 @section Defining C Preprocessor Symbols
8560 A common action to take in response to a feature test is to define a C
8561 preprocessor symbol indicating the results of the test.  That is done by
8562 calling @code{AC_DEFINE} or @code{AC_DEFINE_UNQUOTED}.
8564 By default, @code{AC_OUTPUT} places the symbols defined by these macros
8565 into the output variable @code{DEFS}, which contains an option
8566 @option{-D@var{symbol}=@var{value}} for each symbol defined.  Unlike in
8567 Autoconf version 1, there is no variable @code{DEFS} defined while
8568 @command{configure} is running.  To check whether Autoconf macros have
8569 already defined a certain C preprocessor symbol, test the value of the
8570 appropriate cache variable, as in this example:
8572 @example
8573 AC_CHECK_FUNC([vprintf], [AC_DEFINE([HAVE_VPRINTF], [1],
8574                           [Define if vprintf exists.])])
8575 if test "$ac_cv_func_vprintf" != yes; then
8576   AC_CHECK_FUNC([_doprnt], [AC_DEFINE([HAVE_DOPRNT], [1],
8577                             [Define if _doprnt exists.])])
8579 @end example
8581 If @code{AC_CONFIG_HEADERS} has been called, then instead of creating
8582 @code{DEFS}, @code{AC_OUTPUT} creates a header file by substituting the
8583 correct values into @code{#define} statements in a template file.
8584 @xref{Configuration Headers}, for more information about this kind of
8585 output.
8587 @defmac AC_DEFINE (@var{variable}, @var{value}, @ovar{description})
8588 @defmacx AC_DEFINE (@var{variable})
8589 @cvindex @var{variable}
8590 @acindex{DEFINE}
8591 Define @var{variable} to @var{value} (verbatim), by defining a C
8592 preprocessor macro for @var{variable}.  @var{variable} should be a C
8593 identifier, optionally suffixed by a parenthesized argument list to
8594 define a C preprocessor macro with arguments.  The macro argument list,
8595 if present, should be a comma-separated list of C identifiers, possibly
8596 terminated by an ellipsis @samp{...} if C99 syntax is employed.
8597 @var{variable} should not contain comments, white space, trigraphs,
8598 backslash-newlines, universal character names, or non-@acronym{ASCII}
8599 characters.
8601 @var{value} may contain backslash-escaped newlines, which will be
8602 preserved if you use @code{AC_CONFIG_HEADERS} but flattened if passed
8603 via @code{@@DEFS@@} (with no effect on the compilation, since the
8604 preprocessor sees only one line in the first place).  @var{value} should
8605 not contain raw newlines.  If you are not using
8606 @code{AC_CONFIG_HEADERS}, @var{value} should not contain any @samp{#}
8607 characters, as @command{make} tends to eat them.  To use a shell
8608 variable, use @code{AC_DEFINE_UNQUOTED} instead.
8610 @var{description} is only useful if you are using
8611 @code{AC_CONFIG_HEADERS}.  In this case, @var{description} is put into
8612 the generated @file{config.h.in} as the comment before the macro define.
8613 The following example defines the C preprocessor variable
8614 @code{EQUATION} to be the string constant @samp{"$a > $b"}:
8616 @example
8617 AC_DEFINE([EQUATION], ["$a > $b"],
8618   [Equation string.])
8619 @end example
8621 If neither @var{value} nor @var{description} are given, then
8622 @var{value} defaults to 1 instead of to the empty string.  This is for
8623 backwards compatibility with older versions of Autoconf, but this usage
8624 is obsolescent and may be withdrawn in future versions of Autoconf.
8626 If the @var{variable} is a literal string, it is passed to
8627 @code{m4_pattern_allow} (@pxref{Forbidden Patterns}).
8629 If multiple @code{AC_DEFINE} statements are executed for the same
8630 @var{variable} name (not counting any parenthesized argument list),
8631 the last one wins.
8632 @end defmac
8634 @defmac AC_DEFINE_UNQUOTED (@var{variable}, @var{value}, @ovar{description})
8635 @defmacx AC_DEFINE_UNQUOTED (@var{variable})
8636 @acindex{DEFINE_UNQUOTED}
8637 @cvindex @var{variable}
8638 Like @code{AC_DEFINE}, but three shell expansions are
8639 performed---once---on @var{variable} and @var{value}: variable expansion
8640 (@samp{$}), command substitution (@samp{`}), and backslash escaping
8641 (@samp{\}).  Single and double quote characters in the value have no
8642 special meaning.  Use this macro instead of @code{AC_DEFINE} when
8643 @var{variable} or @var{value} is a shell variable.  Examples:
8645 @example
8646 AC_DEFINE_UNQUOTED([config_machfile], ["$machfile"],
8647   [Configuration machine file.])
8648 AC_DEFINE_UNQUOTED([GETGROUPS_T], [$ac_cv_type_getgroups],
8649   [getgroups return type.])
8650 AC_DEFINE_UNQUOTED([$ac_tr_hdr], [1],
8651   [Translated header name.])
8652 @end example
8653 @end defmac
8655 Due to a syntactical bizarreness of the Bourne shell, do not use
8656 semicolons to separate @code{AC_DEFINE} or @code{AC_DEFINE_UNQUOTED}
8657 calls from other macro calls or shell code; that can cause syntax errors
8658 in the resulting @command{configure} script.  Use either blanks or
8659 newlines.  That is, do this:
8661 @example
8662 AC_CHECK_HEADER([elf.h],
8663   [AC_DEFINE([SVR4], [1], [System V Release 4]) LIBS="-lelf $LIBS"])
8664 @end example
8666 @noindent
8667 or this:
8669 @example
8670 AC_CHECK_HEADER([elf.h],
8671   [AC_DEFINE([SVR4], [1], [System V Release 4])
8672    LIBS="-lelf $LIBS"])
8673 @end example
8675 @noindent
8676 instead of this:
8678 @example
8679 AC_CHECK_HEADER([elf.h],
8680   [AC_DEFINE([SVR4], [1], [System V Release 4]); LIBS="-lelf $LIBS"])
8681 @end example
8683 @node Setting Output Variables
8684 @section Setting Output Variables
8685 @cindex Output variables
8687 Another way to record the results of tests is to set @dfn{output
8688 variables}, which are shell variables whose values are substituted into
8689 files that @command{configure} outputs.  The two macros below create new
8690 output variables.  @xref{Preset Output Variables}, for a list of output
8691 variables that are always available.
8693 @defmac AC_SUBST (@var{variable}, @ovar{value})
8694 @acindex{SUBST}
8695 Create an output variable from a shell variable.  Make @code{AC_OUTPUT}
8696 substitute the variable @var{variable} into output files (typically one
8697 or more makefiles).  This means that @code{AC_OUTPUT}
8698 replaces instances of @samp{@@@var{variable}@@} in input files with the
8699 value that the shell variable @var{variable} has when @code{AC_OUTPUT}
8700 is called.  The value can contain any non-@code{NUL} character, including
8701 newline.
8702 Variable occurrences should not overlap: e.g., an input file should
8703 not contain @samp{@@@var{var1}@@@var{var2}@@} if @var{var1} and @var{var2}
8704 are variable names.
8705 The substituted value is not rescanned for more output variables;
8706 occurrences of @samp{@@@var{variable}@@} in the value are inserted
8707 literally into the output file.  (The algorithm uses the special marker
8708 @code{|#_!!_#|} internally, so neither the substituted value nor the
8709 output file may contain @code{|#_!!_#|}.)
8711 If @var{value} is given, in addition assign it to @var{variable}.
8713 The string @var{variable} is passed to @code{m4_pattern_allow}
8714 (@pxref{Forbidden Patterns}).
8715 @end defmac
8717 @defmac AC_SUBST_FILE (@var{variable})
8718 @acindex{SUBST_FILE}
8719 Another way to create an output variable from a shell variable.  Make
8720 @code{AC_OUTPUT} insert (without substitutions) the contents of the file
8721 named by shell variable @var{variable} into output files.  This means
8722 that @code{AC_OUTPUT} replaces instances of
8723 @samp{@@@var{variable}@@} in output files (such as @file{Makefile.in})
8724 with the contents of the file that the shell variable @var{variable}
8725 names when @code{AC_OUTPUT} is called.  Set the variable to
8726 @file{/dev/null} for cases that do not have a file to insert.
8727 This substitution occurs only when the @samp{@@@var{variable}@@} is on a
8728 line by itself, optionally surrounded by spaces and tabs.  The
8729 substitution replaces the whole line, including the spaces, tabs, and
8730 the terminating newline.
8732 This macro is useful for inserting makefile fragments containing
8733 special dependencies or other @code{make} directives for particular host
8734 or target types into makefiles.  For example, @file{configure.ac}
8735 could contain:
8737 @example
8738 AC_SUBST_FILE([host_frag])
8739 host_frag=$srcdir/conf/sun4.mh
8740 @end example
8742 @noindent
8743 and then a @file{Makefile.in} could contain:
8745 @example
8746 @@host_frag@@
8747 @end example
8749 The string @var{variable} is passed to @code{m4_pattern_allow}
8750 (@pxref{Forbidden Patterns}).
8751 @end defmac
8753 @cindex Precious Variable
8754 @cindex Variable, Precious
8755 Running @command{configure} in varying environments can be extremely
8756 dangerous.  If for instance the user runs @samp{CC=bizarre-cc
8757 ./configure}, then the cache, @file{config.h}, and many other output
8758 files depend upon @command{bizarre-cc} being the C compiler.  If
8759 for some reason the user runs @command{./configure} again, or if it is
8760 run via @samp{./config.status --recheck}, (@xref{Automatic Remaking},
8761 and @pxref{config.status Invocation}), then the configuration can be
8762 inconsistent, composed of results depending upon two different
8763 compilers.
8765 Environment variables that affect this situation, such as @samp{CC}
8766 above, are called @dfn{precious variables}, and can be declared as such
8767 by @code{AC_ARG_VAR}.
8769 @defmac AC_ARG_VAR (@var{variable}, @var{description})
8770 @acindex{ARG_VAR}
8771 Declare @var{variable} is a precious variable, and include its
8772 @var{description} in the variable section of @samp{./configure --help}.
8774 Being precious means that
8775 @itemize @minus
8776 @item
8777 @var{variable} is substituted via @code{AC_SUBST}.
8779 @item
8780 The value of @var{variable} when @command{configure} was launched is
8781 saved in the cache, including if it was not specified on the command
8782 line but via the environment.  Indeed, while @command{configure} can
8783 notice the definition of @code{CC} in @samp{./configure CC=bizarre-cc},
8784 it is impossible to notice it in @samp{CC=bizarre-cc ./configure},
8785 which, unfortunately, is what most users do.
8787 We emphasize that it is the @emph{initial} value of @var{variable} which
8788 is saved, not that found during the execution of @command{configure}.
8789 Indeed, specifying @samp{./configure FOO=foo} and letting
8790 @samp{./configure} guess that @code{FOO} is @code{foo} can be two
8791 different things.
8793 @item
8794 @var{variable} is checked for consistency between two
8795 @command{configure} runs.  For instance:
8797 @example
8798 $ @kbd{./configure --silent --config-cache}
8799 $ @kbd{CC=cc ./configure --silent --config-cache}
8800 configure: error: `CC' was not set in the previous run
8801 configure: error: changes in the environment can compromise \
8802 the build
8803 configure: error: run `make distclean' and/or \
8804 `rm config.cache' and start over
8805 @end example
8807 @noindent
8808 and similarly if the variable is unset, or if its content is changed.
8809 If the content has white space changes only, then the error is degraded
8810 to a warning only, but the old value is reused.
8812 @item
8813 @var{variable} is kept during automatic reconfiguration
8814 (@pxref{config.status Invocation}) as if it had been passed as a command
8815 line argument, including when no cache is used:
8817 @example
8818 $ @kbd{CC=/usr/bin/cc ./configure var=raboof --silent}
8819 $ @kbd{./config.status --recheck}
8820 running CONFIG_SHELL=/bin/sh /bin/sh ./configure var=raboof \
8821   CC=/usr/bin/cc  --no-create --no-recursion
8822 @end example
8823 @end itemize
8824 @end defmac
8826 @node Special Chars in Variables
8827 @section Special Characters in Output Variables
8828 @cindex Output variables, special characters in
8830 Many output variables are intended to be evaluated both by
8831 @command{make} and by the shell.  Some characters are expanded
8832 differently in these two contexts, so to avoid confusion these
8833 variables' values should not contain any of the following characters:
8835 @example
8836 " # $ & ' ( ) * ; < > ? [ \ ^ ` |
8837 @end example
8839 Also, these variables' values should neither contain newlines, nor start
8840 with @samp{~}, nor contain white space or @samp{:} immediately followed
8841 by @samp{~}.  The values can contain nonempty sequences of white space
8842 characters like tabs and spaces, but each such sequence might
8843 arbitrarily be replaced by a single space during substitution.
8845 These restrictions apply both to the values that @command{configure}
8846 computes, and to the values set directly by the user.  For example, the
8847 following invocations of @command{configure} are problematic, since they
8848 attempt to use special characters within @code{CPPFLAGS} and white space
8849 within @code{$(srcdir)}:
8851 @example
8852 CPPFLAGS='-DOUCH="&\"#$*?"' '../My Source/ouch-1.0/configure'
8854 '../My Source/ouch-1.0/configure' CPPFLAGS='-DOUCH="&\"#$*?"'
8855 @end example
8857 @node Caching Results
8858 @section Caching Results
8859 @cindex Cache
8861 To avoid checking for the same features repeatedly in various
8862 @command{configure} scripts (or in repeated runs of one script),
8863 @command{configure} can optionally save the results of many checks in a
8864 @dfn{cache file} (@pxref{Cache Files}).  If a @command{configure} script
8865 runs with caching enabled and finds a cache file, it reads the results
8866 of previous runs from the cache and avoids rerunning those checks.  As a
8867 result, @command{configure} can then run much faster than if it had to
8868 perform all of the checks every time.
8870 @defmac AC_CACHE_VAL (@var{cache-id}, @var{commands-to-set-it})
8871 @acindex{CACHE_VAL}
8872 Ensure that the results of the check identified by @var{cache-id} are
8873 available.  If the results of the check were in the cache file that was
8874 read, and @command{configure} was not given the @option{--quiet} or
8875 @option{--silent} option, print a message saying that the result was
8876 cached; otherwise, run the shell commands @var{commands-to-set-it}.  If
8877 the shell commands are run to determine the value, the value is
8878 saved in the cache file just before @command{configure} creates its output
8879 files.  @xref{Cache Variable Names}, for how to choose the name of the
8880 @var{cache-id} variable.
8882 The @var{commands-to-set-it} @emph{must have no side effects} except for
8883 setting the variable @var{cache-id}, see below.
8884 @end defmac
8886 @defmac AC_CACHE_CHECK (@var{message}, @var{cache-id}, @
8887   @var{commands-to-set-it})
8888 @acindex{CACHE_CHECK}
8889 A wrapper for @code{AC_CACHE_VAL} that takes care of printing the
8890 messages.  This macro provides a convenient shorthand for the most
8891 common way to use these macros.  It calls @code{AC_MSG_CHECKING} for
8892 @var{message}, then @code{AC_CACHE_VAL} with the @var{cache-id} and
8893 @var{commands} arguments, and @code{AC_MSG_RESULT} with @var{cache-id}.
8895 The @var{commands-to-set-it} @emph{must have no side effects} except for
8896 setting the variable @var{cache-id}, see below.
8897 @end defmac
8899 It is common to find buggy macros using @code{AC_CACHE_VAL} or
8900 @code{AC_CACHE_CHECK}, because people are tempted to call
8901 @code{AC_DEFINE} in the @var{commands-to-set-it}.  Instead, the code that
8902 @emph{follows} the call to @code{AC_CACHE_VAL} should call
8903 @code{AC_DEFINE}, by examining the value of the cache variable.  For
8904 instance, the following macro is broken:
8906 @example
8907 @group
8908 AC_DEFUN([AC_SHELL_TRUE],
8909 [AC_CACHE_CHECK([whether true(1) works], [my_cv_shell_true_works],
8910                 [my_cv_shell_true_works=no
8911                  (true) 2>/dev/null && my_cv_shell_true_works=yes
8912                  if test "$my_cv_shell_true_works" = yes; then
8913                    AC_DEFINE([TRUE_WORKS], [1],
8914                              [Define if `true(1)' works properly.])
8915                  fi])
8917 @end group
8918 @end example
8920 @noindent
8921 This fails if the cache is enabled: the second time this macro is run,
8922 @code{TRUE_WORKS} @emph{will not be defined}.  The proper implementation
8925 @example
8926 @group
8927 AC_DEFUN([AC_SHELL_TRUE],
8928 [AC_CACHE_CHECK([whether true(1) works], [my_cv_shell_true_works],
8929                 [my_cv_shell_true_works=no
8930                  (true) 2>/dev/null && my_cv_shell_true_works=yes])
8931  if test "$my_cv_shell_true_works" = yes; then
8932    AC_DEFINE([TRUE_WORKS], [1],
8933              [Define if `true(1)' works properly.])
8934  fi
8936 @end group
8937 @end example
8939 Also, @var{commands-to-set-it} should not print any messages, for
8940 example with @code{AC_MSG_CHECKING}; do that before calling
8941 @code{AC_CACHE_VAL}, so the messages are printed regardless of whether
8942 the results of the check are retrieved from the cache or determined by
8943 running the shell commands.
8945 @menu
8946 * Cache Variable Names::        Shell variables used in caches
8947 * Cache Files::                 Files @command{configure} uses for caching
8948 * Cache Checkpointing::         Loading and saving the cache file
8949 @end menu
8951 @node Cache Variable Names
8952 @subsection Cache Variable Names
8953 @cindex Cache variable
8955 The names of cache variables should have the following format:
8957 @example
8958 @var{package-prefix}_cv_@var{value-type}_@var{specific-value}_@ovar{additional-options}
8959 @end example
8961 @noindent
8962 for example, @samp{ac_cv_header_stat_broken} or
8963 @samp{ac_cv_prog_gcc_traditional}.  The parts of the variable name are:
8965 @table @asis
8966 @item @var{package-prefix}
8967 An abbreviation for your package or organization; the same prefix you
8968 begin local Autoconf macros with, except lowercase by convention.
8969 For cache values used by the distributed Autoconf macros, this value is
8970 @samp{ac}.
8972 @item @code{_cv_}
8973 Indicates that this shell variable is a cache value.  This string
8974 @emph{must} be present in the variable name, including the leading
8975 underscore.
8977 @item @var{value-type}
8978 A convention for classifying cache values, to produce a rational naming
8979 system.  The values used in Autoconf are listed in @ref{Macro Names}.
8981 @item @var{specific-value}
8982 Which member of the class of cache values this test applies to.
8983 For example, which function (@samp{alloca}), program (@samp{gcc}), or
8984 output variable (@samp{INSTALL}).
8986 @item @var{additional-options}
8987 Any particular behavior of the specific member that this test applies to.
8988 For example, @samp{broken} or @samp{set}.  This part of the name may
8989 be omitted if it does not apply.
8990 @end table
8992 The values assigned to cache variables may not contain newlines.
8993 Usually, their values are Boolean (@samp{yes} or @samp{no}) or the
8994 names of files or functions; so this is not an important restriction.
8996 @node Cache Files
8997 @subsection Cache Files
8999 A cache file is a shell script that caches the results of configure
9000 tests run on one system so they can be shared between configure scripts
9001 and configure runs.  It is not useful on other systems.  If its contents
9002 are invalid for some reason, the user may delete or edit it.
9004 By default, @command{configure} uses no cache file,
9005 to avoid problems caused by accidental
9006 use of stale cache files.
9008 To enable caching, @command{configure} accepts @option{--config-cache} (or
9009 @option{-C}) to cache results in the file @file{config.cache}.
9010 Alternatively, @option{--cache-file=@var{file}} specifies that
9011 @var{file} be the cache file.  The cache file is created if it does not
9012 exist already.  When @command{configure} calls @command{configure} scripts in
9013 subdirectories, it uses the @option{--cache-file} argument so that they
9014 share the same cache.  @xref{Subdirectories}, for information on
9015 configuring subdirectories with the @code{AC_CONFIG_SUBDIRS} macro.
9017 @file{config.status} only pays attention to the cache file if it is
9018 given the @option{--recheck} option, which makes it rerun
9019 @command{configure}.
9021 It is wrong to try to distribute cache files for particular system types.
9022 There is too much room for error in doing that, and too much
9023 administrative overhead in maintaining them.  For any features that
9024 can't be guessed automatically, use the standard method of the canonical
9025 system type and linking files (@pxref{Manual Configuration}).
9027 The site initialization script can specify a site-wide cache file to
9028 use, instead of the usual per-program cache.  In this case, the cache
9029 file gradually accumulates information whenever someone runs a new
9030 @command{configure} script.  (Running @command{configure} merges the new cache
9031 results with the existing cache file.)  This may cause problems,
9032 however, if the system configuration (e.g., the installed libraries or
9033 compilers) changes and the stale cache file is not deleted.
9035 @node Cache Checkpointing
9036 @subsection Cache Checkpointing
9038 If your configure script, or a macro called from @file{configure.ac}, happens
9039 to abort the configure process, it may be useful to checkpoint the cache
9040 a few times at key points using @code{AC_CACHE_SAVE}.  Doing so
9041 reduces the amount of time it takes to rerun the configure script with
9042 (hopefully) the error that caused the previous abort corrected.
9044 @c FIXME: Do we really want to document this guy?
9045 @defmac AC_CACHE_LOAD
9046 @acindex{CACHE_LOAD}
9047 Loads values from existing cache file, or creates a new cache file if a
9048 cache file is not found.  Called automatically from @code{AC_INIT}.
9049 @end defmac
9051 @defmac AC_CACHE_SAVE
9052 @acindex{CACHE_SAVE}
9053 Flushes all cached values to the cache file.  Called automatically from
9054 @code{AC_OUTPUT}, but it can be quite useful to call
9055 @code{AC_CACHE_SAVE} at key points in @file{configure.ac}.
9056 @end defmac
9058 For instance:
9060 @example
9061 @r{ @dots{} AC_INIT, etc. @dots{}}
9062 @group
9063 # Checks for programs.
9064 AC_PROG_CC
9065 AC_PROG_AWK
9066 @r{ @dots{} more program checks @dots{}}
9067 AC_CACHE_SAVE
9068 @end group
9070 @group
9071 # Checks for libraries.
9072 AC_CHECK_LIB([nsl], [gethostbyname])
9073 AC_CHECK_LIB([socket], [connect])
9074 @r{ @dots{} more lib checks @dots{}}
9075 AC_CACHE_SAVE
9076 @end group
9078 @group
9079 # Might abort@dots{}
9080 AM_PATH_GTK([1.0.2], [], [AC_MSG_ERROR([GTK not in path])])
9081 AM_PATH_GTKMM([0.9.5], [], [AC_MSG_ERROR([GTK not in path])])
9082 @end group
9083 @r{ @dots{} AC_OUTPUT, etc. @dots{}}
9084 @end example
9086 @node Printing Messages
9087 @section Printing Messages
9088 @cindex Messages, from @command{configure}
9090 @command{configure} scripts need to give users running them several kinds
9091 of information.  The following macros print messages in ways appropriate
9092 for each kind.  The arguments to all of them get enclosed in shell
9093 double quotes, so the shell performs variable and back-quote
9094 substitution on them.
9096 These macros are all wrappers around the @command{echo} shell command.
9097 They direct output to the appropriate file descriptor (@pxref{File
9098 Descriptor Macros}).
9099 @command{configure} scripts should rarely need to run @command{echo} directly
9100 to print messages for the user.  Using these macros makes it easy to
9101 change how and when each kind of message is printed; such changes need
9102 only be made to the macro definitions and all the callers change
9103 automatically.
9105 To diagnose static issues, i.e., when @command{autoconf} is run, see
9106 @ref{Diagnostic Macros}.
9108 @defmac AC_MSG_CHECKING (@var{feature-description})
9109 @acindex{MSG_CHECKING}
9110 Notify the user that @command{configure} is checking for a particular
9111 feature.  This macro prints a message that starts with @samp{checking }
9112 and ends with @samp{...} and no newline.  It must be followed by a call
9113 to @code{AC_MSG_RESULT} to print the result of the check and the
9114 newline.  The @var{feature-description} should be something like
9115 @samp{whether the Fortran compiler accepts C++ comments} or @samp{for
9116 c89}.
9118 This macro prints nothing if @command{configure} is run with the
9119 @option{--quiet} or @option{--silent} option.
9120 @end defmac
9122 @anchor{AC_MSG_RESULT}
9123 @defmac AC_MSG_RESULT (@var{result-description})
9124 @acindex{MSG_RESULT}
9125 Notify the user of the results of a check.  @var{result-description} is
9126 almost always the value of the cache variable for the check, typically
9127 @samp{yes}, @samp{no}, or a file name.  This macro should follow a call
9128 to @code{AC_MSG_CHECKING}, and the @var{result-description} should be
9129 the completion of the message printed by the call to
9130 @code{AC_MSG_CHECKING}.
9132 This macro prints nothing if @command{configure} is run with the
9133 @option{--quiet} or @option{--silent} option.
9134 @end defmac
9136 @anchor{AC_MSG_NOTICE}
9137 @defmac AC_MSG_NOTICE (@var{message})
9138 @acindex{MSG_NOTICE}
9139 Deliver the @var{message} to the user.  It is useful mainly to print a
9140 general description of the overall purpose of a group of feature checks,
9141 e.g.,
9143 @example
9144 AC_MSG_NOTICE([checking if stack overflow is detectable])
9145 @end example
9147 This macro prints nothing if @command{configure} is run with the
9148 @option{--quiet} or @option{--silent} option.
9149 @end defmac
9151 @anchor{AC_MSG_ERROR}
9152 @defmac AC_MSG_ERROR (@var{error-description}, @ovar{exit-status})
9153 @acindex{MSG_ERROR}
9154 Notify the user of an error that prevents @command{configure} from
9155 completing.  This macro prints an error message to the standard error
9156 output and exits @command{configure} with @var{exit-status} (1 by default).
9157 @var{error-description} should be something like @samp{invalid value
9158 $HOME for \$HOME}.
9160 The @var{error-description} should start with a lower-case letter, and
9161 ``cannot'' is preferred to ``can't''.
9162 @end defmac
9164 @defmac AC_MSG_FAILURE (@var{error-description}, @ovar{exit-status})
9165 @acindex{MSG_FAILURE}
9166 This @code{AC_MSG_ERROR} wrapper notifies the user of an error that
9167 prevents @command{configure} from completing @emph{and} that additional
9168 details are provided in @file{config.log}.  This is typically used when
9169 abnormal results are found during a compilation.
9170 @end defmac
9172 @anchor{AC_MSG_WARN}
9173 @defmac AC_MSG_WARN (@var{problem-description})
9174 @acindex{MSG_WARN}
9175 Notify the @command{configure} user of a possible problem.  This macro
9176 prints the message to the standard error output; @command{configure}
9177 continues running afterward, so macros that call @code{AC_MSG_WARN} should
9178 provide a default (back-up) behavior for the situations they warn about.
9179 @var{problem-description} should be something like @samp{ln -s seems to
9180 make hard links}.
9181 @end defmac
9185 @c ====================================================== Programming in M4.
9187 @node Programming in M4
9188 @chapter Programming in M4
9189 @cindex M4
9191 Autoconf is written on top of two layers: @dfn{M4sugar}, which provides
9192 convenient macros for pure M4 programming, and @dfn{M4sh}, which
9193 provides macros dedicated to shell script generation.
9195 As of this version of Autoconf, these two layers still contain
9196 experimental macros, whose interface might change in the future.  As a
9197 matter of fact, @emph{anything that is not documented must not be used}.
9199 @menu
9200 * M4 Quotation::                Protecting macros from unwanted expansion
9201 * Using autom4te::              The Autoconf executables backbone
9202 * Programming in M4sugar::      Convenient pure M4 macros
9203 * Programming in M4sh::         Common shell Constructs
9204 * File Descriptor Macros::      File descriptor macros for input and output
9205 @end menu
9207 @node M4 Quotation
9208 @section M4 Quotation
9209 @cindex M4 quotation
9210 @cindex quotation
9212 The most common problem with existing macros is an improper quotation.
9213 This section, which users of Autoconf can skip, but which macro writers
9214 @emph{must} read, first justifies the quotation scheme that was chosen
9215 for Autoconf and then ends with a rule of thumb.  Understanding the
9216 former helps one to follow the latter.
9218 @menu
9219 * Active Characters::           Characters that change the behavior of M4
9220 * One Macro Call::              Quotation and one macro call
9221 * Quoting and Parameters::      M4 vs. shell parameters
9222 * Quotation and Nested Macros::  Macros calling macros
9223 * Changequote is Evil::         Worse than INTERCAL: M4 + changequote
9224 * Quadrigraphs::                Another way to escape special characters
9225 * Quotation Rule Of Thumb::     One parenthesis, one quote
9226 @end menu
9228 @node Active Characters
9229 @subsection Active Characters
9231 To fully understand where proper quotation is important, you first need
9232 to know what the special characters are in Autoconf: @samp{#} introduces
9233 a comment inside which no macro expansion is performed, @samp{,}
9234 separates arguments, @samp{[} and @samp{]} are the quotes themselves,
9235 @samp{(} and @samp{)} (which M4 tries to match by pairs), and finally
9236 @samp{$} inside a macro definition.
9238 In order to understand the delicate case of macro calls, we first have
9239 to present some obvious failures.  Below they are ``obvious-ified'',
9240 but when you find them in real life, they are usually in disguise.
9242 Comments, introduced by a hash and running up to the newline, are opaque
9243 tokens to the top level: active characters are turned off, and there is
9244 no macro expansion:
9246 @example
9247 # define([def], ine)
9248 @result{}# define([def], ine)
9249 @end example
9251 Each time there can be a macro expansion, there is a quotation
9252 expansion, i.e., one level of quotes is stripped:
9254 @example
9255 int tab[10];
9256 @result{}int tab10;
9257 [int tab[10];]
9258 @result{}int tab[10];
9259 @end example
9261 Without this in mind, the reader might try hopelessly to use her macro
9262 @code{array}:
9264 @example
9265 define([array], [int tab[10];])
9266 array
9267 @result{}int tab10;
9268 [array]
9269 @result{}array
9270 @end example
9272 @noindent
9273 How can you correctly output the intended results@footnote{Using
9274 @code{defn}.}?
9277 @node One Macro Call
9278 @subsection One Macro Call
9280 Let's proceed on the interaction between active characters and macros
9281 with this small macro, which just returns its first argument:
9283 @example
9284 define([car], [$1])
9285 @end example
9287 @noindent
9288 The two pairs of quotes above are not part of the arguments of
9289 @code{define}; rather, they are understood by the top level when it
9290 tries to find the arguments of @code{define}.  Therefore, assuming
9291 @code{car} is not already defined, it is equivalent to write:
9293 @example
9294 define(car, $1)
9295 @end example
9297 @noindent
9298 But, while it is acceptable for a @file{configure.ac} to avoid unnecessary
9299 quotes, it is bad practice for Autoconf macros which must both be more
9300 robust and also advocate perfect style.
9302 At the top level, there are only two possibilities: either you
9303 quote or you don't:
9305 @example
9306 car(foo, bar, baz)
9307 @result{}foo
9308 [car(foo, bar, baz)]
9309 @result{}car(foo, bar, baz)
9310 @end example
9312 Let's pay attention to the special characters:
9314 @example
9315 car(#)
9316 @error{}EOF in argument list
9317 @end example
9319 The closing parenthesis is hidden in the comment; with a hypothetical
9320 quoting, the top level understood it this way:
9322 @example
9323 car([#)]
9324 @end example
9326 @noindent
9327 Proper quotation, of course, fixes the problem:
9329 @example
9330 car([#])
9331 @result{}#
9332 @end example
9334 Here are more examples:
9336 @example
9337 car(foo, bar)
9338 @result{}foo
9339 car([foo, bar])
9340 @result{}foo, bar
9341 car((foo, bar))
9342 @result{}(foo, bar)
9343 car([(foo], [bar)])
9344 @result{}(foo
9345 define([a], [b])
9346 @result{}
9347 car(a)
9348 @result{}b
9349 car([a])
9350 @result{}b
9351 car([[a]])
9352 @result{}a
9353 car([[[a]]])
9354 @result{}[a]
9355 @end example
9357 @node Quoting and Parameters
9358 @subsection Quoting and Parameters
9360 When M4 encounters @samp{$} within a macro definition, followed
9361 immediately by a character it recognizes (@samp{0}@dots{}@samp{9},
9362 @samp{#}, @samp{@@}, or @samp{*}), it will perform M4 parameter
9363 expansion.  This happens regardless of how many layers of quotes the
9364 parameter expansion is nested within, or even if it occurs in text that
9365 will be rescanned as a comment.
9367 @example
9368 define([none], [$1])
9369 @result{}
9370 define([one], [[$1]])
9371 @result{}
9372 define([two], [[[$1]]])
9373 @result{}
9374 define([comment], [# $1])
9375 @result{}
9376 define([active], [ACTIVE])
9377 @result{}
9378 none([active])
9379 @result{}ACTIVE
9380 one([active])
9381 @result{}active
9382 two([active])
9383 @result{}[active]
9384 comment([active])
9385 @result{}# active
9386 @end example
9388 On the other hand, since autoconf generates shell code, you often want
9389 to output shell variable expansion, rather than performing M4 parameter
9390 expansion.  To do this, you must use M4 quoting to separate the @samp{$}
9391 from the next character in the definition of your macro.  If the macro
9392 definition occurs in single-quoted text, then insert another level of
9393 quoting; if the usage is already inside a double-quoted string, then
9394 split it into concatenated strings.
9396 @example
9397 define([single], [a single-quoted $[]1 definition])
9398 @result{}
9399 define([double], [[a double-quoted $][1 definition]])
9400 @result{}
9401 single
9402 @result{}a single-quoted $1 definition
9403 double
9404 @result{}a double-quoted $1 definition
9405 @end example
9407 Posix states that M4 implementations are free to provide implementation
9408 extensions when @samp{$@{} is encountered in a macro definition.
9409 Autoconf reserves the longer sequence @samp{$@{@{} for use with planned
9410 extensions that will be available in the future @acronym{GNU} M4 2.0,
9411 but guarantees that all other instances of @samp{$@{} will be output
9412 literally.  Therefore, this idiom can also be used to output shell code
9413 parameter references:
9415 @example
9416 define([first], [$@{1@}])first
9417 @result{}$@{1@}
9418 @end example
9420 Posix also states that @samp{$11} should expand to the first parameter
9421 concatenated with a literal @samp{1}, although some versions of
9422 @acronym{GNU} M4 expand the eleventh parameter instead.  For
9423 portability, you should only use single-digit M4 parameter expansion.
9425 With this in mind, we can explore the cases where macros invoke
9426 macros@enddots{}
9428 @node Quotation and Nested Macros
9429 @subsection Quotation and Nested Macros
9431 The examples below use the following macros:
9433 @example
9434 define([car], [$1])
9435 define([active], [ACT, IVE])
9436 define([array], [int tab[10]])
9437 @end example
9439 Each additional embedded macro call introduces other possible
9440 interesting quotations:
9442 @example
9443 car(active)
9444 @result{}ACT
9445 car([active])
9446 @result{}ACT, IVE
9447 car([[active]])
9448 @result{}active
9449 @end example
9451 In the first case, the top level looks for the arguments of @code{car},
9452 and finds @samp{active}.  Because M4 evaluates its arguments
9453 before applying the macro, @samp{active} is expanded, which results in:
9455 @example
9456 car(ACT, IVE)
9457 @result{}ACT
9458 @end example
9460 @noindent
9461 In the second case, the top level gives @samp{active} as first and only
9462 argument of @code{car}, which results in:
9464 @example
9465 active
9466 @result{}ACT, IVE
9467 @end example
9469 @noindent
9470 i.e., the argument is evaluated @emph{after} the macro that invokes it.
9471 In the third case, @code{car} receives @samp{[active]}, which results in:
9473 @example
9474 [active]
9475 @result{}active
9476 @end example
9478 @noindent
9479 exactly as we already saw above.
9481 The example above, applied to a more realistic example, gives:
9483 @example
9484 car(int tab[10];)
9485 @result{}int tab10;
9486 car([int tab[10];])
9487 @result{}int tab10;
9488 car([[int tab[10];]])
9489 @result{}int tab[10];
9490 @end example
9492 @noindent
9493 Huh?  The first case is easily understood, but why is the second wrong,
9494 and the third right?  To understand that, you must know that after
9495 M4 expands a macro, the resulting text is immediately subjected
9496 to macro expansion and quote removal.  This means that the quote removal
9497 occurs twice---first before the argument is passed to the @code{car}
9498 macro, and second after the @code{car} macro expands to the first
9499 argument.
9501 As the author of the Autoconf macro @code{car}, you then consider it to
9502 be incorrect that your users have to double-quote the arguments of
9503 @code{car}, so you ``fix'' your macro.  Let's call it @code{qar} for
9504 quoted car:
9506 @example
9507 define([qar], [[$1]])
9508 @end example
9510 @noindent
9511 and check that @code{qar} is properly fixed:
9513 @example
9514 qar([int tab[10];])
9515 @result{}int tab[10];
9516 @end example
9518 @noindent
9519 Ahhh!  That's much better.
9521 But note what you've done: now that the result of @code{qar} is always
9522 a literal string, the only time a user can use nested macros is if she
9523 relies on an @emph{unquoted} macro call:
9525 @example
9526 qar(active)
9527 @result{}ACT
9528 qar([active])
9529 @result{}active
9530 @end example
9532 @noindent
9533 leaving no way for her to reproduce what she used to do with @code{car}:
9535 @example
9536 car([active])
9537 @result{}ACT, IVE
9538 @end example
9540 @noindent
9541 Worse yet: she wants to use a macro that produces a set of @code{cpp}
9542 macros:
9544 @example
9545 define([my_includes], [#include <stdio.h>])
9546 car([my_includes])
9547 @result{}#include <stdio.h>
9548 qar(my_includes)
9549 @error{}EOF in argument list
9550 @end example
9552 This macro, @code{qar}, because it double quotes its arguments, forces
9553 its users to leave their macro calls unquoted, which is dangerous.
9554 Commas and other active symbols are interpreted by M4 before
9555 they are given to the macro, often not in the way the users expect.
9556 Also, because @code{qar} behaves differently from the other macros,
9557 it's an exception that should be avoided in Autoconf.
9559 @node Changequote is Evil
9560 @subsection @code{changequote} is Evil
9561 @cindex @code{changequote}
9563 The temptation is often high to bypass proper quotation, in particular
9564 when it's late at night.  Then, many experienced Autoconf hackers
9565 finally surrender to the dark side of the force and use the ultimate
9566 weapon: @code{changequote}.
9568 The M4 builtin @code{changequote} belongs to a set of primitives that
9569 allow one to adjust the syntax of the language to adjust it to one's
9570 needs.  For instance, by default M4 uses @samp{`} and @samp{'} as
9571 quotes, but in the context of shell programming (and actually of most
9572 programming languages), that's about the worst choice one can make:
9573 because of strings and back-quoted expressions in shell code (such as
9574 @samp{'this'} and @samp{`that`}), and because of literal characters in usual
9575 programming languages (as in @samp{'0'}), there are many unbalanced
9576 @samp{`} and @samp{'}.  Proper M4 quotation then becomes a nightmare, if
9577 not impossible.  In order to make M4 useful in such a context, its
9578 designers have equipped it with @code{changequote}, which makes it
9579 possible to choose another pair of quotes.  M4sugar, M4sh, Autoconf, and
9580 Autotest all have chosen to use @samp{[} and @samp{]}.  Not especially
9581 because they are unlikely characters, but @emph{because they are
9582 characters unlikely to be unbalanced}.
9584 There are other magic primitives, such as @code{changecom} to specify
9585 what syntactic forms are comments (it is common to see
9586 @samp{changecom(<!--, -->)} when M4 is used to produce HTML pages),
9587 @code{changeword} and @code{changesyntax} to change other syntactic
9588 details (such as the character to denote the @var{n}th argument, @samp{$} by
9589 default, the parentheses around arguments, etc.).
9591 These primitives are really meant to make M4 more useful for specific
9592 domains: they should be considered like command line options:
9593 @option{--quotes}, @option{--comments}, @option{--words}, and
9594 @option{--syntax}.  Nevertheless, they are implemented as M4 builtins, as
9595 it makes M4 libraries self contained (no need for additional options).
9597 There lies the problem@enddots{}
9599 @sp 1
9601 The problem is that it is then tempting to use them in the middle of an
9602 M4 script, as opposed to its initialization.  This, if not carefully
9603 thought out, can lead to disastrous effects: @emph{you are changing the
9604 language in the middle of the execution}.  Changing and restoring the
9605 syntax is often not enough: if you happened to invoke macros in between,
9606 these macros are lost, as the current syntax is probably not
9607 the one they were implemented with.
9609 @c FIXME: I've been looking for a short, real case example, but I
9610 @c lost them all :(
9613 @node Quadrigraphs
9614 @subsection Quadrigraphs
9615 @cindex quadrigraphs
9616 @cindex @samp{@@S|@@}
9617 @cindex @samp{@@&t@@}
9618 @c Info cannot handle `:' in index entries.
9619 @c @cindex @samp{@@<:@@}
9620 @c @cindex @samp{@@:>@@}
9621 @c @cindex @samp{@@%:@@}
9623 When writing an Autoconf macro you may occasionally need to generate
9624 special characters that are difficult to express with the standard
9625 Autoconf quoting rules.  For example, you may need to output the regular
9626 expression @samp{[^[]}, which matches any character other than @samp{[}.
9627 This expression contains unbalanced brackets so it cannot be put easily
9628 into an M4 macro.
9630 You can work around this problem by using one of the following
9631 @dfn{quadrigraphs}:
9633 @table @samp
9634 @item @@<:@@
9635 @samp{[}
9636 @item @@:>@@
9637 @samp{]}
9638 @item @@S|@@
9639 @samp{$}
9640 @item @@%:@@
9641 @samp{#}
9642 @item @@&t@@
9643 Expands to nothing.
9644 @end table
9646 Quadrigraphs are replaced at a late stage of the translation process,
9647 after @command{m4} is run, so they do not get in the way of M4 quoting.
9648 For example, the string @samp{^@@<:@@}, independently of its quotation,
9649 appears as @samp{^[} in the output.
9651 The empty quadrigraph can be used:
9653 @itemize @minus
9654 @item to mark trailing spaces explicitly
9656 Trailing spaces are smashed by @command{autom4te}.  This is a feature.
9658 @item to produce other quadrigraphs
9660 For instance @samp{@@<@@&t@@:@@} produces @samp{@@<:@@}.
9662 @item to escape @emph{occurrences} of forbidden patterns
9664 For instance you might want to mention @code{AC_FOO} in a comment, while
9665 still being sure that @command{autom4te} still catches unexpanded
9666 @samp{AC_*}.  Then write @samp{AC@@&t@@_FOO}.
9667 @end itemize
9669 The name @samp{@@&t@@} was suggested by Paul Eggert:
9671 @quotation
9672 I should give some credit to the @samp{@@&t@@} pun.  The @samp{&} is my
9673 own invention, but the @samp{t} came from the source code of the
9674 @sc{algol68c} compiler, written by Steve Bourne (of Bourne shell fame),
9675 and which used @samp{mt} to denote the empty string.  In C, it would
9676 have looked like something like:
9678 @example
9679 char const mt[] = "";
9680 @end example
9682 @noindent
9683 but of course the source code was written in Algol 68.
9685 I don't know where he got @samp{mt} from: it could have been his own
9686 invention, and I suppose it could have been a common pun around the
9687 Cambridge University computer lab at the time.
9688 @end quotation
9690 @node Quotation Rule Of Thumb
9691 @subsection Quotation Rule Of Thumb
9693 To conclude, the quotation rule of thumb is:
9695 @center @emph{One pair of quotes per pair of parentheses.}
9697 Never over-quote, never under-quote, in particular in the definition of
9698 macros.  In the few places where the macros need to use brackets
9699 (usually in C program text or regular expressions), properly quote
9700 @emph{the arguments}!
9702 It is common to read Autoconf programs with snippets like:
9704 @example
9705 AC_TRY_LINK(
9706 changequote(<<, >>)dnl
9707 <<#include <time.h>
9708 #ifndef tzname /* For SGI.  */
9709 extern char *tzname[]; /* RS6000 and others reject char **tzname.  */
9710 #endif>>,
9711 changequote([, ])dnl
9712 [atoi (*tzname);], ac_cv_var_tzname=yes, ac_cv_var_tzname=no)
9713 @end example
9715 @noindent
9716 which is incredibly useless since @code{AC_TRY_LINK} is @emph{already}
9717 double quoting, so you just need:
9719 @example
9720 AC_TRY_LINK(
9721 [#include <time.h>
9722 #ifndef tzname /* For SGI.  */
9723 extern char *tzname[]; /* RS6000 and others reject char **tzname.  */
9724 #endif],
9725             [atoi (*tzname);],
9726             [ac_cv_var_tzname=yes],
9727             [ac_cv_var_tzname=no])
9728 @end example
9730 @noindent
9731 The M4-fluent reader might note that these two examples are rigorously
9732 equivalent, since M4 swallows both the @samp{changequote(<<, >>)}
9733 and @samp{<<} @samp{>>} when it @dfn{collects} the arguments: these
9734 quotes are not part of the arguments!
9736 Simplified, the example above is just doing this:
9738 @example
9739 changequote(<<, >>)dnl
9740 <<[]>>
9741 changequote([, ])dnl
9742 @end example
9744 @noindent
9745 instead of simply:
9747 @example
9748 [[]]
9749 @end example
9751 With macros that do not double quote their arguments (which is the
9752 rule), double-quote the (risky) literals:
9754 @example
9755 AC_LINK_IFELSE([AC_LANG_PROGRAM(
9756 [[#include <time.h>
9757 #ifndef tzname /* For SGI.  */
9758 extern char *tzname[]; /* RS6000 and others reject char **tzname.  */
9759 #endif]],
9760                                 [atoi (*tzname);])],
9761                [ac_cv_var_tzname=yes],
9762                [ac_cv_var_tzname=no])
9763 @end example
9765 Please note that the macro @code{AC_TRY_LINK} is obsolete, so you really
9766 should be using @code{AC_LINK_IFELSE} instead.
9768 @xref{Quadrigraphs}, for what to do if you run into a hopeless case
9769 where quoting does not suffice.
9771 When you create a @command{configure} script using newly written macros,
9772 examine it carefully to check whether you need to add more quotes in
9773 your macros.  If one or more words have disappeared in the M4
9774 output, you need more quotes.  When in doubt, quote.
9776 However, it's also possible to put on too many layers of quotes.  If
9777 this happens, the resulting @command{configure} script may contain
9778 unexpanded macros.  The @command{autoconf} program checks for this problem
9779 by looking for the string @samp{AC_} in @file{configure}.  However, this
9780 heuristic does not work in general: for example, it does not catch
9781 overquoting in @code{AC_DEFINE} descriptions.
9784 @c ---------------------------------------- Using autom4te
9786 @node Using autom4te
9787 @section Using @command{autom4te}
9789 The Autoconf suite, including M4sugar, M4sh, and Autotest, in addition
9790 to Autoconf per se, heavily rely on M4.  All these different uses
9791 revealed common needs factored into a layer over M4:
9792 @command{autom4te}@footnote{
9794 Yet another great name from Lars J. Aas.
9798 @command{autom4te} is a preprocessor that is like @command{m4}.
9799 It supports M4 extensions designed for use in tools like Autoconf.
9801 @menu
9802 * autom4te Invocation::         A @acronym{GNU} M4 wrapper
9803 * Customizing autom4te::        Customizing the Autoconf package
9804 @end menu
9806 @node autom4te Invocation
9807 @subsection Invoking @command{autom4te}
9809 The command line arguments are modeled after M4's:
9811 @example
9812 autom4te @var{options} @var{files}
9813 @end example
9815 @noindent
9816 @evindex M4
9817 where the @var{files} are directly passed to @command{m4}.  By default,
9818 @acronym{GNU} M4 is found during configuration, but the environment
9819 variable
9820 @env{M4} can be set to tell @command{autom4te} where to look.  In addition
9821 to the regular expansion, it handles the replacement of the quadrigraphs
9822 (@pxref{Quadrigraphs}), and of @samp{__oline__}, the current line in the
9823 output.  It supports an extended syntax for the @var{files}:
9825 @table @file
9826 @item @var{file}.m4f
9827 This file is an M4 frozen file.  Note that @emph{all the previous files
9828 are ignored}.  See the option @option{--melt} for the rationale.
9830 @item @var{file}?
9831 If found in the library path, the @var{file} is included for expansion,
9832 otherwise it is ignored instead of triggering a failure.
9833 @end table
9835 @sp 1
9837 Of course, it supports the Autoconf common subset of options:
9839 @table @option
9840 @item --help
9841 @itemx -h
9842 Print a summary of the command line options and exit.
9844 @item --version
9845 @itemx -V
9846 Print the version number of Autoconf and exit.
9848 @item --verbose
9849 @itemx -v
9850 Report processing steps.
9852 @item --debug
9853 @itemx -d
9854 Don't remove the temporary files and be even more verbose.
9856 @item --include=@var{dir}
9857 @itemx -I @var{dir}
9858 Also look for input files in @var{dir}.  Multiple invocations
9859 accumulate.
9861 @item --output=@var{file}
9862 @itemx -o @var{file}
9863 Save output (script or trace) to @var{file}.  The file @option{-} stands
9864 for the standard output.
9865 @end table
9867 @sp 1
9869 As an extension of @command{m4}, it includes the following options:
9871 @table @option
9872 @item --warnings=@var{category}
9873 @itemx -W @var{category}
9874 @evindex WARNINGS
9875 @c FIXME: Point to the M4sugar macros, not Autoconf's.
9876 Report the warnings related to @var{category} (which can actually be a
9877 comma separated list).  @xref{Reporting Messages}, macro
9878 @code{AC_DIAGNOSE}, for a comprehensive list of categories.  Special
9879 values include:
9881 @table @samp
9882 @item all
9883 report all the warnings
9885 @item none
9886 report none
9888 @item error
9889 treats warnings as errors
9891 @item no-@var{category}
9892 disable warnings falling into @var{category}
9893 @end table
9895 Warnings about @samp{syntax} are enabled by default, and the environment
9896 variable @env{WARNINGS}, a comma separated list of categories, is
9897 honored.  @samp{autom4te -W @var{category}} actually
9898 behaves as if you had run:
9900 @example
9901 autom4te --warnings=syntax,$WARNINGS,@var{category}
9902 @end example
9904 @noindent
9905 For example, if you want to disable defaults and @env{WARNINGS}
9906 of @command{autom4te}, but enable the warnings about obsolete
9907 constructs, you would use @option{-W none,obsolete}.
9909 @cindex Back trace
9910 @cindex Macro invocation stack
9911 @command{autom4te} displays a back trace for errors, but not for
9912 warnings; if you want them, just pass @option{-W error}.
9914 @item --melt
9915 @itemx -M
9916 Do not use frozen files.  Any argument @code{@var{file}.m4f} is
9917 replaced by @code{@var{file}.m4}.  This helps tracing the macros which
9918 are executed only when the files are frozen, typically
9919 @code{m4_define}.  For instance, running:
9921 @example
9922 autom4te --melt 1.m4 2.m4f 3.m4 4.m4f input.m4
9923 @end example
9925 @noindent
9926 is roughly equivalent to running:
9928 @example
9929 m4 1.m4 2.m4 3.m4 4.m4 input.m4
9930 @end example
9932 @noindent
9933 while
9935 @example
9936 autom4te 1.m4 2.m4f 3.m4 4.m4f input.m4
9937 @end example
9939 @noindent
9940 is equivalent to:
9942 @example
9943 m4 --reload-state=4.m4f input.m4
9944 @end example
9946 @item --freeze
9947 @itemx -f
9948 Produce a frozen state file.  @command{autom4te} freezing is stricter
9949 than M4's: it must produce no warnings, and no output other than empty
9950 lines (a line with white space is @emph{not} empty) and comments
9951 (starting with @samp{#}).  Unlike @command{m4}'s similarly-named option,
9952 this option takes no argument:
9954 @example
9955 autom4te 1.m4 2.m4 3.m4 --freeze --output=3.m4f
9956 @end example
9958 @noindent
9959 corresponds to
9961 @example
9962 m4 1.m4 2.m4 3.m4 --freeze-state=3.m4f
9963 @end example
9965 @item --mode=@var{octal-mode}
9966 @itemx -m @var{octal-mode}
9967 Set the mode of the non-traces output to @var{octal-mode}; by default
9968 @samp{0666}.
9969 @end table
9971 @sp 1
9973 @cindex @file{autom4te.cache}
9974 As another additional feature over @command{m4}, @command{autom4te}
9975 caches its results.  @acronym{GNU} M4 is able to produce a regular
9976 output and traces at the same time.  Traces are heavily used in the
9977 @acronym{GNU} Build System: @command{autoheader} uses them to build
9978 @file{config.h.in}, @command{autoreconf} to determine what
9979 @acronym{GNU} Build System components are used, @command{automake} to
9980 ``parse'' @file{configure.ac} etc.  To avoid recomputation,
9981 traces are cached while performing regular expansion,
9982 and conversely.  This cache is (actually, the caches are) stored in
9983 the directory @file{autom4te.cache}.  @emph{It can safely be removed}
9984 at any moment (especially if for some reason @command{autom4te}
9985 considers it trashed).
9987 @table @option
9988 @item --cache=@var{directory}
9989 @itemx -C @var{directory}
9990 Specify the name of the directory where the result should be cached.
9991 Passing an empty value disables caching.  Be sure to pass a relative
9992 file name, as for the time being, global caches are not supported.
9994 @item --no-cache
9995 Don't cache the results.
9997 @item --force
9998 @itemx -f
9999 If a cache is used, consider it obsolete (but update it anyway).
10000 @end table
10002 @sp 1
10004 Because traces are so important to the @acronym{GNU} Build System,
10005 @command{autom4te} provides high level tracing features as compared to
10006 M4, and helps exploiting the cache:
10008 @table @option
10009 @item --trace=@var{macro}[:@var{format}]
10010 @itemx -t @var{macro}[:@var{format}]
10011 Trace the invocations of @var{macro} according to the @var{format}.
10012 Multiple @option{--trace} arguments can be used to list several macros.
10013 Multiple @option{--trace} arguments for a single macro are not
10014 cumulative; instead, you should just make @var{format} as long as
10015 needed.
10017 The @var{format} is a regular string, with newlines if desired, and
10018 several special escape codes.  It defaults to @samp{$f:$l:$n:$%}.  It can
10019 use the following special escapes:
10021 @table @samp
10022 @item $$
10023 The character @samp{$}.
10025 @item $f
10026 The file name from which @var{macro} is called.
10028 @item $l
10029 The line number from which @var{macro} is called.
10031 @item $d
10032 The depth of the @var{macro} call.  This is an M4 technical detail that
10033 you probably don't want to know about.
10035 @item $n
10036 The name of the @var{macro}.
10038 @item $@var{num}
10039 The @var{num}th argument of the call to @var{macro}.
10041 @item $@@
10042 @itemx $@var{sep}@@
10043 @itemx $@{@var{separator}@}@@
10044 All the arguments passed to @var{macro}, separated by the character
10045 @var{sep} or the string @var{separator} (@samp{,} by default).  Each
10046 argument is quoted, i.e., enclosed in a pair of square brackets.
10048 @item $*
10049 @itemx $@var{sep}*
10050 @itemx $@{@var{separator}@}*
10051 As above, but the arguments are not quoted.
10053 @item $%
10054 @itemx $@var{sep}%
10055 @itemx $@{@var{separator}@}%
10056 As above, but the arguments are not quoted, all new line characters in
10057 the arguments are smashed, and the default separator is @samp{:}.
10059 The escape @samp{$%} produces single-line trace outputs (unless you put
10060 newlines in the @samp{separator}), while @samp{$@@} and @samp{$*} do
10061 not.
10062 @end table
10064 @xref{autoconf Invocation}, for examples of trace uses.
10066 @item --preselect=@var{macro}
10067 @itemx -p @var{macro}
10068 Cache the traces of @var{macro}, but do not enable traces.  This is
10069 especially important to save CPU cycles in the future.  For instance,
10070 when invoked, @command{autoconf} preselects all the macros that
10071 @command{autoheader}, @command{automake}, @command{autoreconf}, etc.,
10072 trace, so that running @command{m4} is not needed to trace them: the
10073 cache suffices.  This results in a huge speed-up.
10074 @end table
10076 @sp 1
10078 @cindex Autom4te Library
10079 Finally, @command{autom4te} introduces the concept of @dfn{Autom4te
10080 libraries}.  They consists in a powerful yet extremely simple feature:
10081 sets of combined command line arguments:
10083 @table @option
10084 @item --language=@var{language}
10085 @itemx -l @var{language}
10086 Use the @var{language} Autom4te library.  Current languages include:
10088 @table @code
10089 @item M4sugar
10090 create M4sugar output.
10092 @item M4sh
10093 create M4sh executable shell scripts.
10095 @item Autotest
10096 create Autotest executable test suites.
10098 @item Autoconf-without-aclocal-m4
10099 create Autoconf executable configure scripts without
10100 reading @file{aclocal.m4}.
10102 @item Autoconf
10103 create Autoconf executable configure scripts.  This language inherits
10104 all the characteristics of @code{Autoconf-without-aclocal-m4} and
10105 additionally reads @file{aclocal.m4}.
10106 @end table
10108 @item --prepend-include=@var{dir}
10109 @item -B @var{dir}
10110 Prepend directory @var{dir} to the search path.  This is used to include
10111 the language-specific files before any third-party macros.
10113 @end table
10115 @cindex @file{autom4te.cfg}
10116 As an example, if Autoconf is installed in its default location,
10117 @file{/usr/local}, the command @samp{autom4te -l m4sugar foo.m4} is
10118 strictly equivalent to the command:
10120 @example
10121 autom4te --prepend-include /usr/local/share/autoconf \
10122   m4sugar/m4sugar.m4f --warnings syntax foo.m4
10123 @end example
10125 @noindent
10126 Recursive expansion applies here: the command @samp{autom4te -l m4sh foo.m4}
10127 is the same as @samp{autom4te --language M4sugar m4sugar/m4sh.m4f
10128 foo.m4}, i.e.:
10130 @example
10131 autom4te --prepend-include /usr/local/share/autoconf \
10132   m4sugar/m4sugar.m4f m4sugar/m4sh.m4f --mode 777 foo.m4
10133 @end example
10135 @noindent
10136 The definition of the languages is stored in @file{autom4te.cfg}.
10138 @node Customizing autom4te
10139 @subsection Customizing @command{autom4te}
10141 One can customize @command{autom4te} via @file{~/.autom4te.cfg} (i.e.,
10142 as found in the user home directory), and @file{./.autom4te.cfg} (i.e.,
10143 as found in the directory from which @command{autom4te} is run).  The
10144 order is first reading @file{autom4te.cfg}, then @file{~/.autom4te.cfg},
10145 then @file{./.autom4te.cfg}, and finally the command line arguments.
10147 In these text files, comments are introduced with @code{#}, and empty
10148 lines are ignored.  Customization is performed on a per-language basis,
10149 wrapped in between a @samp{begin-language: "@var{language}"},
10150 @samp{end-language: "@var{language}"} pair.
10152 Customizing a language stands for appending options (@pxref{autom4te
10153 Invocation}) to the current definition of the language.  Options, and
10154 more generally arguments, are introduced by @samp{args:
10155 @var{arguments}}.  You may use the traditional shell syntax to quote the
10156 @var{arguments}.
10158 As an example, to disable Autoconf caches (@file{autom4te.cache})
10159 globally, include the following lines in @file{~/.autom4te.cfg}:
10161 @verbatim
10162 ## ------------------ ##
10163 ## User Preferences.  ##
10164 ## ------------------ ##
10166 begin-language: "Autoconf-without-aclocal-m4"
10167 args: --no-cache
10168 end-language: "Autoconf-without-aclocal-m4"
10169 @end verbatim
10172 @node Programming in M4sugar
10173 @section Programming in M4sugar
10175 @cindex M4sugar
10176 M4 by itself provides only a small, but sufficient, set of all-purpose
10177 macros.  M4sugar introduces additional generic macros.  Its name was
10178 coined by Lars J. Aas: ``Readability And Greater Understanding Stands 4
10179 M4sugar''.
10181 M4sugar reserves the macro namespace @samp{^_m4_} for internal use, and
10182 the macro namespace @samp{^m4_} for M4sugar macros.  You should not
10183 define your own macros into these namespaces.
10185 @menu
10186 * Redefined M4 Macros::         M4 builtins changed in M4sugar
10187 * Diagnostic Macros::           Diagnostic messages from M4sugar
10188 * Diversion support::           Diversions in M4sugar
10189 * Conditional constructs::      Conditions in M4
10190 * Looping constructs::          Iteration in M4
10191 * Evaluation Macros::           More quotation and evaluation control
10192 * Text processing Macros::      String manipulation in M4
10193 * Number processing Macros::    Arithmetic computation in M4
10194 * Forbidden Patterns::          Catching unexpanded macros
10195 @end menu
10197 @node Redefined M4 Macros
10198 @subsection Redefined M4 Macros
10200 @msindex{builtin}
10201 @msindex{changecom}
10202 @msindex{changequote}
10203 @msindex{debugfile}
10204 @msindex{debugmode}
10205 @msindex{decr}
10206 @msindex{define}
10207 @msindex{divnum}
10208 @msindex{dumpdef}
10209 @msindex{errprint}
10210 @msindex{esyscmd}
10211 @msindex{eval}
10212 @msindex{format}
10213 @msindex{ifdef}
10214 @msindex{incr}
10215 @msindex{index}
10216 @msindex{indir}
10217 @msindex{len}
10218 @msindex{pushdef}
10219 @msindex{shift}
10220 @msindex{substr}
10221 @msindex{syscmd}
10222 @msindex{sysval}
10223 @msindex{traceoff}
10224 @msindex{traceon}
10225 @msindex{translit}
10226 With a few exceptions, all the M4 native macros are moved in the
10227 @samp{m4_} pseudo-namespace, e.g., M4sugar renames @code{define} as
10228 @code{m4_define} etc.
10230 The list of macros unchanged from M4, except for their name, is:
10231 @itemize @minus
10232 @item m4_builtin
10233 @item m4_changecom
10234 @item m4_changequote
10235 @item m4_debugfile
10236 @item m4_debugmode
10237 @item m4_decr
10238 @item m4_define
10239 @item m4_divnum
10240 @item m4_dumpdef
10241 @item m4_errprint
10242 @item m4_esyscmd
10243 @item m4_eval
10244 @item m4_format
10245 @item m4_ifdef
10246 @item m4_incr
10247 @item m4_index
10248 @item m4_indir
10249 @item m4_len
10250 @item m4_pushdef
10251 @item m4_shift
10252 @item m4_substr
10253 @item m4_syscmd
10254 @item m4_sysval
10255 @item m4_traceoff
10256 @item m4_traceon
10257 @item m4_translit
10258 @end itemize
10260 Some M4 macros are redefined, and are slightly incompatible with their
10261 native equivalent.
10263 @defmac __file__
10264 @defmacx __line__
10265 @MSindex __file__
10266 @MSindex __line__
10267 All M4 macros starting with @samp{__} retain their original name: for
10268 example, no @code{m4__file__} is defined.
10269 @end defmac
10271 @defmac __oline__
10272 @MSindex __oline__
10273 This is not technically a macro, but a feature of Autom4te.  The
10274 sequence @code{__oline__} can be used similarly to the other m4sugar
10275 location macros, but rather than expanding to the location of the input
10276 file, it is translated to the line number where it appears in the output
10277 file after all other M4 expansions.
10278 @end defmac
10280 @defmac dnl
10281 @MSindex dnl
10282 This macro kept its original name: no @code{m4_dnl} is defined.
10283 @end defmac
10285 @defmac m4_bpatsubst (@var{string}, @var{regexp}, @ovar{replacement})
10286 @msindex{bpatsubst}
10287 This macro corresponds to @code{patsubst}.  The name @code{m4_patsubst}
10288 is kept for future versions of M4sugar, once @acronym{GNU} M4 2.0 is
10289 released and supports extended regular expression syntax.
10290 @end defmac
10292 @defmac m4_bregexp (@var{string}, @var{regexp}, @ovar{replacement})
10293 @msindex{bregexp}
10294 This macro corresponds to @code{regexp}.  The name @code{m4_regexp}
10295 is kept for future versions of M4sugar, once @acronym{GNU} M4 2.0 is
10296 released and supports extended regular expression syntax.
10297 @end defmac
10299 @defmac m4_defn (@var{macro})
10300 @msindex{defn}
10301 Unlike the M4 builtin, this macro fails if @var{macro} is not
10302 defined.  Also, while newer M4 can concatenate multiple definitions,
10303 this version currently only supports a single @var{macro}.  See
10304 @code{m4_undefine}.
10305 @end defmac
10307 @defmac m4_divert (@var{diversion})
10308 @msindex{divert}
10309 M4sugar relies heavily on diversions, so rather than behaving as a
10310 primitive, @code{m4_divert} behaves like:
10311 @example
10312 m4_divert_pop()m4_divert_push([@var{diversion}])
10313 @end example
10314 @noindent
10315 @xref{Diversion support}, for more details about the use of the
10316 diversion stack.
10317 @end defmac
10319 @defmac m4_exit (@var{exit-status})
10320 @msindex{exit}
10321 This macro corresponds to @code{m4exit}.
10322 @end defmac
10324 @defmac m4_if (@var{comment})
10325 @defmacx m4_if (@var{string-1}, @var{string-2}, @var{equal}, @ovar{not-equal})
10326 @defmacx m4_if (@var{string-1}, @var{string-2}, @var{equal}, @dots{})
10327 @msindex{if}
10328 This macro corresponds to @code{ifelse}.  @var{string-1} and
10329 @var{string-2} are compared literally, so usually one of the two
10330 arguments is passed unquoted.  @xref{Conditional constructs}, for more
10331 conditional idioms.
10332 @end defmac
10334 @defmac m4_include (@var{file})
10335 @defmacx m4_sinclude (@var{file})
10336 @msindex{include}
10337 @msindex{sinclude}
10338 Like the M4 builtins, but warn against multiple inclusions of @var{file}.
10339 @end defmac
10341 @defmac m4_mkstemp (@var{template})
10342 @defmacx m4_maketemp (@var{template})
10343 @msindex{maketemp}
10344 @msindex{mkstemp}
10345 Posix requires @code{maketemp} to replace the trailing @samp{X}
10346 characters in @var{template} with the process id, without regards to the
10347 existence of a file by that name, but this a security hole.  When this
10348 was pointed out to the Posix folks, they agreed to invent a new macro
10349 @code{mkstemp} that always creates a uniquely named file, but not all
10350 versions of @acronym{GNU} M4 support the new macro.  In M4sugar,
10351 @code{m4_maketemp} and @code{m4_mkstemp} are synonyms for each other,
10352 and both have the secure semantics regardless of which macro the
10353 underlying M4 provides.
10354 @end defmac
10356 @defmac m4_popdef (@var{macro})
10357 @msindex{popdef}
10358 Unlike the M4 builtin, this macro fails if @var{macro} is not
10359 defined.  Also, while newer M4 can pop multiple definitions at once,
10360 this version currently only supports a single @var{macro}.  See
10361 @code{m4_undefine}.
10362 @end defmac
10364 @defmac m4_undefine (@var{macro})
10365 @msindex{undefine}
10366 Unlike the M4 builtin, this macro fails if @var{macro} is not
10367 defined.  Also, while newer M4 can undefine multiple definitions at
10368 once, this version currently only supports a single @var{macro}.  Use
10370 @example
10371 m4_ifdef([@var{macro}], [m4_undefine([@var{macro}])])
10372 @end example
10374 @noindent
10375 to recover the behavior of the builtin.
10376 @end defmac
10378 @defmac m4_undivert (@var{diversion})
10379 @msindex{undivert}
10380 Unlike the M4 builtin, only one diversion can be undiverted per
10381 invocation.  Also, since the M4sugar diversion stack prefers named
10382 diversions, the use of @code{m4_undivert} to include files is risky.
10383 @xref{Diversion support}, for more details about the use of the
10384 diversion stack.
10385 @end defmac
10387 @defmac m4_wrap (@var{text})
10388 @defmacx m4_wrap_lifo (@var{text})
10389 @msindex{wrap}
10390 @msindex{wrap_lifo}
10391 These macros correspond to @code{m4wrap}.  Posix requires arguments of
10392 multiple wrap calls to be reprocessed at @acronym{EOF} in the same order
10393 as the original calls (first-in, first-out).  @acronym{GNU} M4 versions
10394 through 1.4.10, however, reprocess them in reverse order (last-in,
10395 first-out).  Both orders are useful, therefore, you can rely on
10396 @code{m4_wrap} to provide FIFO semantics and @code{m4_wrap_lifo} for
10397 LIFO semantics, regardless of the underlying @acronym{GNU} M4 version.
10399 Unlike the @acronym{GNU} M4 builtin, these macros only recognize one
10400 argument, and avoid token pasting between consecutive invocations.  On
10401 the other hand, nested calls to @code{m4_wrap} from within wrapped text
10402 work just as in the builtin.
10403 @end defmac
10406 @node Diagnostic Macros
10407 @subsection Diagnostic messages from M4sugar
10408 @cindex Messages, from @command{M4sugar}
10410 When macros statically diagnose abnormal situations, benign or fatal,
10411 they should report them using these macros.  For issuing dynamic issues,
10412 i.e., when @command{configure} is run, see @ref{Printing Messages}.
10414 @defmac m4_assert (@var{expression}, @dvar{exit-status, 1})
10415 @msindex{assert}
10416 Assert that the arithmetic @var{expression} evaluates to non-zero.
10417 Otherwise, issue a fatal error, and exit @command{autom4te} with
10418 @var{exit-status}.
10419 @end defmac
10421 @defmac m4_errprintn (@var{message})
10422 @msindex{errprintn}
10423 Similar to the builtin @code{m4_errprint}, except that a newline is
10424 guaranteed after @var{message}.
10425 @end defmac
10427 @anchor{m4_fatal}
10428 @defmac m4_fatal (@var{message})
10429 @msindex{fatal}
10430 Report a severe error @var{message} prefixed with the current location,
10431 and have @command{autom4te} die.
10432 @end defmac
10434 @defmac m4_location
10435 @msindex{location}
10436 Useful as a prefix in a message line.  Short for:
10437 @example
10438 __file__:__line__
10439 @end example
10440 @end defmac
10442 @anchor{m4_warn}
10443 @defmac m4_warn (@var{category}, @var{message})
10444 @msindex{warn}
10445 Report @var{message} as a warning (or as an error if requested by the
10446 user) if warnings of the @var{category} are turned on.  If the message
10447 is emitted, it is prefixed with the current location, and followed by a
10448 call trace of all macros defined via @code{AC_DEFUN} used to get to the
10449 current expansion.  You are encouraged to use standard categories, which
10450 currently include:
10452 @table @samp
10453 @item all
10454 messages that don't fall into one of the following categories.  Use of an
10455 empty @var{category} is equivalent.
10457 @item cross
10458 related to cross compilation issues.
10460 @item obsolete
10461 use of an obsolete construct.
10463 @item syntax
10464 dubious syntactic constructs, incorrectly ordered macro calls.
10465 @end table
10466 @end defmac
10469 @node Diversion support
10470 @subsection Diversion support
10472 M4sugar makes heavy use of diversions, because it is often the case that
10473 text that must appear early in the output is not discovered until late
10474 in the input.  Additionally, some of the topological sorting algorithms
10475 used in resolving macro dependencies use diversions.  Therefore, most
10476 macros should not need to change diversions directly, but rather rely on
10477 higher-level M4sugar macros to manage diversions transparently.
10479 To make diversion management easier, M4sugar uses the concept of named
10480 diversions.  Rather than using diversion numbers directly, it is nicer
10481 to associate a name with each diversion; the diversion number associated
10482 with a particular diversion name is an implementation detail, so you
10483 should only use diversion names.  In general, you should not output text
10484 to a named diversion until after calling the appropriate initialization
10485 routine for your language (@code{m4_init}, @code{AS_INIT},
10486 @code{AT_INIT}, @dots{}), although there are some exceptions documented
10487 below.
10489 M4sugar defines two named diversions.
10490 @table @code
10491 @item KILL
10492 Text written to this diversion is discarded.  This is the default
10493 diversion once M4sugar is initialized.
10494 @item GROW
10495 This diversion is used behind the scenes by topological sorting macros,
10496 such as @code{AC_REQUIRE}.
10497 @end table
10499 M4sh adds several more named diversions.
10500 @table @code
10501 @item BINSH
10502 This diversion is reserved for the @samp{#!} interpreter line.
10503 @item HEADER-REVISION
10504 This diversion holds text from @code{AC_REVISION}.
10505 @item HEADER-COMMENT
10506 This diversion holds comments about the purpose of a file.
10507 @item HEADER-COPYRIGHT
10508 This diversion is managed by @code{AC_COPYRIGHT}.
10509 @item M4SH-SANITIZE
10510 This diversion contains M4sh sanitization code, used to ensure M4sh is
10511 executing in a reasonable shell environment.
10512 @item M4SH-INIT
10513 This diversion contains M4sh initialization code, initializing variables
10514 that are required by other M4sh macros.
10515 @item BODY
10516 This diversion contains the body of the shell code, and is the default
10517 diversion once M4sh is initialized.
10518 @end table
10520 Autotest inherits diversions from M4sh, and changes the default
10521 diversion from @code{BODY} back to @code{KILL}.  It also adds several
10522 more named diversions, with the following subset designed for developer
10523 use.
10524 @table @code
10525 @item PREPARE_TESTS
10526 This diversion contains initialization sequences which are executed
10527 after @file{atconfig} and @file{atlocal}, and after all command line
10528 arguments have been parsed, but prior to running any tests.  It can be
10529 used to set up state that is required across all tests.  This diversion
10530 will work even before @code{AT_INIT}.
10531 @end table
10533 For now, the named diversions of Autoconf and Autoheader, and the
10534 remaining diversions of Autotest, are not documented.  In other words,
10535 intentionally outputting text into an undocumented diversion is subject
10536 to breakage in a future release of Autoconf.
10538 @defmac m4_divert_once (@var{diversion}, @ovar{content})
10539 @msindex{divert_once}
10540 Similar to @code{m4_divert_text}, except that @var{content} is only
10541 output to @var{diversion} if this is the first time that
10542 @code{m4_divert_once} has been called with its particular arguments.
10543 @end defmac
10545 @defmac m4_divert_pop (@ovar{diversion})
10546 @msindex{divert_pop}
10547 If provided, check that the current diversion is indeed @var{diversion}.
10548 Then change to the diversion located earlier on the stack, giving an
10549 error if an attempt is made to pop beyond the initial m4sugar diversion
10550 of @code{KILL}.
10551 @end defmac
10553 @defmac m4_divert_push (@var{diversion})
10554 @msindex{divert_push}
10555 Remember the former diversion on the diversion stack, and output
10556 subsequent text into @var{diversion}.  M4sugar maintains a diversion
10557 stack, and issues an error if there is not a matching pop for every
10558 push.
10559 @end defmac
10561 @defmac m4_divert_text (@var{diversion}, @ovar{content})
10562 @msindex{divert_text}
10563 Output @var{content} and a newline into @var{diversion}, without
10564 affecting the current diversion.  Shorthand for:
10565 @example
10566 m4_divert_push([@var{diversion}])@var{content}
10567 m4_divert_pop([@var{diversion}])dnl
10568 @end example
10569 @end defmac
10571 @defmac m4_init
10572 @msindex{init}
10573 Initialize the M4sugar environment, setting up the default named
10574 diversion to be @code{KILL}.
10575 @end defmac
10577 @node Conditional constructs
10578 @subsection Conditional constructs
10580 The following macros provide additional conditional contructs, as
10581 convenience wrappers around @code{m4_if}.
10583 @defmac m4_bmatch (@var{string}, @var{regex-1}, @var{value-1}, @
10584   @ovar{regex-2}, @ovar{value-2}, @dots{}, @ovar{default})
10585 @msindex{bmatch}
10586 The string @var{string} is repeatedly compared against a series of
10587 @var{regex} arguments; if a match is found, the expansion is the
10588 corresponding @var{value}, otherwise, the macro moves on to the next
10589 @var{regex}.  If no @var{regex} match, then the result is the optional
10590 @var{default}, or nothing.
10591 @end defmac
10593 @defmac m4_bpatsubsts (@var{string}, @var{regex-1}, @var{subst-1}, @
10594   @ovar{regex-2}, @ovar{subst-2}, @dots{})
10595 @msindex{bpatsubsts}
10596 The string @var{string} is altered by @var{regex-1} and @var{subst-1},
10597 as if by:
10598 @example
10599 m4_bpatsubst([[@var{string}]], [@var{regex}], [@var{subst}])
10600 @end example
10602 @noindent
10603 The result of the substitution is then passed through the next set of
10604 @var{regex} and @var{subst}, and so forth.  An empty @var{subst} implies
10605 deletion of any matched portions in the current string.  Note that this
10606 macro over-quotes @var{string}; this behavior is intentional, so that
10607 the result of each step of the recursion remains as a quoted string.
10608 However, it means that anchors (@samp{^} and @samp{$} in the @var{regex}
10609 will line up with the extra quotations, and not the characters of the
10610 original string.
10611 @end defmac
10613 @defmac m4_case (@var{string}, @var{value-1}, @var{if-value-1}, @
10614   @ovar{value-2}, @ovar{if-value-2}, @dots{}, @ovar{default})
10615 @msindex{case}
10616 Test @var{string} against multiple @var{value} possibilities, resulting
10617 in the first @var{if-value} for a match, or in the optional
10618 @var{default}.  This is shorthand for:
10619 @example
10620 m4_if([@var{string}], [@var{value-1}], [@var{if-value-1}],
10621       [@var{string}], [@var{value-2}], [@var{if-value-2}], @dots{},
10622       [@var{default}])
10623 @end example
10624 @end defmac
10626 @defmac m4_cond (@var{test-1}, @var{value-1}, @var{if-value-1}, @
10627   @ovar{test-2}, @ovar{value-2}, @ovar{if-value-2}, @dots{}, @ovar{default})
10628 @msindex{cond}
10629 This macro was introduced in Autoconf 2.62.  Similar to @code{m4_if},
10630 except that each @var{test} is expanded only when it is encountered.
10631 This is useful for short-circuiting expensive tests; while @code{m4_if}
10632 requires all its strings to be expanded up front before doing
10633 comparisons, @code{m4_cond} only expands a @var{test} when all earlier
10634 tests have failed.
10636 For an example, these two sequences give the same result, but in the
10637 case where @samp{$1} does not contain a backslash, the @code{m4_cond}
10638 version only expands @code{m4_index} once, instead of five times, for
10639 faster computation if this is a common case for @samp{$1}.  Notice that
10640 every third argument is unquoted for @code{m4_if}, and quoted for
10641 @code{m4_cond}:
10643 @example
10644 m4_if(m4_index([$1], [\]), [-1], [$2],
10645       m4_eval(m4_index([$1], [\\]) >= 0), [1], [$2],
10646       m4_eval(m4_index([$1], [\$]) >= 0), [1], [$2],
10647       m4_eval(m4_index([$1], [\`]) >= 0), [1], [$3],
10648       m4_eval(m4_index([$1], [\"]) >= 0), [1], [$3],
10649       [$2])
10650 m4_cond([m4_index([$1], [\])], [-1], [$2],
10651         [m4_eval(m4_index([$1], [\\]) >= 0)], [1], [$2],
10652         [m4_eval(m4_index([$1], [\$]) >= 0)], [1], [$2],
10653         [m4_eval(m4_index([$1], [\`]) >= 0)], [1], [$3],
10654         [m4_eval(m4_index([$1], [\"]) >= 0)], [1], [$3],
10655         [$2])
10656 @end example
10657 @end defmac
10659 @defmac m4_default (@var{expr-1}, @var{expr-2})
10660 @msindex{default}
10661 If @var{expr-1} is not empty, use it.  Otherwise, expand to
10662 @var{expr-2}.  Useful for providing a fixed default if the expression
10663 that results in @var{expr-1} would otherwise be empty.
10664 @end defmac
10666 @defmac m4_ifndef (@var{macro}, @var{if-not-defined}, @ovar{if-defined})
10667 @msindex{ifndef}
10668 This is shorthand for:
10669 @example
10670 m4_ifdef([@var{macro}], [@var{if-defined}], [@var{if-not-defined}])
10671 @end example
10672 @end defmac
10674 @defmac m4_ifset (@var{macro}, @ovar{if-true}, @ovar{if-false})
10675 @msindex{ifset}
10676 If @var{macro} is undefined, or is defined as the empty string, expand
10677 to @var{if-false}.  Otherwise, expands to @var{if-true}.  Similar to:
10678 @example
10679 m4_ifval(m4_defn([@var{macro}]), [@var{if-true}], [@var{if-false}])
10680 @end example
10681 @noindent
10682 except that it is not an error if @var{macro} is undefined.
10683 @end defmac
10685 @defmac m4_ifval (@var{cond}, @ovar{if-true}, @ovar{if-false})
10686 @msindex{ifval}
10687 Expands to @var{if-true} if @var{cond} is not empty, otherwise to
10688 @var{if-false}.  This is shorthand for:
10689 @example
10690 m4_if([@var{cond}], [], [@var{if-true}], [@var{if-false}])
10691 @end example
10692 @end defmac
10694 @defmac m4_ifvaln (@var{cond}, @ovar{if-true}, @ovar{if-false})
10695 @msindex{ifvaln}
10696 Similar to @code{m4_ifval}, except guarantee that a newline is present
10697 after any non-empty expansion.
10698 @end defmac
10700 @defmac m4_n (@var{text})
10701 @msindex{n}
10702 Expand to @var{text}, and add a newline if @var{text} is not empty.
10703 @end defmac
10706 @node Looping constructs
10707 @subsection Looping constructs
10709 The following macros are useful in implementing recursive algorithms in
10710 M4, including loop operations.  An M4 list is formed by quoting a list
10711 of quoted elements; generally the lists are comma-separated, although
10712 @code{m4_foreach_w} is whitespace-separated.  For example, the list
10713 @samp{[[a], [b,c]]} contains two elements: @samp{[a]} and @samp{[b,c]}.
10714 It is common to see lists with unquoted elements when those elements are
10715 not likely to be macro names, as in @samp{[fputc_unlocked,
10716 fgetc_unlocked]}.
10718 @defmac m4_car (@var{list})
10719 @msindex{car}
10720 Expands to the quoted first element of the comma-separated quoted
10721 @var{list}.  Often used with @code{m4_cdr} to recursively iterate
10722 through a list.  Generally, when using quoted lists of quoted elements,
10723 @code{m4_car} should be called without any extra quotes.
10724 @end defmac
10726 @defmac m4_cdr (@var{list})
10727 @msindex{cdr}
10728 Expands to a quoted list of all but the first element of the
10729 comma-separated quoted @var{list}, or the empty string if @var{list} had
10730 only one element.  Generally, when using quoted lists of quoted
10731 elements, @code{m4_cdr} should be called without any extra quotes.
10733 For example, this is a simple implementation of @code{m4_map}; note how
10734 each iteration checks for the end of recursion, then merely applies the
10735 first argument to the first element of the list, then repeats with the
10736 rest of the list.  (The actual implementation in M4sugar is a bit more
10737 involved, to gain some speed and share code with @code{m4_map_sep}).
10738 @example
10739 m4_define([m4_map], [m4_ifval([$2],
10740   [m4_apply([$1], m4_car($2))[]$0([$1], m4_cdr($2))])])dnl
10741 m4_map([ m4_eval], [[[1]], [[1+1]], [[10],[16]]])
10742 @result{} 1 2 a
10743 @end example
10744 @end defmac
10746 @defmac m4_for (@var{var}, @var{first}, @var{last}, @ovar{step}, @
10747   @var{expression})
10748 @msindex{for}
10749 Loop over the numeric values between @var{first} and @var{last}
10750 including bounds by increments of @var{step}.  For each iteration,
10751 expand @var{expression} with the numeric value assigned to @var{var}.
10752 If @var{step} is omitted, it defaults to @samp{1} or @samp{-1} depending
10753 on the order of the limits.  If given, @var{step} has to match this
10754 order.
10755 @end defmac
10757 @defmac m4_foreach (@var{var}, @var{list}, @var{expression})
10758 @msindex{foreach}
10759 Loop over the comma-separated M4 list @var{list}, assigning each value
10760 to @var{var}, and expand @var{expression}.  The following example
10761 outputs two lines:
10763 @example
10764 m4_foreach([myvar], [[foo], [bar, baz]],
10765            [echo myvar
10766 ])dnl
10767 @result{}echo foo
10768 @result{}echo bar, baz
10769 @end example
10770 @end defmac
10772 @anchor{m4_foreach_w}
10773 @defmac m4_foreach_w (@var{var}, @var{list}, @var{expression})
10774 @msindex{foreach_w}
10775 Loop over the white-space-separated list @var{list}, assigning each value
10776 to @var{var}, and expand @var{expression}.
10778 The deprecated macro @code{AC_FOREACH} is an alias of
10779 @code{m4_foreach_w}.
10780 @end defmac
10782 @defmac m4_map (@var{macro}, @var{list})
10783 @defmacx m4_map_sep (@var{macro}, @var{separator}, @var{list})
10784 Loop over the comma separated quoted list of argument descriptions in
10785 @var{list}, and invoke @var{macro} with the arguments.  An argument
10786 description is in turn a comma-separated quoted list of quoted elements,
10787 suitable for @code{m4_apply}, making it possible to invoke @var{macro}
10788 without arguments if an argument description is empty.
10789 @code{m4_map_sep} additionally outputs @var{separator} between macro
10790 invocations, with no additional expansion of the separator.
10791 @example
10792 m4_map([m4_count], [])
10793 @result{}
10794 m4_map([ m4_count], [[],
10795                      [[1]],
10796                      [[1], [2]]])
10797 @result{} 0 1 2
10798 m4_map_sep([m4_eval], [,], [[[1+2]],
10799                             [[10], [16]]])
10800 @result{}3,a
10801 @end example
10802 @end defmac
10804 @defmac m4_shiftn (@var{count}, @dots{})
10805 @defmacx m4_shift2 (@dots{})
10806 @defmacx m4_shift3 (@dots{})
10807 @msindex{shift2}
10808 @msindex{shift3}
10809 @msindex{shiftn}
10810 @code{m4_shiftn} performs @var{count} iterations of @code{m4_shift},
10811 along with validation that enough arguments were passed in to match the
10812 shift count, and that the count is positive.  @code{m4_shift2} and
10813 @code{m4_shift3} are specializations
10814 of @code{m4_shiftn}, introduced in Autoconf 2.62, and are more efficient
10815 for two and three shifts, respectively.
10816 @end defmac
10819 @node Evaluation Macros
10820 @subsection Evaluation Macros
10822 The following macros give some control over the order of the evaluation
10823 by adding or removing levels of quotes.
10825 @defmac m4_apply (@var{macro}, @var{list})
10826 @msindex{apply}
10827 Apply the elements of the quoted, comma-separated @var{list} as the
10828 arguments to @var{macro}.  If @var{list} is empty, invoke @var{macro}
10829 without arguments.  Note the difference between @code{m4_indir}, which
10830 expects its first argument to be a macro name but can use names that are
10831 otherwise invalid, and @code{m4_apply}, where @var{macro} can contain
10832 other text, but must end in a valid macro name.
10833 @example
10834 m4_apply([m4_count], [])
10835 @result{}0
10836 m4_apply([m4_count], [[]])
10837 @result{}1
10838 m4_apply([m4_count], [[1], [2]])
10839 @result{}2
10840 m4_apply([m4_join], [[|], [1], [2]])
10841 @result{}1|2
10842 @end example
10843 @end defmac
10845 @defmac m4_count (@var{arg}, @dots{})
10846 @msindex{count}
10847 This macro returns the decimal count of the number of arguments it was
10848 passed.
10849 @end defmac
10851 @defmac m4_do (@var{arg}, @dots{})
10852 @msindex{do}
10853 This macro loops over its arguments and expands each @var{arg} in
10854 sequence.  Its main use is for readability; it allows the use of
10855 indentation and fewer @code{dnl} to result in the same expansion.
10856 @end defmac
10858 @defmac m4_dquote (@var{arg}, @dots{})
10859 @msindex{dquote}
10860 Return the arguments as a quoted list of quoted arguments.
10861 Conveniently, if there is just one @var{arg}, this effectively adds a
10862 level of quoting.
10863 @end defmac
10865 @defmac m4_dquote_elt (@var{arg}, @dots{})
10866 @msindex{dquote_elt}
10867 Return the arguments as a series of double-quoted arguments.  Whereas
10868 @code{m4_dquote} returns a single argument, @code{m4_dquote_elt} returns
10869 as many arguments as it was passed.
10870 @end defmac
10872 @defmac m4_echo (@var{arg}, @dots{})
10873 @msindex{echo}
10874 Return the arguments, with the same level of quoting.  Other than
10875 discarding whitespace after unquoted commas, this macro is a no-op.
10876 @end defmac
10878 @defmac m4_expand (@var{arg})
10879 @msindex{expand}
10880 Return the expansion of @var{arg} as a quoted string.  Whereas
10881 @code{m4_quote} is designed to collect expanded text into a single
10882 argument, @code{m4_expand} is designed to perform one level of expansion
10883 on quoted text.  The distinction is in the treatment of whitespace
10884 following a comma in the original @var{arg}.  Any time multiple
10885 arguments are collected into one with @code{m4_quote}, the M4 argument
10886 collection rules discard the whitespace.  However, with @code{m4_expand},
10887 whitespace is preserved, even after the expansion of macros contained in
10888 @var{arg}.
10890 Note that @code{m4_expand} cannot parse everything.  The expansion of
10891 @var{arg} must not contain unbalanced quotes (although quadrigraphs can
10892 get around this), nor unbalanced parentheses (portable shell @code{case}
10893 statements are a major culprit here, but creative shell comments can get
10894 around this).
10896 @example
10897 m4_define([active], [ACT, IVE])dnl
10898 m4_define([active2], [[ACT, IVE]])dnl
10899 m4_quote(active, active)
10900 @result{}ACT,IVE,ACT,IVE
10901 m4_expand([active, active])
10902 @result{}ACT, IVE, ACT, IVE
10903 m4_quote(active2, active2)
10904 @result{}ACT, IVE,ACT, IVE
10905 m4_expand([active2, active2])
10906 @result{}ACT, IVE, ACT, IVE
10907 @end example
10908 @end defmac
10910 @defmac m4_ignore (@dots{})
10911 @msindex{ignore}
10912 This macro was introduced in Autoconf 2.62.  Expands to nothing,
10913 ignoring all of its arguments.  By itself, this isn't very useful.
10914 However, it can be used to conditionally ignore an arbitrary number of
10915 arguments, by deciding which macro name to apply to a list of arguments.
10916 @example
10917 dnl foo outputs a message only if [debug] is defined.
10918 m4_define([foo],
10919 [m4_ifdef([debug],[AC_MSG_NOTICE],[m4_ignore])([debug message])])
10920 @end example
10922 Note that for earlier versions of Autoconf, the macro @code{__gnu__} can
10923 serve the same purpose, although it is less readable.
10924 @end defmac
10926 @defmac m4_make_list (@var{arg}, @dots{})
10927 @msindex{make_list}
10928 This macro exists to aid debugging of M4sugar algorithms.  Its net
10929 effect is similar to @code{m4_dquote}---it produces a quoted list of
10930 quoted arguments, for each @var{arg}.  The difference is that this
10931 version uses a comma-newline separator instead of just comma, to improve
10932 readability of the list; with the result that it is less efficient than
10933 @code{m4_dquote}.
10934 @example
10935 m4_define([zero],[0])m4_define([one],[1])m4_define([two],[2])dnl
10936 m4_dquote(zero, [one], [[two]])
10937 @result{}[0],[one],[[two]]
10938 m4_make_list(zero, [one], [[two]])
10939 @result{}[0],
10940 @result{}[one],
10941 @result{}[[two]]
10942 m4_foreach([number], m4_dquote(zero, [one], [[two]]), [ number])
10943 @result{} 0 1 two
10944 m4_foreach([number], m4_make_list(zero, [one], [[two]]), [ number])
10945 @result{} 0 1 two
10946 @end example
10947 @end defmac
10949 @c m4_noquote is too dangerous to document - it invokes macros that
10950 @c probably rely on @samp{[]} nested quoting for proper operation.  The
10951 @c user should generally prefer m4_unquote instead.
10953 @defmac m4_quote (@var{arg}, @dots{})
10954 @msindex{quote}
10955 Return the arguments as a single entity, i.e., wrap them into a pair of
10956 quotes.  This effectively collapses multiple arguments into one,
10957 although it loses whitespace after unquoted commas in the process.
10958 @end defmac
10960 @defmac m4_unquote (@var{arg}, @dots{})
10961 @msindex{unquote}
10962 This macro was introduced in Autoconf 2.62.  Expand each argument,
10963 separated by commas.  For a single @var{arg}, this effectively removes a
10964 layer of quoting, and @code{m4_unquote([@var{arg}])} is more efficient
10965 than the equivalent @code{m4_do([@var{arg}])}.  For multiple arguments,
10966 this results in an unquoted list of expansions.  This is commonly used
10967 with @code{m4_split}, in order to convert a single quoted list into a
10968 series of quoted elements.
10969 @end defmac
10971 The following example aims at emphasizing the difference between several
10972 scenarios: not using these macros, using @code{m4_defn}, using
10973 @code{m4_quote}, using @code{m4_dquote}, and using @code{m4_expand}.
10975 @example
10976 $ @kbd{cat example.m4}
10977 dnl Overquote, so that quotes are visible.
10978 m4_define([show], [$[]1 = [$1], $[]@@ = [$@@]])
10979 m4_define([a], [A])
10980 m4_define([mkargs], [1, 2[,] 3])
10981 m4_define([arg1], [[$1]])
10982 m4_divert([0])dnl
10983 show(a, b)
10984 show([a, b])
10985 show(m4_quote(a, b))
10986 show(m4_dquote(a, b))
10987 show(m4_expand([a, b]))
10989 arg1(mkargs)
10990 arg1([mkargs])
10991 arg1(m4_defn([mkargs]))
10992 arg1(m4_quote(mkargs))
10993 arg1(m4_dquote(mkargs))
10994 arg1(m4_expand([mkargs]))
10995 $ @kbd{autom4te -l m4sugar example.m4}
10996 $1 = A, $@@ = [A],[b]
10997 $1 = a, b, $@@ = [a, b]
10998 $1 = A,b, $@@ = [A,b]
10999 $1 = [A],[b], $@@ = [[A],[b]]
11000 $1 = A, b, $@@ = [A, b]
11003 mkargs
11004 1, 2[,] 3
11005 1,2, 3
11006 [1],[2, 3]
11007 1, 2, 3
11008 @end example
11011 @node Text processing Macros
11012 @subsection String manipulation in M4
11014 The following macros may be used to manipulate strings in M4.  Many of
11015 the macros in this section intentionally result in quoted strings as
11016 output, rather than subjecting the arguments to further expansions.  As
11017 a result, if you are manipulating text that contains active M4
11018 characters, the arguments are passed with single quoting rather than
11019 double.
11021 @defmac m4_append (@var{macro-name}, @var{string}, @ovar{separator})
11022 @defmacx m4_append_uniq (@var{macro-name}, @var{string}, @ovar{separator} @
11023   @ovar{if-uniq}, @ovar{if-duplicate})
11024 @msindex{append}
11025 @msindex{append_uniq}
11026 Redefine @var{macro-name} to its former contents with @var{separator}
11027 and @var{string} added at the end.  If @var{macro-name} was undefined
11028 before (but not if it was defined but empty), then no @var{separator} is
11029 added.  As of Autoconf 2.62, neither @var{string} nor @var{separator}
11030 are expanded during this macro; instead, they are expanded when
11031 @var{macro-name} is invoked.
11033 @code{m4_append} can be used to grow strings, and @code{m4_append_uniq}
11034 to grow strings without duplicating substrings.  Additionally,
11035 @code{m4_append_uniq} takes two optional parameters as of Autoconf 2.62;
11036 @var{if-uniq} is expanded if @var{string} was appended, and
11037 @var{if-duplicate} is expanded if @var{string} was already present.
11038 Also, @code{m4_append_uniq} warns if @var{separator} is not empty, but
11039 occurs within @var{string}, since that can lead to duplicates.
11041 @example
11042 m4_define([active], [ACTIVE])dnl
11043 m4_append([sentence], [This is an])dnl
11044 m4_append([sentence], [ active ])dnl
11045 m4_append([sentence], [symbol.])dnl
11046 sentence
11047 @result{}This is an ACTIVE symbol.
11048 m4_undefine([active])dnl
11049 @result{}This is an active symbol.
11050 m4_append_uniq([list], [one], [, ], [new], [existing])
11051 @result{}new
11052 m4_append_uniq([list], [one], [, ], [new], [existing])
11053 @result{}existing
11054 m4_append_uniq([list], [two], [, ], [new], [existing])
11055 @result{}new
11056 m4_append_uniq([list], [three], [, ], [new], [existing])
11057 @result{}new
11058 m4_append_uniq([list], [two], [, ], [new], [existing])
11059 @result{}existing
11060 list
11061 @result{}one, two, three
11062 m4_dquote(list)
11063 @result{}[one],[two],[three]
11064 m4_append([list2], [one], [[, ]])dnl
11065 m4_append_uniq([list2], [two], [[, ]])dnl
11066 m4_append([list2], [three], [[, ]])dnl
11067 list2
11068 @result{}one, two, three
11069 m4_dquote(list2)
11070 @result{}[one, two, three]
11071 @end example
11072 @end defmac
11074 @defmac m4_append_uniq_w (@var{macro-name}, @var{strings})
11075 @msindex{append_uniq_w}
11076 This macro was introduced in Autoconf 2.62.  It is similar to
11077 @code{m4_append_uniq}, but treats @var{strings} as a whitespace
11078 separated list of words to append, and only appends unique words.
11079 @var{macro-name} is updated with a single space between new words.
11080 @example
11081 m4_append_uniq_w([numbers], [1 1 2])dnl
11082 m4_append_uniq_w([numbers], [ 2 3 ])dnl
11083 numbers
11084 @result{}1 2 3
11085 @end example
11086 @end defmac
11088 @defmac m4_combine (@ovar{separator}, @var{prefix-list}, @ovar{infix}, @
11089   @var{suffix-1}, @ovar{suffix-2}, @dots{})
11090 @msindex{combine}
11091 This macro produces a quoted string containing the pairwise combination
11092 of every element of the quoted, comma-separated @var{prefix-list}, and
11093 every element from the @var{suffix} arguments.  Each pairwise
11094 combination is joined with @var{infix} in the middle, and successive
11095 pairs are joined by @var{separator}.  No expansion occurs on any of the
11096 arguments.  No output occurs if either the @var{prefix} or @var{suffix}
11097 list is empty, but the lists can contain empty elements.
11098 @example
11099 m4_define([a], [oops])dnl
11100 m4_combine([, ], [[a], [b], [c]], [-], [1], [2], [3])
11101 @result{}a-1, a-2, a-3, b-1, b-2, b-3, c-1, c-2, c-3
11102 m4_combine([, ], [[a], [b]], [-])
11103 @result{}
11104 m4_combine([, ], [[a], [b]], [-], [])
11105 @result{}a-, b-
11106 m4_combine([, ], [], [-], [1], [2])
11107 @result{}
11108 m4_combine([, ], [[]], [-], [1], [2])
11109 @result{}-1, -2
11110 @end example
11111 @end defmac
11113 @defmac m4_flatten (@var{string})
11114 @msindex{flatten}
11115 Flatten @var{string} into a single line.  Delete all backslash-newline
11116 pairs, and replace all remaining newlines with a space.  The result is
11117 still a quoted string.
11118 @end defmac
11120 @defmac m4_join (@ovar{separator}, @var{args}@dots{})
11121 @msindex{join}
11122 Concatenate each @var{arg}, separated by @var{separator}, with the
11123 exception that no back-to-back separators are issued for empty
11124 arguments.  The result is a quoted string.
11125 @example
11126 m4_define([active], [ACTIVE])dnl
11127 m4_join([|], [one], [], [active], [two])
11128 @result{}one|active|two
11129 @end example
11131 Note that if all you intend to do is join @var{args} with commas between
11132 them, to form a quoted list suitable for @code{m4_foreach}, it is more
11133 efficient to use @code{m4_dquote}.
11134 @end defmac
11136 @defmac m4_newline
11137 @msindex{newline}
11138 This macro was introduced in Autoconf 2.62, and expands to a newline.
11139 It is primarily useful for maintaining macro formatting, and ensuring
11140 that M4 does not discard leading whitespace during argument collection.
11141 @end defmac
11143 @defmac m4_normalize (@var{string})
11144 @msindex{normalize}
11145 Remove leading and trailing spaces and tabs, sequences of
11146 backslash-then-newline, and replace multiple spaces, tabs, and newlines
11147 with a single space.  This is a combination of @code{m4_flatten} and
11148 @code{m4_strip}.
11149 @end defmac
11151 @defmac m4_re_escape (@var{string})
11152 @msindex{re_escape}
11153 Backslash-escape all characters in @var{string} that are active in
11154 regexps.
11155 @end defmac
11157 @defmac m4_split (@var{string}, @dvar{regexp, [\t ]+})
11158 @msindex{split}
11159 Split @var{string} into an M4 list of elements quoted by @samp{[} and
11160 @samp{]}, while keeping white space at the beginning and at the end.
11161 If @var{regexp} is given, use it instead of @samp{[\t ]+} for splitting.
11162 If @var{string} is empty, the result is an empty list.
11163 @end defmac
11165 @defmac m4_strip (@var{string})
11166 @msindex{strip}
11167 Strip whitespace from @var{string}.  Sequences of spaces and tabs are
11168 reduced to a single space, then leading and trailing spaces are removed.
11169 The result is still a quoted string.  Note that this does not interfere
11170 with newlines; if you want newlines stripped as well, consider
11171 @code{m4_flatten}, or do it all at once with @code{m4_normalize}.
11172 @end defmac
11174 @defmac m4_text_box (@var{message}, @dvar{frame, -})
11175 @msindex{text_box}
11176 Add a text box around @var{message}, using @var{frame} as the border
11177 character above and below the message.  The frame correctly accounts for
11178 the subsequent expansion of @var{message}.  For example:
11179 @example
11180 m4_define([macro], [abc])dnl
11181 m4_text_box([macro])
11182 @result{}## --- ##
11183 @result{}## abc ##
11184 @result{}## --- ##
11185 @end example
11186 @end defmac
11188 @defmac m4_text_wrap (@var{string}, @ovar{prefix}, @
11189   @dvar{prefix1, @var{prefix}}, @dvar{width, 79})
11190 @msindex{text_wrap}
11191 Break @var{string} into a series of whitespace-separated words, then
11192 output those words separated by spaces, and wrapping lines any time the
11193 output would exceed @var{width} columns.  If given, @var{prefix1} begins
11194 the first line, and @var{prefix} begins all wrapped lines.  If
11195 @var{prefix1} is longer than @var{prefix}, then the first line consists
11196 of just @var{prefix1}.  If @var{prefix} is longer than @var{prefix1},
11197 padding is inserted so that the first word of @var{string} begins at the
11198 same indentation as all wrapped lines.  Note that using literal tab
11199 characters in any of the arguments will interfere with the calculation
11200 of width.  No expansions occur on @var{prefix}, @var{prefix1}, or the
11201 words of @var{string}, although quadrigraphs are recognized.
11203 For some examples:
11204 @example
11205 m4_text_wrap([Short string */], [   ], [/* ], [20])
11206 @result{}/* Short string */
11207 m4_text_wrap([Much longer string */], [   ], [/* ], [20])
11208 @result{}/* Much longer
11209 @result{}   string */
11210 m4_text_wrap([Short doc.], [          ], [  --short ], [30])
11211 @result{}  --short Short doc.
11212 m4_text_wrap([Short doc.], [          ], [  --too-wide ], [30])
11213 @result{}  --too-wide
11214 @result{}          Short doc.
11215 m4_text_wrap([Super long documentation.], [     ],
11216              [  --too-wide ], 30)
11217 @result{}  --too-wide
11218 @result{}     Super long
11219 @result{}     documentation.
11220 @end example
11221 @end defmac
11223 @defmac m4_tolower (@var{string})
11224 @defmacx m4_toupper (@var{string})
11225 @msindex{tolower}
11226 @msindex{toupper}
11227 Return @var{string} with letters converted to upper or lower case,
11228 respectively.
11229 @end defmac
11231 @node Number processing Macros
11232 @subsection Arithmetic computation in M4
11234 The following macros facilitate integer arithmetic operations.
11235 Where a parameter is documented as taking an arithmetic expression, you
11236 can use anything that can be parsed by @code{m4_eval}.
11238 @defmac m4_cmp (@var{expr-1}, @var{expr-2})
11239 @msindex{cmp}
11240 Compare the arithmetic expressions @var{expr-1} and @var{expr-2}, and
11241 expand to @samp{-1} if @var{expr-1} is smaller, @samp{0} if they are
11242 equal, and @samp{1} if @var{expr-1} is larger.
11243 @end defmac
11245 @defmac m4_list_cmp (@var{list-1}, @var{list-2})
11246 @msindex{list_cmp}
11247 Compare the two M4 lists consisting of comma-separated arithmetic
11248 expressions, left to right.  Expand to @samp{-1} for the first element
11249 pairing where the value from @var{list-1} is smaller, @samp{1} where the
11250 value from @var{list-2} is smaller, or @samp{0} if both lists have the
11251 same values.  If one list is shorter than the other, the remaining
11252 elements of the longer list are compared against zero.
11253 @example
11254 m4_list_cmp([1, 0],       [1])
11255 @result{}0
11256 m4_list_cmp([1, [1 * 0]], [1, 0])
11257 @result{}0
11258 m4_list_cmp([1, 2],       [1, 0])
11259 @result{}1
11260 m4_list_cmp([1, [1+1], 3],[1, 2])
11261 @result{}1
11262 m4_list_cmp([1, 2, -3],   [1, 2])
11263 @result{}-1
11264 m4_list_cmp([1, 0],       [1, 2])
11265 @result{}-1
11266 m4_list_cmp([1],          [1, 2])
11267 @result{}-1
11268 @end example
11269 @end defmac
11271 @defmac m4_max (@var{arg}, @dots{})
11272 @msindex{max}
11273 This macro was introduced in Autoconf 2.62.  Expand to the decimal value
11274 of the maximum arithmetic expression among all the arguments.
11275 @end defmac
11277 @defmac m4_min (@var{arg}, @dots{})
11278 @msindex{min}
11279 This macro was introduced in Autoconf 2.62.  Expand to the decimal value
11280 of the minimum arithmetic expression among all the arguments.
11281 @end defmac
11283 @defmac m4_sign (@var{expr})
11284 @msindex{sign}
11285 Expand to @samp{-1} if the arithmetic expression @var{expr} is negative,
11286 @samp{1} if it is positive, and @samp{0} if it is zero.
11287 @end defmac
11289 @anchor{m4_version_compare}
11290 @defmac m4_version_compare (@var{version-1}, @var{version-2})
11291 @msindex{version_compare}
11292 This macro was introduced in Autoconf 2.53, but had a number of
11293 usability limitations that were not lifted until Autoconf 2.62.  Compare
11294 the version strings @var{version-1} and @var{version-2}, and expand to
11295 @samp{-1} if @var{version-1} is smaller, @samp{0} if they are the same,
11296 or @samp{1} @var{version-2} is smaller.  Version strings must be a list
11297 of elements separated by @samp{.}, @samp{,} or @samp{-}, where each
11298 element is a number along with optional case-insensitive letters
11299 designating beta releases.  The comparison stops at the leftmost element
11300 that contains a difference, although a 0 element compares equal to a
11301 missing element.
11303 It is permissible to include commit identifiers in @var{version}, such
11304 as an abbreviated SHA1 of the commit, provided there is still a
11305 monotonically increasing prefix to allow for accurate version-based
11306 comparisons.  For example, this paragraph was written when the
11307 development snapshot of autoconf claimed to be at version
11308 @samp{2.61a-248-dc51}, or 248 commits after the 2.61a release, with an
11309 abbreviated commit identification of @samp{dc51}.
11311 @example
11312 m4_version_compare([1.1], [2.0])
11313 @result{}-1
11314 m4_version_compare([2.0b], [2.0a])
11315 @result{}1
11316 m4_version_compare([1.1.1], [1.1.1a])
11317 @result{}-1
11318 m4_version_compare([1.2], [1.1.1a])
11319 @result{}1
11320 m4_version_compare([1.0], [1])
11321 @result{}0
11322 m4_version_compare([1.1pre], [1.1PRE])
11323 @result{}0
11324 m4_version_compare([1.1a], [1,10])
11325 @result{}-1
11326 m4_version_compare([2.61a], [2.61a-248-dc51])
11327 @result{}-1
11328 m4_version_compare([2.61b], [2.61a-248-dc51])
11329 @result{}1
11330 @end example
11331 @end defmac
11334 @node Forbidden Patterns
11335 @subsection Forbidden Patterns
11336 @cindex Forbidden patterns
11337 @cindex Patterns, forbidden
11339 M4sugar provides a means to define suspicious patterns, patterns
11340 describing tokens which should not be found in the output.  For
11341 instance, if an Autoconf @file{configure} script includes tokens such as
11342 @samp{AC_DEFINE}, or @samp{dnl}, then most probably something went
11343 wrong (typically a macro was not evaluated because of overquotation).
11345 M4sugar forbids all the tokens matching @samp{^_?m4_} and @samp{^dnl$}.
11346 Additional layers, such as M4sh and Autoconf, add additional forbidden
11347 patterns to the list.
11349 @defmac m4_pattern_forbid (@var{pattern})
11350 @msindex{pattern_forbid}
11351 Declare that no token matching @var{pattern} must be found in the output.
11352 Comments are not checked; this can be a problem if, for instance, you
11353 have some macro left unexpanded after an @samp{#include}.  No consensus
11354 is currently found in the Autoconf community, as some people consider it
11355 should be valid to name macros in comments (which doesn't make sense to
11356 the authors of this documentation: input, such as macros, should be
11357 documented by @samp{dnl} comments; reserving @samp{#}-comments to
11358 document the output).
11359 @end defmac
11361 Of course, you might encounter exceptions to these generic rules, for
11362 instance you might have to refer to @samp{$m4_flags}.
11364 @defmac m4_pattern_allow (@var{pattern})
11365 @msindex{pattern_allow}
11366 Any token matching @var{pattern} is allowed, including if it matches an
11367 @code{m4_pattern_forbid} pattern.
11368 @end defmac
11370 @node Programming in M4sh
11371 @section Programming in M4sh
11373 @c FIXME: Eventually will become a chapter, as it is not related to
11374 @c programming in M4 per se.
11376 M4sh, pronounced ``mash'', is aiming at producing portable Bourne shell
11377 scripts.  This name was coined by Lars J. Aas, who notes that,
11378 according to the Webster's Revised Unabridged Dictionary (1913):
11380 @quotation
11381 Mash \Mash\, n.  [Akin to G. meisch, maisch, meische, maische, mash,
11382 wash, and prob.@: to AS. miscian to mix.  See ``Mix''.]
11384 @enumerate 1
11385 @item
11386 A mass of mixed ingredients reduced to a soft pulpy state by beating or
11387 pressure@enddots{}
11389 @item
11390 A mixture of meal or bran and water fed to animals.
11392 @item
11393 A mess; trouble.  [Obs.] --Beau.@: & Fl.
11394 @end enumerate
11395 @end quotation
11398 For the time being, it is not mature enough to be widely used.
11400 M4sh reserves the M4 macro namespace @samp{^_AS_} for internal use, and
11401 the namespace @samp{^AS_} for M4sh macros.  It also reserves the shell
11402 and environment variable namespace @samp{^as_}, and the here-doc
11403 delimiter namespace @samp{^_AS[A-Z]} in the output file.  You should not
11404 define your own macros or output shell code that conflicts with these
11405 namespaces.
11407 M4sh provides portable alternatives for some common shell constructs
11408 that unfortunately are not portable in practice.
11410 @c Deprecated, to be replaced by a better API
11411 @ignore
11412 @defmac AS_BASENAME (@var{file-name})
11413 @asindex{BASENAME}
11414 Output the non-directory portion of @var{file-name}.  For example,
11415 if @code{$file} is @samp{/one/two/three}, the command
11416 @code{base=`AS_BASENAME(["$file"])`} sets @code{base} to @samp{three}.
11417 @end defmac
11418 @end ignore
11420 @defmac AS_BOURNE_COMPATIBLE
11421 @asindex{BOURNE_COMPATIBLE}
11422 Set up the shell to be more compatible with the Bourne shell as
11423 standardized by Posix, if possible.  This may involve setting
11424 environment variables, or setting options, or similar
11425 implementation-specific actions.
11426 @end defmac
11428 @defmac AS_CASE (@var{word}, @ovar{pattern1}, @ovar{if-matched1}, @
11429   @dots{}, @ovar{default})
11430 @asindex{CASE}
11431 Expand into a shell @samp{case} statement, where @var{word} is matched
11432 against one or more patterns.  @var{if-matched} is run if the
11433 corresponding pattern matched @var{word}, else @var{default} is run.
11434 @end defmac
11436 @defmac AS_DIRNAME (@var{file-name})
11437 @asindex{DIRNAME}
11438 Output the directory portion of @var{file-name}.  For example,
11439 if @code{$file} is @samp{/one/two/three}, the command
11440 @code{dir=`AS_DIRNAME(["$file"])`} sets @code{dir} to @samp{/one/two}.
11441 @end defmac
11443 @defmac AS_IF (@var{test1}, @ovar{run-if-true1}, @dots{}, @ovar{run-if-false})
11444 @asindex{IF}
11445 Run shell code @var{test1}.  If @var{test1} exits with a zero status then
11446 run shell code @var{run-if-true1}, else examine further tests.  If no test
11447 exits with a zero status, run shell code @var{run-if-false}, with
11448 simplifications if either @var{run-if-true1} or @var{run-if-false1}
11449 is empty.  For example,
11451 @example
11452 AS_IF([test "$foo" = yes], [HANDLE_FOO([yes])],
11453       [test "$foo" != no], [HANDLE_FOO([maybe])],
11454       [echo foo not specified])
11455 @end example
11457 @noindent
11458 ensures any required macros of @code{HANDLE_FOO}
11459 are expanded before the first test.
11460 @end defmac
11462 @defmac AS_INIT
11463 @asindex{INIT}
11464 Initialize the M4sh environment.  This macro calls @code{m4_init}, then
11465 outputs the @code{#! /bin/sh} line, a notice about where the output was
11466 generated from, and code to sanitize the environment for the rest of the
11467 script.  Finally, it changes the current diversion to @code{BODY}.
11468 @end defmac
11470 @defmac AS_MKDIR_P (@var{file-name})
11471 @asindex{MKDIR_P}
11472 Make the directory @var{file-name}, including intervening directories
11473 as necessary.  This is equivalent to @samp{mkdir -p @var{file-name}},
11474 except that it is portable to older versions of @command{mkdir} that
11475 lack support for the @option{-p} option.  Also, @code{AS_MKDIR_P}
11476 succeeds if @var{file-name} is a symbolic link to an existing directory,
11477 even though Posix is unclear whether @samp{mkdir -p} should
11478 succeed in that case.  If creation of @var{file-name} fails, exit the
11479 script.
11481 Also see the @code{AC_PROG_MKDIR_P} macro (@pxref{Particular Programs}).
11482 @end defmac
11484 @defmac AS_SHELL_SANITIZE
11485 @asindex{SHELL_SANITIZE}
11486 Initialize the shell suitably for @code{configure} scripts.  This has
11487 the effect of @code{AS_BOURNE_COMPATIBLE}, and sets some other
11488 environment variables for predictable results from configuration tests.
11489 For example, it sets @env{LC_ALL} to change to the default C locale.
11490 @xref{Special Shell Variables}.
11491 @end defmac
11493 @defmac AS_TR_CPP (@var{expression})
11494 @asindex{TR_CPP}
11495 Transform @var{expression} into a valid right-hand side for a C @code{#define}.
11496 For example:
11498 @example
11499 # This outputs "#define HAVE_CHAR_P 1".
11500 type="char *"
11501 echo "#define AS_TR_CPP([HAVE_$type]) 1"
11502 @end example
11503 @end defmac
11505 @defmac AS_TR_SH (@var{expression})
11506 @asindex{TR_SH}
11507 Transform @var{expression} into a valid shell variable name.  For example:
11509 @example
11510 # This outputs "Have it!".
11511 header="sys/some file.h"
11512 AS_TR_SH([HAVE_$header])=yes
11513 if test "$HAVE_sys_some_file_h" = yes; then echo "Have it!"; fi
11514 @end example
11515 @end defmac
11517 @defmac AS_SET_CATFILE (@var{var}, @var{dir}, @var{file})
11518 @asindex{SET_CATFILE}
11519 Set the shell variable @var{var} to @var{dir}/@var{file}, but
11520 optimizing the common cases (@var{dir} or @var{file} is @samp{.},
11521 @var{file} is absolute, etc.).
11522 @end defmac
11525 @node File Descriptor Macros
11526 @section File Descriptor Macros
11527 @cindex input
11528 @cindex standard input
11529 @cindex file descriptors
11530 @cindex descriptors
11531 @cindex low-level output
11532 @cindex output, low-level
11534 The following macros define file descriptors used to output messages
11535 (or input values) from @file{configure} scripts.
11536 For example:
11538 @example
11539 echo "$wombats found" >&AS_MESSAGE_LOG_FD
11540 echo 'Enter desired kangaroo count:' >&AS_MESSAGE_FD
11541 read kangaroos <&AS_ORIGINAL_STDIN_FD`
11542 @end example
11544 @noindent
11545 However doing so is seldom needed, because Autoconf provides higher
11546 level macros as described below.
11548 @defmac AS_MESSAGE_FD
11549 @asindex{MESSAGE_FD}
11550 The file descriptor for @samp{checking for...}  messages and results.
11551 Normally this directs messages to the standard output, however when
11552 @command{configure} is run with the @option{-q} option, messages sent to
11553 @code{AS_MESSAGE_FD} are discarded.
11555 If you want to display some messages, consider using one of the printing
11556 macros (@pxref{Printing Messages}) instead.  Copies of messages output
11557 via these macros are also recorded in @file{config.log}.
11558 @end defmac
11560 @defmac AS_MESSAGE_LOG_FD
11561 @asindex{MESSAGE_LOG_FD}
11563 The file descriptor for messages logged to @file{config.log}.  Macros
11564 that run tools, like @code{AC_COMPILE_IFELSE} (@pxref{Running the
11565 Compiler}), redirect all output to this descriptor.  You may want to do
11566 so if you develop such a low-level macro.
11567 @end defmac
11569 @defmac AS_ORIGINAL_STDIN_FD
11570 @asindex{ORIGINAL_STDIN_FD}
11571 The file descriptor for the original standard input.
11573 When @command{configure} runs, it may accidentally execute an
11574 interactive command that has the same name as the non-interactive meant
11575 to be used or checked.  If the standard input was the terminal, such
11576 interactive programs would cause @command{configure} to stop, pending
11577 some user input.  Therefore @command{configure} redirects its standard
11578 input from @file{/dev/null} during its initialization.  This is not
11579 normally a problem, since @command{configure} normally does not need
11580 user input.
11582 In the extreme case where your @file{configure} script really needs to
11583 obtain some values from the original standard input, you can read them
11584 explicitly from @code{AS_ORIGINAL_STDIN_FD}.
11585 @end defmac
11588 @c =================================================== Writing Autoconf Macros.
11590 @node Writing Autoconf Macros
11591 @chapter Writing Autoconf Macros
11593 When you write a feature test that could be applicable to more than one
11594 software package, the best thing to do is encapsulate it in a new macro.
11595 Here are some instructions and guidelines for writing Autoconf macros.
11597 @menu
11598 * Macro Definitions::           Basic format of an Autoconf macro
11599 * Macro Names::                 What to call your new macros
11600 * Reporting Messages::          Notifying @command{autoconf} users
11601 * Dependencies Between Macros::  What to do when macros depend on other macros
11602 * Obsoleting Macros::           Warning about old ways of doing things
11603 * Coding Style::                Writing Autoconf macros @`a la Autoconf
11604 @end menu
11606 @node Macro Definitions
11607 @section Macro Definitions
11609 @acindex{DEFUN}
11610 Autoconf macros are defined using the @code{AC_DEFUN} macro, which is
11611 similar to the M4 builtin @code{m4_define} macro.  In addition to
11612 defining a macro, @code{AC_DEFUN} adds to it some code that is used to
11613 constrain the order in which macros are called (@pxref{Prerequisite
11614 Macros}).
11616 An Autoconf macro definition looks like this:
11618 @example
11619 AC_DEFUN(@var{macro-name}, @var{macro-body})
11620 @end example
11622 You can refer to any arguments passed to the macro as @samp{$1},
11623 @samp{$2}, etc.  @xref{Definitions, , How to define new macros, m4.info,
11624 @acronym{GNU} M4}, for more complete information on writing M4 macros.
11626 Be sure to properly quote both the @var{macro-body} @emph{and} the
11627 @var{macro-name} to avoid any problems if the macro happens to have
11628 been previously defined.
11630 Each macro should have a header comment that gives its prototype, and a
11631 brief description.  When arguments have default values, display them in
11632 the prototype.  For example:
11634 @example
11635 # AC_MSG_ERROR(ERROR, [EXIT-STATUS = 1])
11636 # --------------------------------------
11637 m4_define([AC_MSG_ERROR],
11638   [@{ AS_MESSAGE([error: $1], [2])
11639      exit m4_default([$2], [1]); @}])
11640 @end example
11642 Comments about the macro should be left in the header comment.  Most
11643 other comments make their way into @file{configure}, so just keep
11644 using @samp{#} to introduce comments.
11646 @cindex @code{dnl}
11647 If you have some special comments about pure M4 code, comments
11648 that make no sense in @file{configure} and in the header comment, then
11649 use the builtin @code{dnl}: it causes M4 to discard the text
11650 through the next newline.
11652 Keep in mind that @code{dnl} is rarely needed to introduce comments;
11653 @code{dnl} is more useful to get rid of the newlines following macros
11654 that produce no output, such as @code{AC_REQUIRE}.
11657 @node Macro Names
11658 @section Macro Names
11660 All of the public Autoconf macros have all-uppercase names in the
11661 namespace @samp{^AC_} to prevent them from accidentally conflicting with
11662 other text; Autoconf also reserves the namespace @samp{^_AC_} for
11663 internal macros.  All shell variables that they use for internal
11664 purposes have mostly-lowercase names starting with @samp{ac_}.  Autoconf
11665 also uses here-doc delimiters in the namespace @samp{^_AC[A-Z]}.  During
11666 @command{configure}, files produced by Autoconf make heavy use of the
11667 file system namespace @samp{^conf}.
11669 Since Autoconf is built on top of M4sugar (@pxref{Programming in
11670 M4sugar}) and M4sh (@pxref{Programming in M4sh}), you must also be aware
11671 of those namespaces (@samp{^_?\(m4\|AS\)_}).  And since
11672 @file{configure.ac} is also designed to be scanned by Autoheader,
11673 Autoscan, Autoupdate, and Automake, you should be aware of the
11674 @samp{^_?A[HNUM]_} namespaces.  In general, you @emph{should not use}
11675 the namespace of a package that does not own the macro or shell code you
11676 are writing.
11678 To ensure that your macros don't conflict with present or future
11679 Autoconf macros, you should prefix your own macro names and any shell
11680 variables they use with some other sequence.  Possibilities include your
11681 initials, or an abbreviation for the name of your organization or
11682 software package.  Historically, people have not always followed the
11683 rule of using a namespace appropriate for their package, and this has
11684 made it difficult for determining the origin of a macro (and where to
11685 report bugs about that macro), as well as difficult for the true
11686 namespace owner to add new macros without interference from pre-existing
11687 uses of third-party macros.  Perhaps the best example of this confusion
11688 is the @code{AM_GNU_GETTEXT} macro, which belongs, not to Automake, but
11689 to Gettext.
11691 Most of the Autoconf macros' names follow a structured naming convention
11692 that indicates the kind of feature check by the name.  The macro names
11693 consist of several words, separated by underscores, going from most
11694 general to most specific.  The names of their cache variables use the
11695 same convention (@pxref{Cache Variable Names}, for more information on
11696 them).
11698 The first word of the name after the namepace initials (such as
11699 @samp{AC_}) usually tells the category
11700 of the feature being tested.  Here are the categories used in Autoconf for
11701 specific test macros, the kind of macro that you are more likely to
11702 write.  They are also used for cache variables, in all-lowercase.  Use
11703 them where applicable; where they're not, invent your own categories.
11705 @table @code
11706 @item C
11707 C language builtin features.
11708 @item DECL
11709 Declarations of C variables in header files.
11710 @item FUNC
11711 Functions in libraries.
11712 @item GROUP
11713 Posix group owners of files.
11714 @item HEADER
11715 Header files.
11716 @item LIB
11717 C libraries.
11718 @item PROG
11719 The base names of programs.
11720 @item MEMBER
11721 Members of aggregates.
11722 @item SYS
11723 Operating system features.
11724 @item TYPE
11725 C builtin or declared types.
11726 @item VAR
11727 C variables in libraries.
11728 @end table
11730 After the category comes the name of the particular feature being
11731 tested.  Any further words in the macro name indicate particular aspects
11732 of the feature.  For example, @code{AC_PROG_CC_STDC} checks whether the
11733 C compiler supports @acronym{ISO} Standard C.
11735 An internal macro should have a name that starts with an underscore;
11736 Autoconf internals should therefore start with @samp{_AC_}.
11737 Additionally, a macro that is an internal subroutine of another macro
11738 should have a name that starts with an underscore and the name of that
11739 other macro, followed by one or more words saying what the internal
11740 macro does.  For example, @code{AC_PATH_X} has internal macros
11741 @code{_AC_PATH_X_XMKMF} and @code{_AC_PATH_X_DIRECT}.
11743 @node Reporting Messages
11744 @section Reporting Messages
11745 @cindex Messages, from @command{autoconf}
11747 When macros statically diagnose abnormal situations, benign or fatal, it
11748 is possible to make @command{autoconf} detect the problem, and refuse to
11749 create @file{configure} in the case of an error.  The macros in this
11750 section are considered obsolescent, and new code should use M4sugar
11751 macros for this purpose, see @ref{Diagnostic Macros}.
11753 On the other hand, it is possible to want to detect errors when
11754 @command{configure} is run, which are dependent on the environment of
11755 the user rather than the maintainer.  For dynamic diagnostics, see
11756 @ref{Printing Messages}.
11758 @defmac AC_DIAGNOSE (@var{category}, @var{message})
11759 @acindex{DIAGNOSE}
11760 Report @var{message} as a warning (or as an error if requested by the
11761 user) if warnings of the @var{category} are turned on.  This macro is
11762 obsolescent; you are encouraged to use:
11763 @example
11764 m4_warn([@var{category}], [@var{message}])
11765 @end example
11766 @noindent
11767 instead.  @xref{m4_warn}, for more details, including valid
11768 @var{category} names.
11769 @end defmac
11771 @defmac AC_WARNING (@var{message})
11772 @acindex{WARNING}
11773 Report @var{message} as a syntax warning.  This macro is obsolescent;
11774 you are encouraged to use:
11775 @example
11776 m4_warn([syntax], [@var{message}])
11777 @end example
11778 @noindent
11779 instead.  @xref{m4_warn}, for more details, as well as better
11780 finer-grained categories of warnings (not all problems have to do with
11781 syntax).
11782 @end defmac
11784 @defmac AC_FATAL (@var{message})
11785 @acindex{FATAL}
11786 Report a severe error @var{message}, and have @command{autoconf} die.
11787 This macro is obsolescent; you are encouraged to use:
11788 @example
11789 m4_fatal([@var{message}])
11790 @end example
11791 @noindent
11792 instead.  @xref{m4_fatal}, for more details.
11793 @end defmac
11795 When the user runs @samp{autoconf -W error}, warnings from
11796 @code{m4_warn} (including those issued through @code{AC_DIAGNOSE} and
11797 @code{AC_WARNING}) are reported as errors, see @ref{autoconf Invocation}.
11799 @node Dependencies Between Macros
11800 @section Dependencies Between Macros
11801 @cindex Dependencies between macros
11803 Some Autoconf macros depend on other macros having been called first in
11804 order to work correctly.  Autoconf provides a way to ensure that certain
11805 macros are called if needed and a way to warn the user if macros are
11806 called in an order that might cause incorrect operation.
11808 @menu
11809 * Prerequisite Macros::         Ensuring required information
11810 * Suggested Ordering::          Warning about possible ordering problems
11811 * One-Shot Macros::             Ensuring a macro is called only once
11812 @end menu
11814 @node Prerequisite Macros
11815 @subsection Prerequisite Macros
11816 @cindex Prerequisite macros
11817 @cindex Macros, prerequisites
11819 A macro that you write might need to use values that have previously
11820 been computed by other macros.  For example, @code{AC_DECL_YYTEXT}
11821 examines the output of @code{flex} or @code{lex}, so it depends on
11822 @code{AC_PROG_LEX} having been called first to set the shell variable
11823 @code{LEX}.
11825 Rather than forcing the user of the macros to keep track of the
11826 dependencies between them, you can use the @code{AC_REQUIRE} macro to do
11827 it automatically.  @code{AC_REQUIRE} can ensure that a macro is only
11828 called if it is needed, and only called once.
11830 @defmac AC_REQUIRE (@var{macro-name})
11831 @acindex{REQUIRE}
11832 If the M4 macro @var{macro-name} has not already been called, call it
11833 (without any arguments).  Make sure to quote @var{macro-name} with
11834 square brackets.  @var{macro-name} must have been defined using
11835 @code{AC_DEFUN} or else contain a call to @code{AC_PROVIDE} to indicate
11836 that it has been called.
11838 @code{AC_REQUIRE} must be used inside a macro defined by @code{AC_DEFUN}; it
11839 must not be called from the top level.
11840 @end defmac
11842 @code{AC_REQUIRE} is often misunderstood.  It really implements
11843 dependencies between macros in the sense that if one macro depends upon
11844 another, the latter is expanded @emph{before} the body of the
11845 former.  To be more precise, the required macro is expanded before
11846 the outermost defined macro in the current expansion stack.
11847 In particular, @samp{AC_REQUIRE([FOO])} is not replaced with the body of
11848 @code{FOO}.  For instance, this definition of macros:
11850 @example
11851 @group
11852 AC_DEFUN([TRAVOLTA],
11853 [test "$body_temperature_in_celsius" -gt "38" &&
11854   dance_floor=occupied])
11855 AC_DEFUN([NEWTON_JOHN],
11856 [test "$hair_style" = "curly" &&
11857   dance_floor=occupied])
11858 @end group
11860 @group
11861 AC_DEFUN([RESERVE_DANCE_FLOOR],
11862 [if date | grep '^Sat.*pm' >/dev/null 2>&1; then
11863   AC_REQUIRE([TRAVOLTA])
11864   AC_REQUIRE([NEWTON_JOHN])
11865 fi])
11866 @end group
11867 @end example
11869 @noindent
11870 with this @file{configure.ac}
11872 @example
11873 AC_INIT([Dance Manager], [1.0], [bug-dance@@example.org])
11874 RESERVE_DANCE_FLOOR
11875 if test "$dance_floor" = occupied; then
11876   AC_MSG_ERROR([cannot pick up here, let's move])
11878 @end example
11880 @noindent
11881 does not leave you with a better chance to meet a kindred soul at
11882 other times than Saturday night since it expands into:
11884 @example
11885 @group
11886 test "$body_temperature_in_Celsius" -gt "38" &&
11887   dance_floor=occupied
11888 test "$hair_style" = "curly" &&
11889   dance_floor=occupied
11891 if date | grep '^Sat.*pm' >/dev/null 2>&1; then
11895 @end group
11896 @end example
11898 This behavior was chosen on purpose: (i) it prevents messages in
11899 required macros from interrupting the messages in the requiring macros;
11900 (ii) it avoids bad surprises when shell conditionals are used, as in:
11902 @example
11903 @group
11904 if @dots{}; then
11905   AC_REQUIRE([SOME_CHECK])
11907 @dots{}
11908 SOME_CHECK
11909 @end group
11910 @end example
11912 The helper macros @code{AS_IF} and @code{AS_CASE} may be used to
11913 enforce expansion of required macros outside of shell conditional
11914 constructs.  You are furthermore encouraged to put all @code{AC_REQUIRE} calls
11915 at the beginning of a macro.  You can use @code{dnl} to avoid the empty
11916 lines they leave.
11918 @node Suggested Ordering
11919 @subsection Suggested Ordering
11920 @cindex Macros, ordering
11921 @cindex Ordering macros
11923 Some macros should be run before another macro if both are called, but
11924 neither @emph{requires} that the other be called.  For example, a macro
11925 that changes the behavior of the C compiler should be called before any
11926 macros that run the C compiler.  Many of these dependencies are noted in
11927 the documentation.
11929 Autoconf provides the @code{AC_BEFORE} macro to warn users when macros
11930 with this kind of dependency appear out of order in a
11931 @file{configure.ac} file.  The warning occurs when creating
11932 @command{configure} from @file{configure.ac}, not when running
11933 @command{configure}.
11935 For example, @code{AC_PROG_CPP} checks whether the C compiler
11936 can run the C preprocessor when given the @option{-E} option.  It should
11937 therefore be called after any macros that change which C compiler is
11938 being used, such as @code{AC_PROG_CC}.  So @code{AC_PROG_CC} contains:
11940 @example
11941 AC_BEFORE([$0], [AC_PROG_CPP])dnl
11942 @end example
11944 @noindent
11945 This warns the user if a call to @code{AC_PROG_CPP} has already occurred
11946 when @code{AC_PROG_CC} is called.
11948 @defmac AC_BEFORE (@var{this-macro-name}, @var{called-macro-name})
11949 @acindex{BEFORE}
11950 Make M4 print a warning message to the standard error output if
11951 @var{called-macro-name} has already been called.  @var{this-macro-name}
11952 should be the name of the macro that is calling @code{AC_BEFORE}.  The
11953 macro @var{called-macro-name} must have been defined using
11954 @code{AC_DEFUN} or else contain a call to @code{AC_PROVIDE} to indicate
11955 that it has been called.
11956 @end defmac
11958 @node One-Shot Macros
11959 @subsection One-Shot Macros
11960 @cindex One-shot macros
11961 @cindex Macros, called once
11963 Some macros should be called only once, either because calling them
11964 multiple time is unsafe, or because it is bad style.  For instance
11965 Autoconf ensures that @code{AC_CANONICAL_BUILD} and cousins
11966 (@pxref{Canonicalizing}) are evaluated only once, because it makes no
11967 sense to run these expensive checks more than once.  Such one-shot
11968 macros can be defined using @code{AC_DEFUN_ONCE}.
11970 @defmac AC_DEFUN_ONCE (@var{macro-name}, @var{macro-body})
11971 @acindex{DEFUN_ONCE}
11973 Declare macro @var{macro-name} like @code{AC_DEFUN} would (@pxref{Macro
11974 Definitions}), and emit a warning any time the macro is called more than
11975 once.
11976 @end defmac
11978 Obviously it is not sensible to evaluate a macro defined by
11979 @code{AC_DEFUN_ONCE} in a macro defined by @code{AC_DEFUN}.
11980 Most of the time you want to use @code{AC_REQUIRE} (@pxref{Prerequisite
11981 Macros}).
11983 @node Obsoleting Macros
11984 @section Obsoleting Macros
11985 @cindex Obsoleting macros
11986 @cindex Macros, obsoleting
11988 Configuration and portability technology has evolved over the years.
11989 Often better ways of solving a particular problem are developed, or
11990 ad-hoc approaches are systematized.  This process has occurred in many
11991 parts of Autoconf.  One result is that some of the macros are now
11992 considered @dfn{obsolete}; they still work, but are no longer considered
11993 the best thing to do, hence they should be replaced with more modern
11994 macros.  Ideally, @command{autoupdate} should replace the old macro calls
11995 with their modern implementation.
11997 Autoconf provides a simple means to obsolete a macro.
11999 @anchor{AU_DEFUN}
12000 @defmac AU_DEFUN (@var{old-macro}, @var{implementation}, @ovar{message})
12001 @auindex{DEFUN}
12002 Define @var{old-macro} as @var{implementation}.  The only difference
12003 with @code{AC_DEFUN} is that the user is warned that
12004 @var{old-macro} is now obsolete.
12006 If she then uses @command{autoupdate}, the call to @var{old-macro} is
12007 replaced by the modern @var{implementation}.  @var{message} should
12008 include information on what to do after running @command{autoupdate};
12009 @command{autoupdate} prints it as a warning, and includes it
12010 in the updated @file{configure.ac} file.
12012 The details of this macro are hairy: if @command{autoconf} encounters an
12013 @code{AU_DEFUN}ed macro, all macros inside its second argument are expanded
12014 as usual.  However, when @command{autoupdate} is run, only M4 and M4sugar
12015 macros are expanded here, while all other macros are disabled and
12016 appear literally in the updated @file{configure.ac}.
12017 @end defmac
12019 @defmac AU_ALIAS (@var{old-name}, @var{new-name})
12020 @auindex{ALIAS}
12021 Used if the @var{old-name} is to be replaced by a call to @var{new-macro}
12022 with the same parameters.  This happens for example if the macro was renamed.
12023 @end defmac
12025 @node Coding Style
12026 @section Coding Style
12027 @cindex Coding style
12029 The Autoconf macros follow a strict coding style.  You are encouraged to
12030 follow this style, especially if you intend to distribute your macro,
12031 either by contributing it to Autoconf itself, or via other means.
12033 The first requirement is to pay great attention to the quotation.  For
12034 more details, see @ref{Autoconf Language}, and @ref{M4 Quotation}.
12036 Do not try to invent new interfaces.  It is likely that there is a macro
12037 in Autoconf that resembles the macro you are defining: try to stick to
12038 this existing interface (order of arguments, default values, etc.).  We
12039 @emph{are} conscious that some of these interfaces are not perfect;
12040 nevertheless, when harmless, homogeneity should be preferred over
12041 creativity.
12043 Be careful about clashes both between M4 symbols and between shell
12044 variables.
12046 If you stick to the suggested M4 naming scheme (@pxref{Macro Names}),
12047 you are unlikely to generate conflicts.  Nevertheless, when you need to
12048 set a special value, @emph{avoid using a regular macro name}; rather,
12049 use an ``impossible'' name.  For instance, up to version 2.13, the macro
12050 @code{AC_SUBST} used to remember what @var{symbol} macros were already defined
12051 by setting @code{AC_SUBST_@var{symbol}}, which is a regular macro name.
12052 But since there is a macro named @code{AC_SUBST_FILE}, it was just
12053 impossible to @samp{AC_SUBST(FILE)}!  In this case,
12054 @code{AC_SUBST(@var{symbol})} or @code{_AC_SUBST(@var{symbol})} should
12055 have been used (yes, with the parentheses).
12056 @c or better yet, high-level macros such as @code{m4_expand_once}
12058 No Autoconf macro should ever enter the user-variable name space; i.e.,
12059 except for the variables that are the actual result of running the
12060 macro, all shell variables should start with @code{ac_}.  In
12061 addition, small macros or any macro that is likely to be embedded in
12062 other macros should be careful not to use obvious names.
12064 @cindex @code{dnl}
12065 Do not use @code{dnl} to introduce comments: most of the comments you
12066 are likely to write are either header comments which are not output
12067 anyway, or comments that should make their way into @file{configure}.
12068 There are exceptional cases where you do want to comment special M4
12069 constructs, in which case @code{dnl} is right, but keep in mind that it
12070 is unlikely.
12072 M4 ignores the leading blanks and newlines before each argument.
12073 Use this feature to
12074 indent in such a way that arguments are (more or less) aligned with the
12075 opening parenthesis of the macro being called.  For instance, instead of
12077 @example
12078 AC_CACHE_CHECK(for EMX OS/2 environment,
12079 ac_cv_emxos2,
12080 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM(, [return __EMX__;])],
12081 [ac_cv_emxos2=yes], [ac_cv_emxos2=no])])
12082 @end example
12084 @noindent
12085 write
12087 @example
12088 AC_CACHE_CHECK([for EMX OS/2 environment], [ac_cv_emxos2],
12089 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([], [return __EMX__;])],
12090                    [ac_cv_emxos2=yes],
12091                    [ac_cv_emxos2=no])])
12092 @end example
12094 @noindent
12095 or even
12097 @example
12098 AC_CACHE_CHECK([for EMX OS/2 environment],
12099                [ac_cv_emxos2],
12100                [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([],
12101                                                    [return __EMX__;])],
12102                                   [ac_cv_emxos2=yes],
12103                                   [ac_cv_emxos2=no])])
12104 @end example
12106 When using @code{AC_RUN_IFELSE} or any macro that cannot work when
12107 cross-compiling, provide a pessimistic value (typically @samp{no}).
12109 Feel free to use various tricks to prevent auxiliary tools, such as
12110 syntax-highlighting editors, from behaving improperly.  For instance,
12111 instead of:
12113 @example
12114 m4_bpatsubst([$1], [$"])
12115 @end example
12117 @noindent
12120 @example
12121 m4_bpatsubst([$1], [$""])
12122 @end example
12124 @noindent
12125 so that Emacsen do not open an endless ``string'' at the first quote.
12126 For the same reasons, avoid:
12128 @example
12129 test $[#] != 0
12130 @end example
12132 @noindent
12133 and use:
12135 @example
12136 test $[@@%:@@] != 0
12137 @end example
12139 @noindent
12140 Otherwise, the closing bracket would be hidden inside a @samp{#}-comment,
12141 breaking the bracket-matching highlighting from Emacsen.  Note the
12142 preferred style to escape from M4: @samp{$[1]}, @samp{$[@@]}, etc.  Do
12143 not escape when it is unnecessary.  Common examples of useless quotation
12144 are @samp{[$]$1} (write @samp{$$1}), @samp{[$]var} (use @samp{$var}),
12145 etc.  If you add portability issues to the picture, you'll prefer
12146 @samp{$@{1+"$[@@]"@}} to @samp{"[$]@@"}, and you'll prefer do something
12147 better than hacking Autoconf @code{:-)}.
12149 When using @command{sed}, don't use @option{-e} except for indenting
12150 purposes.  With the @code{s} and @code{y} commands, the preferred
12151 separator is @samp{/} unless @samp{/} itself might appear in the pattern
12152 or replacement, in which case you should use @samp{|}, or optionally
12153 @samp{,} if you know the pattern and replacement cannot contain a file
12154 name.  If none of these characters will do, choose a printable character
12155 that cannot appear in the pattern or replacement.  Characters from the
12156 set @samp{"#$&'()*;<=>?`|~} are good choices if the pattern or
12157 replacement might contain a file name, since they have special meaning
12158 to the shell and are less likely to occur in file names.
12160 @xref{Macro Definitions}, for details on how to define a macro.  If a
12161 macro doesn't use @code{AC_REQUIRE}, is expected to never be the object
12162 of an @code{AC_REQUIRE} directive, and macros required by other macros
12163 inside arguments do not need to be expanded before this macro, then
12164 use @code{m4_define}.  In case of doubt, use @code{AC_DEFUN}.
12165 All the @code{AC_REQUIRE} statements should be at the beginning of the
12166 macro, and each statement should be followed by @code{dnl}.
12168 You should not rely on the number of arguments: instead of checking
12169 whether an argument is missing, test that it is not empty.  It provides
12170 both a simpler and a more predictable interface to the user, and saves
12171 room for further arguments.
12173 Unless the macro is short, try to leave the closing @samp{])} at the
12174 beginning of a line, followed by a comment that repeats the name of the
12175 macro being defined.  This introduces an additional newline in
12176 @command{configure}; normally, that is not a problem, but if you want to
12177 remove it you can use @samp{[]dnl} on the last line.  You can similarly
12178 use @samp{[]dnl} after a macro call to remove its newline.  @samp{[]dnl}
12179 is recommended instead of @samp{dnl} to ensure that M4 does not
12180 interpret the @samp{dnl} as being attached to the preceding text or
12181 macro output.  For example, instead of:
12183 @example
12184 AC_DEFUN([AC_PATH_X],
12185 [AC_MSG_CHECKING([for X])
12186 AC_REQUIRE_CPP()
12187 @r{# @dots{}omitted@dots{}}
12188   AC_MSG_RESULT([libraries $x_libraries, headers $x_includes])
12189 fi])
12190 @end example
12192 @noindent
12193 you would write:
12195 @example
12196 AC_DEFUN([AC_PATH_X],
12197 [AC_REQUIRE_CPP()[]dnl
12198 AC_MSG_CHECKING([for X])
12199 @r{# @dots{}omitted@dots{}}
12200   AC_MSG_RESULT([libraries $x_libraries, headers $x_includes])
12201 fi[]dnl
12202 ])# AC_PATH_X
12203 @end example
12205 If the macro is long, try to split it into logical chunks.  Typically,
12206 macros that check for a bug in a function and prepare its
12207 @code{AC_LIBOBJ} replacement should have an auxiliary macro to perform
12208 this setup.  Do not hesitate to introduce auxiliary macros to factor
12209 your code.
12211 In order to highlight the recommended coding style, here is a macro
12212 written the old way:
12214 @example
12215 dnl Check for EMX on OS/2.
12216 dnl _AC_EMXOS2
12217 AC_DEFUN(_AC_EMXOS2,
12218 [AC_CACHE_CHECK(for EMX OS/2 environment, ac_cv_emxos2,
12219 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM(, return __EMX__;)],
12220 ac_cv_emxos2=yes, ac_cv_emxos2=no)])
12221 test "$ac_cv_emxos2" = yes && EMXOS2=yes])
12222 @end example
12224 @noindent
12225 and the new way:
12227 @example
12228 # _AC_EMXOS2
12229 # ----------
12230 # Check for EMX on OS/2.
12231 m4_define([_AC_EMXOS2],
12232 [AC_CACHE_CHECK([for EMX OS/2 environment], [ac_cv_emxos2],
12233 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([], [return __EMX__;])],
12234                    [ac_cv_emxos2=yes],
12235                    [ac_cv_emxos2=no])])
12236 test "$ac_cv_emxos2" = yes && EMXOS2=yes[]dnl
12237 ])# _AC_EMXOS2
12238 @end example
12243 @c ============================================= Portable Shell Programming
12245 @node Portable Shell
12246 @chapter Portable Shell Programming
12247 @cindex Portable shell programming
12249 When writing your own checks, there are some shell-script programming
12250 techniques you should avoid in order to make your code portable.  The
12251 Bourne shell and upward-compatible shells like the Korn shell and Bash
12252 have evolved over the years, but to prevent trouble, do not take
12253 advantage of features that were added after Unix version 7, circa
12254 1977 (@pxref{Systemology}).
12256 You should not use aliases, negated character classes, or other features
12257 that are not found in all Bourne-compatible shells; restrict yourself
12258 to the lowest common denominator.  Even @code{unset} is not supported
12259 by all shells!
12261 Shell functions are considered portable nowadays, though Autoconf still
12262 does not use them (Autotest does).  However, some pitfalls have to be
12263 avoided for portable use of shell functions.
12265 Some ancient systems have quite
12266 small limits on the length of the @samp{#!} line; for instance, 32
12267 bytes (not including the newline) on SunOS 4.
12268 A few ancient 4.2@acronym{BSD} based systems (such as Dynix circa 1984)
12269 required a single space between the @samp{#!} and the @samp{/}.
12270 However, these ancient systems are no longer of practical concern.
12272 The set of external programs you should run in a @command{configure} script
12273 is fairly small.  @xref{Utilities in Makefiles, , Utilities in
12274 Makefiles, standards, @acronym{GNU} Coding Standards}, for the list.  This
12275 restriction allows users to start out with a fairly small set of
12276 programs and build the rest, avoiding too many interdependencies between
12277 packages.
12279 Some of these external utilities have a portable subset of features; see
12280 @ref{Limitations of Usual Tools}.
12282 There are other sources of documentation about shells.  The
12283 specification for the Posix
12284 @uref{http://www.opengroup.org/@/susv3/@/utilities/@/xcu_chap02.html, Shell
12285 Command Language}, though more generous than the restrictive shell
12286 subset described above, is fairly portable nowadays.  Also please see
12287 @uref{http://www.faqs.org/@/faqs/@/unix-faq/@/shell/, the Shell FAQs}.
12289 @menu
12290 * Shellology::                  A zoology of shells
12291 * Here-Documents::              Quirks and tricks
12292 * File Descriptors::            FDs and redirections
12293 * File System Conventions::     File names
12294 * Shell Pattern Matching::      Pattern matching
12295 * Shell Substitutions::         Variable and command expansions
12296 * Assignments::                 Varying side effects of assignments
12297 * Parentheses::                 Parentheses in shell scripts
12298 * Slashes::                     Slashes in shell scripts
12299 * Special Shell Variables::     Variables you should not change
12300 * Shell Functions::             What to look out for if you use them
12301 * Limitations of Builtins::     Portable use of not so portable /bin/sh
12302 * Limitations of Usual Tools::  Portable use of portable tools
12303 @end menu
12305 @node Shellology
12306 @section Shellology
12307 @cindex Shellology
12309 There are several families of shells, most prominently the Bourne family
12310 and the C shell family which are deeply incompatible.  If you want to
12311 write portable shell scripts, avoid members of the C shell family.  The
12312 @uref{http://www.faqs.org/@/faqs/@/unix-faq/@/shell/@/shell-differences/, the
12313 Shell difference FAQ} includes a small history of Posix shells, and a
12314 comparison between several of them.
12316 Below we describe some of the members of the Bourne shell family.
12318 @table @asis
12319 @item Ash
12320 @cindex Ash
12321 Ash is often used on @acronym{GNU}/Linux and @acronym{BSD}
12322 systems as a light-weight Bourne-compatible shell.  Ash 0.2 has some
12323 bugs that are fixed in the 0.3.x series, but portable shell scripts
12324 should work around them, since version 0.2 is still shipped with many
12325 @acronym{GNU}/Linux distributions.
12327 To be compatible with Ash 0.2:
12329 @itemize @minus
12330 @item
12331 don't use @samp{$?} after expanding empty or unset variables,
12332 or at the start of an @command{eval}:
12334 @example
12335 foo=
12336 false
12337 $foo
12338 echo "Do not use it: $?"
12339 false
12340 eval 'echo "Do not use it: $?"'
12341 @end example
12343 @item
12344 don't use command substitution within variable expansion:
12346 @example
12347 cat $@{FOO=`bar`@}
12348 @end example
12350 @item
12351 beware that single builtin substitutions are not performed by a
12352 subshell, hence their effect applies to the current shell!  @xref{Shell
12353 Substitutions}, item ``Command Substitution''.
12354 @end itemize
12356 @item Bash
12357 @cindex Bash
12358 To detect whether you are running Bash, test whether
12359 @code{BASH_VERSION} is set.  To require
12360 Posix compatibility, run @samp{set -o posix}.  @xref{Bash POSIX
12361 Mode, , Bash Posix Mode, bash, The @acronym{GNU} Bash Reference
12362 Manual}, for details.
12364 @item Bash 2.05 and later
12365 @cindex Bash 2.05 and later
12366 Versions 2.05 and later of Bash use a different format for the
12367 output of the @command{set} builtin, designed to make evaluating its
12368 output easier.  However, this output is not compatible with earlier
12369 versions of Bash (or with many other shells, probably).  So if
12370 you use Bash 2.05 or higher to execute @command{configure},
12371 you'll need to use Bash 2.05 for all other build tasks as well.
12373 @item Ksh
12374 @cindex Ksh
12375 @cindex Korn shell
12376 @prindex @samp{ksh}
12377 @prindex @samp{ksh88}
12378 @prindex @samp{ksh93}
12379 The Korn shell is compatible with the Bourne family and it mostly
12380 conforms to Posix.  It has two major variants commonly
12381 called @samp{ksh88} and @samp{ksh93}, named after the years of initial
12382 release.  It is usually called @command{ksh}, but is called @command{sh}
12383 on some hosts if you set your path appropriately.
12385 Solaris systems have three variants:
12386 @prindex @command{/usr/bin/ksh} on Solaris
12387 @command{/usr/bin/ksh} is @samp{ksh88}; it is
12388 standard on Solaris 2.0 and later.
12389 @prindex @command{/usr/xpg4/bin/sh} on Solaris
12390 @command{/usr/xpg4/bin/sh} is a Posix-compliant variant of
12391 @samp{ksh88}; it is standard on Solaris 9 and later.
12392 @prindex @command{/usr/dt/bin/dtksh} on Solaris
12393 @command{/usr/dt/bin/dtksh} is @samp{ksh93}.
12394 Variants that are not standard may be parts of optional
12395 packages.  There is no extra charge for these packages, but they are
12396 not part of a minimal OS install and therefore some installations may
12397 not have it.
12399 Starting with Tru64 Version 4.0, the Korn shell @command{/usr/bin/ksh}
12400 is also available as @command{/usr/bin/posix/sh}.  If the environment
12401 variable @env{BIN_SH} is set to @code{xpg4}, subsidiary invocations of
12402 the standard shell conform to Posix.
12404 @item Pdksh
12405 @prindex @samp{pdksh}
12406 A public-domain clone of the Korn shell called @command{pdksh} is widely
12407 available: it has most of the @samp{ksh88} features along with a few of
12408 its own.  It usually sets @code{KSH_VERSION}, except if invoked as
12409 @command{/bin/sh} on Open@acronym{BSD}, and similarly to Bash you can require
12410 Posix compatibility by running @samp{set -o posix}.  Unfortunately, with
12411 @command{pdksh} 5.2.14 (the latest stable version as of January 2007)
12412 Posix mode is buggy and causes @command{pdksh} to depart from Posix in
12413 at least one respect:
12415 @example
12416 $ @kbd{echo "`echo \"hello\"`"}
12417 hello
12418 $ @kbd{set -o posix}
12419 $ @kbd{echo "`echo \"hello\"`"}
12420 "hello"
12421 @end example
12423 The last line of output contains spurious quotes.  This is yet another
12424 reason why portable shell code should not contain
12425 @code{"`@dots{}\"@dots{}\"@dots{}`"} constructs (@pxref{Shell
12426 Substitutions}).
12428 @item Zsh
12429 @cindex Zsh
12430 To detect whether you are running @command{zsh}, test whether
12431 @code{ZSH_VERSION} is set.  By default @command{zsh} is @emph{not}
12432 compatible with the Bourne shell: you must execute @samp{emulate sh},
12433 and for @command{zsh} versions before 3.1.6-dev-18 you must also
12434 set @code{NULLCMD} to @samp{:}.  @xref{Compatibility, , Compatibility,
12435 zsh, The Z Shell Manual}, for details.
12437 The default Mac OS X @command{sh} was originally Zsh; it was changed to
12438 Bash in Mac OS X 10.2.
12439 @end table
12441 The following discussion between Russ Allbery and Robert Lipe is worth
12442 reading:
12444 @noindent
12445 Russ Allbery:
12447 @quotation
12448 The @acronym{GNU} assumption that @command{/bin/sh} is the one and only shell
12449 leads to a permanent deadlock.  Vendors don't want to break users'
12450 existing shell scripts, and there are some corner cases in the Bourne
12451 shell that are not completely compatible with a Posix shell.  Thus,
12452 vendors who have taken this route will @emph{never} (OK@dots{}``never say
12453 never'') replace the Bourne shell (as @command{/bin/sh}) with a
12454 Posix shell.
12455 @end quotation
12457 @noindent
12458 Robert Lipe:
12460 @quotation
12461 This is exactly the problem.  While most (at least most System V's) do
12462 have a Bourne shell that accepts shell functions most vendor
12463 @command{/bin/sh} programs are not the Posix shell.
12465 So while most modern systems do have a shell @emph{somewhere} that meets the
12466 Posix standard, the challenge is to find it.
12467 @end quotation
12469 @node Here-Documents
12470 @section Here-Documents
12471 @cindex Here-documents
12472 @cindex Shell here-documents
12474 Don't rely on @samp{\} being preserved just because it has no special
12475 meaning together with the next symbol.  In the native @command{sh}
12476 on Open@acronym{BSD} 2.7 @samp{\"} expands to @samp{"} in here-documents with
12477 unquoted delimiter.  As a general rule, if @samp{\\} expands to @samp{\}
12478 use @samp{\\} to get @samp{\}.
12480 With Open@acronym{BSD} 2.7's @command{sh}
12482 @example
12483 @group
12484 $ @kbd{cat <<EOF
12485 > \" \\
12486 > EOF}
12487 " \
12488 @end group
12489 @end example
12491 @noindent
12492 and with Bash:
12494 @example
12495 @group
12496 bash-2.04$ @kbd{cat <<EOF
12497 > \" \\
12498 > EOF}
12499 \" \
12500 @end group
12501 @end example
12503 Some shells mishandle large here-documents: for example,
12504 Solaris 10 @command{dtksh} and the UnixWare 7.1.1 Posix shell, which are
12505 derived from Korn shell version M-12/28/93d, mishandle braced variable
12506 expansion that crosses a 1024- or 4096-byte buffer boundary
12507 within a here-document.  Only the part of the variable name after the boundary
12508 is used.  For example, @code{$@{variable@}} could be replaced by the expansion
12509 of @code{$@{ble@}}.  If the end of the variable name is aligned with the block
12510 boundary, the shell reports an error, as if you used @code{$@{@}}.
12511 Instead of @code{$@{variable-default@}}, the shell may expand
12512 @code{$@{riable-default@}}, or even @code{$@{fault@}}.  This bug can often
12513 be worked around by omitting the braces: @code{$variable}.  The bug was
12514 fixed in
12515 @samp{ksh93g} (1998-04-30) but as of 2006 many operating systems were
12516 still shipping older versions with the bug.
12518 Many shells (including the Bourne shell) implement here-documents
12519 inefficiently.  In particular, some shells can be extremely inefficient when
12520 a single statement contains many here-documents.  For instance if your
12521 @file{configure.ac} includes something like:
12523 @example
12524 @group
12525 if <cross_compiling>; then
12526   assume this and that
12527 else
12528   check this
12529   check that
12530   check something else
12531   @dots{}
12532   on and on forever
12533   @dots{}
12535 @end group
12536 @end example
12538 A shell parses the whole @code{if}/@code{fi} construct, creating
12539 temporary files for each here-document in it.  Some shells create links
12540 for such here-documents on every @code{fork}, so that the clean-up code
12541 they had installed correctly removes them.  It is creating the links
12542 that can take the shell forever.
12544 Moving the tests out of the @code{if}/@code{fi}, or creating multiple
12545 @code{if}/@code{fi} constructs, would improve the performance
12546 significantly.  Anyway, this kind of construct is not exactly the
12547 typical use of Autoconf.  In fact, it's even not recommended, because M4
12548 macros can't look into shell conditionals, so we may fail to expand a
12549 macro when it was expanded before in a conditional path, and the
12550 condition turned out to be false at runtime, and we end up not
12551 executing the macro at all.
12553 @node File Descriptors
12554 @section File Descriptors
12555 @cindex Descriptors
12556 @cindex File descriptors
12557 @cindex Shell file descriptors
12559 Most shells, if not all (including Bash, Zsh, Ash), output traces on
12560 stderr, even for subshells.  This might result in undesirable content
12561 if you meant to capture the standard-error output of the inner command:
12563 @example
12564 $ @kbd{ash -x -c '(eval "echo foo >&2") 2>stderr'}
12565 $ @kbd{cat stderr}
12566 + eval echo foo >&2
12567 + echo foo
12569 $ @kbd{bash -x -c '(eval "echo foo >&2") 2>stderr'}
12570 $ @kbd{cat stderr}
12571 + eval 'echo foo >&2'
12572 ++ echo foo
12574 $ @kbd{zsh -x -c '(eval "echo foo >&2") 2>stderr'}
12575 @i{# Traces on startup files deleted here.}
12576 $ @kbd{cat stderr}
12577 +zsh:1> eval echo foo >&2
12578 +zsh:1> echo foo
12580 @end example
12582 @noindent
12583 One workaround is to grep out uninteresting lines, hoping not to remove
12584 good ones.
12586 If you intend to redirect both standard error and standard output,
12587 redirect standard output first.  This works better with @acronym{HP-UX},
12588 since its shell mishandles tracing if standard error is redirected
12589 first:
12591 @example
12592 $ @kbd{sh -x -c ': 2>err >out'}
12593 + :
12594 + 2> err $ @kbd{cat err}
12595 1> out
12596 @end example
12598 Don't try to redirect the standard error of a command substitution.  It
12599 must be done @emph{inside} the command substitution.  When running
12600 @samp{: `cd /zorglub` 2>/dev/null} expect the error message to
12601 escape, while @samp{: `cd /zorglub 2>/dev/null`} works properly.
12603 It is worth noting that Zsh (but not Ash nor Bash) makes it possible
12604 in assignments though: @samp{foo=`cd /zorglub` 2>/dev/null}.
12606 When catering to old systems, don't redirect the same file descriptor
12607 several times, as you are doomed to failure under Ultrix.
12609 @example
12610 ULTRIX V4.4 (Rev. 69) System #31: Thu Aug 10 19:42:23 GMT 1995
12611 UWS V4.4 (Rev. 11)
12612 $ @kbd{eval 'echo matter >fullness' >void}
12613 illegal io
12614 $ @kbd{eval '(echo matter >fullness)' >void}
12615 illegal io
12616 $ @kbd{(eval '(echo matter >fullness)') >void}
12617 Ambiguous output redirect.
12618 @end example
12620 @noindent
12621 In each case the expected result is of course @file{fullness} containing
12622 @samp{matter} and @file{void} being empty.  However, this bug is
12623 probably not of practical concern to modern platforms.
12625 Don't rely on file descriptors 0, 1, and 2 remaining closed in a
12626 subsidiary program.  If any of these descriptors is closed, the
12627 operating system may open an unspecified file for the descriptor in the
12628 new process image.  Posix says this may be done only if the subsidiary
12629 program is set-user-ID or set-group-ID, but @acronym{HP-UX} 11.23 does
12630 it even for ordinary programs.
12632 Don't rely on open file descriptors being open in child processes.  In
12633 @command{ksh}, file descriptors above 2 which are opened using
12634 @samp{exec @var{n}>file} are closed by a subsequent @samp{exec} (such as
12635 that involved in the fork-and-exec which runs a program or script).
12636 Thus, using @command{sh}, we have:
12638 @example
12639 $ @kbd{cat ./descrips}
12640 #!/bin/sh -
12641 echo hello >&5
12642 $ @kbd{exec 5>t}
12643 $ @kbd{./descrips}
12644 $ @kbd{cat t}
12645 hello
12647 @end example
12649 @noindent
12650 But using ksh:
12652 @example
12653 $ @kbd{exec 5>t}
12654 $ @kbd{./descrips}
12655 hello
12656 $ @kbd{cat t}
12658 @end example
12660 @noindent
12661 Within the process which runs the @samp{descrips} script, file
12662 descriptor 5 is closed.
12664 @acronym{DOS} variants cannot rename or remove open files, such as in
12665 @samp{mv foo bar >foo} or @samp{rm foo >foo}, even though this is
12666 perfectly portable among Posix hosts.
12668 A few ancient systems reserved some file descriptors.  By convention,
12669 file descriptor 3 was opened to @file{/dev/tty} when you logged into
12670 Eighth Edition (1985) through Tenth Edition Unix (1989).  File
12671 descriptor 4 had a special use on the Stardent/Kubota Titan (circa
12672 1990), though we don't now remember what it was.  Both these systems are
12673 obsolete, so it's now safe to treat file descriptors 3 and 4 like any
12674 other file descriptors.
12676 @node File System Conventions
12677 @section File System Conventions
12678 @cindex File system conventions
12680 Autoconf uses shell-script processing extensively, so the file names
12681 that it processes should not contain characters that are special to the
12682 shell.  Special characters include space, tab, newline, @sc{nul}, and
12683 the following:
12685 @example
12686 " # $ & ' ( ) * ; < = > ? [ \ ` |
12687 @end example
12689 Also, file names should not begin with @samp{~} or @samp{-}, and should
12690 contain neither @samp{-} immediately after @samp{/} nor @samp{~}
12691 immediately after @samp{:}.  On Posix-like platforms, directory names
12692 should not contain @samp{:}, as this runs afoul of @samp{:} used as the
12693 path separator.
12695 These restrictions apply not only to the files that you distribute, but
12696 also to the absolute file names of your source, build, and destination
12697 directories.
12699 On some Posix-like platforms, @samp{!} and @samp{^} are special too, so
12700 they should be avoided.
12702 Posix lets implementations treat leading @file{//} specially, but
12703 requires leading @file{///} and beyond to be equivalent to @file{/}.
12704 Most Unix variants treat @file{//} like @file{/}.  However, some treat
12705 @file{//} as a ``super-root'' that can provide access to files that are
12706 not otherwise reachable from @file{/}.  The super-root tradition began
12707 with Apollo Domain/OS, which died out long ago, but unfortunately Cygwin
12708 has revived it.
12710 While @command{autoconf} and friends are usually run on some Posix
12711 variety, they can be used on other systems, most notably @acronym{DOS}
12712 variants.  This impacts several assumptions regarding file names.
12714 @noindent
12715 For example, the following code:
12717 @example
12718 case $foo_dir in
12719   /*) # Absolute
12720      ;;
12721   *)
12722      foo_dir=$dots$foo_dir ;;
12723 esac
12724 @end example
12726 @noindent
12727 fails to properly detect absolute file names on those systems, because
12728 they can use a drivespec, and usually use a backslash as directory
12729 separator.  If you want to be portable to @acronym{DOS} variants (at the
12730 price of rejecting valid but oddball Posix file names like @file{a:\b}),
12731 you can check for absolute file names like this:
12733 @cindex absolute file names, detect
12734 @example
12735 case $foo_dir in
12736   [\\/]* | ?:[\\/]* ) # Absolute
12737      ;;
12738   *)
12739      foo_dir=$dots$foo_dir ;;
12740 esac
12741 @end example
12743 @noindent
12744 Make sure you quote the brackets if appropriate and keep the backslash as
12745 first character (@pxref{Limitations of Builtins}).
12747 Also, because the colon is used as part of a drivespec, these systems don't
12748 use it as path separator.  When creating or accessing paths, you can use the
12749 @code{PATH_SEPARATOR} output variable instead.  @command{configure} sets this
12750 to the appropriate value for the build system (@samp{:} or @samp{;}) when it
12751 starts up.
12753 File names need extra care as well.  While @acronym{DOS} variants
12754 that are Posixy enough to run @command{autoconf} (such as @acronym{DJGPP})
12755 are usually able to handle long file names properly, there are still
12756 limitations that can seriously break packages.  Several of these issues
12757 can be easily detected by the
12758 @uref{ftp://ftp.gnu.org/gnu/non-gnu/doschk/doschk-1.1.tar.gz, doschk}
12759 package.
12761 A short overview follows; problems are marked with @sc{sfn}/@sc{lfn} to
12762 indicate where they apply: @sc{sfn} means the issues are only relevant to
12763 plain @acronym{DOS}, not to @acronym{DOS} under Microsoft Windows
12764 variants, while @sc{lfn} identifies problems that exist even under
12765 Microsoft Windows variants.
12767 @table @asis
12768 @item No multiple dots (@sc{sfn})
12769 @acronym{DOS} cannot handle multiple dots in file names.  This is an especially
12770 important thing to remember when building a portable configure script,
12771 as @command{autoconf} uses a .in suffix for template files.
12773 This is perfectly OK on Posix variants:
12775 @example
12776 AC_CONFIG_HEADERS([config.h])
12777 AC_CONFIG_FILES([source.c foo.bar])
12778 AC_OUTPUT
12779 @end example
12781 @noindent
12782 but it causes problems on @acronym{DOS}, as it requires @samp{config.h.in},
12783 @samp{source.c.in} and @samp{foo.bar.in}.  To make your package more portable
12784 to @acronym{DOS}-based environments, you should use this instead:
12786 @example
12787 AC_CONFIG_HEADERS([config.h:config.hin])
12788 AC_CONFIG_FILES([source.c:source.cin foo.bar:foobar.in])
12789 AC_OUTPUT
12790 @end example
12792 @item No leading dot (@sc{sfn})
12793 @acronym{DOS} cannot handle file names that start with a dot.  This is usually
12794 not important for @command{autoconf}.
12796 @item Case insensitivity (@sc{lfn})
12797 @acronym{DOS} is case insensitive, so you cannot, for example, have both a
12798 file called @samp{INSTALL} and a directory called @samp{install}.  This
12799 also affects @command{make}; if there's a file called @samp{INSTALL} in
12800 the directory, @samp{make install} does nothing (unless the
12801 @samp{install} target is marked as PHONY).
12803 @item The 8+3 limit (@sc{sfn})
12804 Because the @acronym{DOS} file system only stores the first 8 characters of
12805 the file name and the first 3 of the extension, those must be unique.
12806 That means that @file{foobar-part1.c}, @file{foobar-part2.c} and
12807 @file{foobar-prettybird.c} all resolve to the same file name
12808 (@file{FOOBAR-P.C}).  The same goes for @file{foo.bar} and
12809 @file{foo.bartender}.
12811 The 8+3 limit is not usually a problem under Microsoft Windows, as it
12812 uses numeric
12813 tails in the short version of file names to make them unique.  However, a
12814 registry setting can turn this behavior off.  While this makes it
12815 possible to share file trees containing long file names between @sc{sfn}
12816 and @sc{lfn} environments, it also means the above problem applies there
12817 as well.
12819 @item Invalid characters (@sc{lfn})
12820 Some characters are invalid in @acronym{DOS} file names, and should therefore
12821 be avoided.  In a @sc{lfn} environment, these are @samp{/}, @samp{\},
12822 @samp{?}, @samp{*}, @samp{:}, @samp{<}, @samp{>}, @samp{|} and @samp{"}.
12823 In a @sc{sfn} environment, other characters are also invalid.  These
12824 include @samp{+}, @samp{,}, @samp{[} and @samp{]}.
12826 @item Invalid names (@sc{lfn})
12827 Some @acronym{DOS} file names are reserved, and cause problems if you
12828 try to use files with those names.  These names include @file{CON},
12829 @file{AUX}, @file{COM1}, @file{COM2}, @file{COM3}, @file{COM4},
12830 @file{LPT1}, @file{LPT2}, @file{LPT3}, @file{NUL}, and @file{PRN}.
12831 File names are case insensitive, so even names like
12832 @file{aux/config.guess} are disallowed.
12834 @end table
12836 @node Shell Pattern Matching
12837 @section Shell Pattern Matching
12838 @cindex Shell pattern matching
12840 Nowadays portable patterns can use negated character classes like
12841 @samp{[!-aeiou]}.  The older syntax @samp{[^-aeiou]} is supported by
12842 some shells but not others; hence portable scripts should never use
12843 @samp{^} as the first character of a bracket pattern.
12845 Outside the C locale, patterns like @samp{[a-z]} are problematic since
12846 they may match characters that are not lower-case letters.
12848 @node Shell Substitutions
12849 @section Shell Substitutions
12850 @cindex Shell substitutions
12852 Contrary to a persistent urban legend, the Bourne shell does not
12853 systematically split variables and back-quoted expressions, in particular
12854 on the right-hand side of assignments and in the argument of @code{case}.
12855 For instance, the following code:
12857 @example
12858 case "$given_srcdir" in
12859 .)  top_srcdir="`echo "$dots" | sed 's|/$||'`" ;;
12860 *)  top_srcdir="$dots$given_srcdir" ;;
12861 esac
12862 @end example
12864 @noindent
12865 is more readable when written as:
12867 @example
12868 case $given_srcdir in
12869 .)  top_srcdir=`echo "$dots" | sed 's|/$||'` ;;
12870 *)  top_srcdir=$dots$given_srcdir ;;
12871 esac
12872 @end example
12874 @noindent
12875 and in fact it is even @emph{more} portable: in the first case of the
12876 first attempt, the computation of @code{top_srcdir} is not portable,
12877 since not all shells properly understand @code{"`@dots{}"@dots{}"@dots{}`"}.
12878 Worse yet, not all shells understand @code{"`@dots{}\"@dots{}\"@dots{}`"}
12879 the same way.  There is just no portable way to use double-quoted
12880 strings inside double-quoted back-quoted expressions (pfew!).
12882 @table @code
12883 @item $@@
12884 @cindex @samp{"$@@"}
12885 One of the most famous shell-portability issues is related to
12886 @samp{"$@@"}.  When there are no positional arguments, Posix says
12887 that @samp{"$@@"} is supposed to be equivalent to nothing, but the
12888 original Unix version 7 Bourne shell treated it as equivalent to
12889 @samp{""} instead, and this behavior survives in later implementations
12890 like Digital Unix 5.0.
12892 The traditional way to work around this portability problem is to use
12893 @samp{$@{1+"$@@"@}}.  Unfortunately this method does not work with
12894 Zsh (3.x and 4.x), which is used on Mac OS X@.  When emulating
12895 the Bourne shell, Zsh performs word splitting on @samp{$@{1+"$@@"@}}:
12897 @example
12898 zsh $ @kbd{emulate sh}
12899 zsh $ @kbd{for i in "$@@"; do echo $i; done}
12900 Hello World
12902 zsh $ @kbd{for i in $@{1+"$@@"@}; do echo $i; done}
12903 Hello
12904 World
12906 @end example
12908 @noindent
12909 Zsh handles plain @samp{"$@@"} properly, but we can't use plain
12910 @samp{"$@@"} because of the portability problems mentioned above.
12911 One workaround relies on Zsh's ``global aliases'' to convert
12912 @samp{$@{1+"$@@"@}} into @samp{"$@@"} by itself:
12914 @example
12915 test "$@{ZSH_VERSION+set@}" = set && alias -g '$@{1+"$@@"@}'='"$@@"'
12916 @end example
12918 Zsh only recognizes this alias when a shell word matches it exactly;
12919 @samp{"foo"$@{1+"$@@"@}} remains subject to word splitting.  Since this
12920 case always yields at least one shell word, use plain @samp{"$@@"}.
12922 A more conservative workaround is to avoid @samp{"$@@"} if it is
12923 possible that there may be no positional arguments.  For example,
12924 instead of:
12926 @example
12927 cat conftest.c "$@@"
12928 @end example
12930 you can use this instead:
12932 @example
12933 case $# in
12934 0) cat conftest.c;;
12935 *) cat conftest.c "$@@";;
12936 esac
12937 @end example
12939 Autoconf macros often use the @command{set} command to update
12940 @samp{$@@}, so if you are writing shell code intended for
12941 @command{configure} you should not assume that the value of @samp{$@@}
12942 persists for any length of time.
12945 @item $@{10@}
12946 @cindex positional parameters
12947 The 10th, 11th, @dots{} positional parameters can be accessed only after
12948 a @code{shift}.  The 7th Edition shell reported an error if given
12949 @code{$@{10@}}, and
12950 Solaris 10 @command{/bin/sh} still acts that way:
12952 @example
12953 $ @kbd{set 1 2 3 4 5 6 7 8 9 10}
12954 $ @kbd{echo $@{10@}}
12955 bad substitution
12956 @end example
12958 @item $@{@var{var}:-@var{value}@}
12959 @c Info cannot handle `:' in index entries.
12960 @c @cindex $@{@var{var}:-@var{value}@}
12961 Old @acronym{BSD} shells, including the Ultrix @code{sh}, don't accept the
12962 colon for any shell substitution, and complain and die.
12963 Similarly for $@{@var{var}:=@var{value}@}, $@{@var{var}:?@var{value}@}, etc.
12965 @item $@{@var{var}=@var{literal}@}
12966 @cindex $@{@var{var}=@var{literal}@}
12967 Be sure to quote:
12969 @example
12970 : $@{var='Some words'@}
12971 @end example
12973 @noindent
12974 otherwise some shells, such as on Digital Unix V 5.0, die because
12975 of a ``bad substitution''.
12977 @sp 1
12979 Solaris @command{/bin/sh} has a frightening bug in its interpretation
12980 of this.  Imagine you need set a variable to a string containing
12981 @samp{@}}.  This @samp{@}} character confuses Solaris @command{/bin/sh}
12982 when the affected variable was already set.  This bug can be exercised
12983 by running:
12985 @example
12986 $ @kbd{unset foo}
12987 $ @kbd{foo=$@{foo='@}'@}}
12988 $ @kbd{echo $foo}
12990 $ @kbd{foo=$@{foo='@}'   # no error; this hints to what the bug is}
12991 $ @kbd{echo $foo}
12993 $ @kbd{foo=$@{foo='@}'@}}
12994 $ @kbd{echo $foo}
12995 @}@}
12996  ^ ugh!
12997 @end example
12999 It seems that @samp{@}} is interpreted as matching @samp{$@{}, even
13000 though it is enclosed in single quotes.  The problem doesn't happen
13001 using double quotes.
13003 @item $@{@var{var}=@var{expanded-value}@}
13004 @cindex $@{@var{var}=@var{expanded-value}@}
13005 On Ultrix,
13006 running
13008 @example
13009 default="yu,yaa"
13010 : $@{var="$default"@}
13011 @end example
13013 @noindent
13014 sets @var{var} to @samp{M-yM-uM-,M-yM-aM-a}, i.e., the 8th bit of
13015 each char is set.  You don't observe the phenomenon using a simple
13016 @samp{echo $var} since apparently the shell resets the 8th bit when it
13017 expands $var.  Here are two means to make this shell confess its sins:
13019 @example
13020 $ @kbd{cat -v <<EOF
13021 $var
13022 EOF}
13023 @end example
13025 @noindent
13028 @example
13029 $ @kbd{set | grep '^var=' | cat -v}
13030 @end example
13032 One classic incarnation of this bug is:
13034 @example
13035 default="a b c"
13036 : $@{list="$default"@}
13037 for c in $list; do
13038   echo $c
13039 done
13040 @end example
13042 @noindent
13043 You'll get @samp{a b c} on a single line.  Why?  Because there are no
13044 spaces in @samp{$list}: there are @samp{M- }, i.e., spaces with the 8th
13045 bit set, hence no IFS splitting is performed!!!
13047 One piece of good news is that Ultrix works fine with @samp{:
13048 $@{list=$default@}}; i.e., if you @emph{don't} quote.  The bad news is
13049 then that @acronym{QNX} 4.25 then sets @var{list} to the @emph{last} item of
13050 @var{default}!
13052 The portable way out consists in using a double assignment, to switch
13053 the 8th bit twice on Ultrix:
13055 @example
13056 list=$@{list="$default"@}
13057 @end example
13059 @noindent
13060 @dots{}but beware of the @samp{@}} bug from Solaris (see above).  For safety,
13061 use:
13063 @example
13064 test "$@{var+set@}" = set || var=@var{@{value@}}
13065 @end example
13067 @item $@{#@var{var}@}
13068 @itemx $@{@var{var}%@var{word}@}
13069 @itemx $@{@var{var}%%@var{word}@}
13070 @itemx $@{@var{var}#@var{word}@}
13071 @itemx $@{@var{var}##@var{word}@}
13072 @cindex $@{#@var{var}@}
13073 @cindex $@{@var{var}%@var{word}@}
13074 @cindex $@{@var{var}%%@var{word}@}
13075 @cindex $@{@var{var}#@var{word}@}
13076 @cindex $@{@var{var}##@var{word}@}
13077 Posix requires support for these usages, but they do not work with many
13078 traditional shells, e.g., Solaris 10 @command{/bin/sh}.
13080 Also, @command{pdksh} 5.2.14 mishandles some @var{word} forms.  For
13081 example if @samp{$1} is @samp{a/b} and @samp{$2} is @samp{a}, then
13082 @samp{$@{1#$2@}} should yield @samp{/b}, but with @command{pdksh} it
13083 yields the empty string.
13086 @item `@var{commands}`
13087 @cindex `@var{commands}`
13088 @cindex Command Substitution
13089 Posix requires shells to trim all trailing newlines from command
13090 output before substituting it, so assignments like
13091 @samp{dir=`echo "$file" | tr a A`} do not work as expected if
13092 @samp{$file} ends in a newline.
13094 While in general it makes no sense, do not substitute a single builtin
13095 with side effects, because Ash 0.2, trying to optimize, does not fork a
13096 subshell to perform the command.
13098 For instance, if you wanted to check that @command{cd} is silent, do not
13099 use @samp{test -z "`cd /`"} because the following can happen:
13101 @example
13102 $ @kbd{pwd}
13103 /tmp
13104 $ @kbd{test -z "`cd /`" && pwd}
13106 @end example
13108 @noindent
13109 The result of @samp{foo=`exit 1`} is left as an exercise to the reader.
13111 The MSYS shell leaves a stray byte in the expansion of a double-quoted
13112 command substitution of a native program, if the end of the substitution
13113 is not aligned with the end of the double quote.  This may be worked
13114 around by inserting another pair of quotes:
13116 @example
13117 $ @kbd{echo "`printf 'foo\r\n'` bar" > broken}
13118 $ @kbd{echo "`printf 'foo\r\n'`"" bar" | cmp - broken}
13119 - broken differ: char 4, line 1
13120 @end example
13123 @item $(@var{commands})
13124 @cindex $(@var{commands})
13125 This construct is meant to replace @samp{`@var{commands}`},
13126 and it has most of the problems listed under @code{`@var{commands}`}.
13128 This construct can be
13129 nested while this is impossible to do portably with back quotes.
13130 Unfortunately it is not yet universally supported.  Most notably, even recent
13131 releases of Solaris don't support it:
13133 @example
13134 $ @kbd{showrev -c /bin/sh | grep version}
13135 Command version: SunOS 5.10 Generic 121005-03 Oct 2006
13136 $ @kbd{echo $(echo blah)}
13137 syntax error: `(' unexpected
13138 @end example
13140 @noindent
13141 nor does @sc{irix} 6.5's Bourne shell:
13142 @example
13143 $ @kbd{uname -a}
13144 IRIX firebird-image 6.5 07151432 IP22
13145 $ @kbd{echo $(echo blah)}
13146 $(echo blah)
13147 @end example
13149 If you do use @samp{$(@var{commands})}, make sure that the commands
13150 do not start with a parenthesis, as that would cause confusion with
13151 a different notation @samp{$((@var{expression}))} that in modern
13152 shells is an arithmetic expression not a command.  To avoid the
13153 confusion, insert a space between the two opening parentheses.
13155 Avoid @var{commands} that contain unbalanced parentheses in
13156 here-documents, comments, or case statement patterns, as many shells
13157 mishandle them.  For example, Bash 3.1, @samp{ksh88}, @command{pdksh}
13158 5.2.14, and Zsh 4.2.6 all mishandle the following valid command:
13160 @example
13161 echo $(case x in x) echo hello;; esac)
13162 @end example
13165 @item $((@var{expression}))
13166 @cindex $((@var{expression}))
13167 Arithmetic expansion is not portable as some shells (most
13168 notably Solaris 10 @command{/bin/sh}) don't support it.
13172 @item ^
13173 @cindex ^ quoting
13174 Always quote @samp{^}, otherwise traditional shells such as
13175 @command{/bin/sh} on Solaris 10 treat this like @samp{|}.
13177 @end table
13180 @node Assignments
13181 @section Assignments
13182 @cindex Shell assignments
13184 When setting several variables in a row, be aware that the order of the
13185 evaluation is undefined.  For instance @samp{foo=1 foo=2; echo $foo}
13186 gives @samp{1} with Solaris @command{/bin/sh}, but @samp{2} with Bash.
13187 You must use
13188 @samp{;} to enforce the order: @samp{foo=1; foo=2; echo $foo}.
13190 Don't rely on the following to find @file{subdir/program}:
13192 @example
13193 PATH=subdir$PATH_SEPARATOR$PATH program
13194 @end example
13196 @noindent
13197 as this does not work with Zsh 3.0.6.  Use something like this
13198 instead:
13200 @example
13201 (PATH=subdir$PATH_SEPARATOR$PATH; export PATH; exec program)
13202 @end example
13204 Don't rely on the exit status of an assignment: Ash 0.2 does not change
13205 the status and propagates that of the last statement:
13207 @example
13208 $ @kbd{false || foo=bar; echo $?}
13210 $ @kbd{false || foo=`:`; echo $?}
13212 @end example
13214 @noindent
13215 and to make things even worse, @acronym{QNX} 4.25 just sets the exit status
13216 to 0 in any case:
13218 @example
13219 $ @kbd{foo=`exit 1`; echo $?}
13221 @end example
13223 To assign default values, follow this algorithm:
13225 @enumerate
13226 @item
13227 If the default value is a literal and does not contain any closing
13228 brace, use:
13230 @example
13231 : $@{var='my literal'@}
13232 @end example
13234 @item
13235 If the default value contains no closing brace, has to be expanded, and
13236 the variable being initialized is not intended to be IFS-split
13237 (i.e., it's not a list), then use:
13239 @example
13240 : $@{var="$default"@}
13241 @end example
13243 @item
13244 If the default value contains no closing brace, has to be expanded, and
13245 the variable being initialized is intended to be IFS-split (i.e., it's a list),
13246 then use:
13248 @example
13249 var=$@{var="$default"@}
13250 @end example
13252 @item
13253 If the default value contains a closing brace, then use:
13255 @example
13256 test "$@{var+set@}" = set || var="has a '@}'"
13257 @end example
13258 @end enumerate
13260 In most cases @samp{var=$@{var="$default"@}} is fine, but in case of
13261 doubt, just use the last form.  @xref{Shell Substitutions}, items
13262 @samp{$@{@var{var}:-@var{value}@}} and @samp{$@{@var{var}=@var{value}@}}
13263 for the rationale.
13265 @node Parentheses
13266 @section Parentheses in Shell Scripts
13267 @cindex Shell parentheses
13269 Beware of two opening parentheses in a row, as many shell
13270 implementations treat them specially.  Posix requires that the command
13271 @samp{((cat))} must behave like @samp{(cat)}, but many shells, including
13272 Bash and the Korn shell, treat @samp{((cat))} as an arithmetic
13273 expression equivalent to @samp{let "cat"}, and may or may not report an
13274 error when they detect that @samp{cat} is not a number.  As another
13275 example, @samp{pdksh} 5.2.14 misparses the following code:
13277 @example
13278 if ((true) || false); then
13279   echo ok
13281 @end example
13283 @noindent
13284 To work around this problem, insert a space between the two opening
13285 parentheses.  There is a similar problem and workaround with
13286 @samp{$((}; see @ref{Shell Substitutions}.
13288 @node Slashes
13289 @section Slashes in Shell Scripts
13290 @cindex Shell slashes
13292 Unpatched Tru64 5.1 @command{sh} omits the last slash of command-line
13293 arguments that contain two trailing slashes:
13295 @example
13296 $ @kbd{echo / // /// //// .// //.}
13297 / / // /// ./ //.
13298 $ @kbd{x=//}
13299 $ @kbd{eval "echo \$x"}
13301 $ @kbd{set -x}
13302 $ @kbd{echo abc | tr -t ab //}
13303 + echo abc
13304 + tr -t ab /
13306 @end example
13308 Unpatched Tru64 4.0 @command{sh} adds a slash after @samp{"$var"} if the
13309 variable is empty and the second double-quote is followed by a word that
13310 begins and ends with slash:
13312 @example
13313 $ @kbd{sh -xc 'p=; echo "$p"/ouch/'}
13315 + echo //ouch/
13316 //ouch/
13317 @end example
13319 However, our understanding is that patches are available, so perhaps
13320 it's not worth worrying about working around these horrendous bugs.
13322 @node Special Shell Variables
13323 @section Special Shell Variables
13324 @cindex Shell variables
13325 @cindex Special shell variables
13327 Some shell variables should not be used, since they can have a deep
13328 influence on the behavior of the shell.  In order to recover a sane
13329 behavior from the shell, some variables should be unset, but
13330 @command{unset} is not portable (@pxref{Limitations of Builtins}) and a
13331 fallback value is needed.
13333 As a general rule, shell variable names containing a lower-case letter
13334 are safe; you can define and use these variables without worrying about
13335 their effect on the underlying system, and without worrying about
13336 whether the shell changes them unexpectedly.  (The exception is the
13337 shell variable @code{status}, as described below.)
13339 Here is a list of names that are known to cause trouble.  This list is
13340 not exhaustive, but you should be safe if you avoid the name
13341 @code{status} and names containing only upper-case letters and
13342 underscores.
13344 @c Alphabetical order, case insensitive, `A' before `a'.
13345 @table @code
13346 @item _
13347 Many shells reserve @samp{$_} for various purposes, e.g., the name of
13348 the last command executed.
13350 @item BIN_SH
13351 @evindex BIN_SH
13352 In Tru64, if @env{BIN_SH} is set to @code{xpg4}, subsidiary invocations of
13353 the standard shell conform to Posix.
13355 @item CDPATH
13356 @evindex CDPATH
13357 When this variable is set it specifies a list of directories to search
13358 when invoking @code{cd} with a relative file name that did not start
13359 with @samp{./} or @samp{../}.  Posix
13360 1003.1-2001 says that if a nonempty directory name from @env{CDPATH}
13361 is used successfully, @code{cd} prints the resulting absolute
13362 file name.  Unfortunately this output can break idioms like
13363 @samp{abs=`cd src && pwd`} because @code{abs} receives the name twice.
13364 Also, many shells do not conform to this part of Posix; for
13365 example, @command{zsh} prints the result only if a directory name
13366 other than @file{.} was chosen from @env{CDPATH}.
13368 In practice the shells that have this problem also support
13369 @command{unset}, so you can work around the problem as follows:
13371 @example
13372 (unset CDPATH) >/dev/null 2>&1 && unset CDPATH
13373 @end example
13375 You can also avoid output by ensuring that your directory name is
13376 absolute or anchored at @samp{./}, as in @samp{abs=`cd ./src && pwd`}.
13378 Autoconf-generated scripts automatically unset @env{CDPATH} if
13379 possible, so you need not worry about this problem in those scripts.
13381 @item DUALCASE
13382 @evindex DUALCASE
13383 In the MKS shell, case statements and file name generation are
13384 case-insensitive unless @env{DUALCASE} is nonzero.
13385 Autoconf-generated scripts export this variable when they start up.
13387 @item ENV
13388 @itemx MAIL
13389 @itemx MAILPATH
13390 @itemx PS1
13391 @itemx PS2
13392 @itemx PS4
13393 @evindex ENV
13394 @evindex MAIL
13395 @evindex MAILPATH
13396 @evindex PS1
13397 @evindex PS2
13398 @evindex PS4
13399 These variables should not matter for shell scripts, since they are
13400 supposed to affect only interactive shells.  However, at least one
13401 shell (the pre-3.0 @sc{uwin} Korn shell) gets confused about
13402 whether it is interactive, which means that (for example) a @env{PS1}
13403 with a side effect can unexpectedly modify @samp{$?}.  To work around
13404 this bug, Autoconf-generated scripts do something like this:
13406 @example
13407 (unset ENV) >/dev/null 2>&1 && unset ENV MAIL MAILPATH
13408 PS1='$ '
13409 PS2='> '
13410 PS4='+ '
13411 @end example
13413 @item FPATH
13414 The Korn shell uses @env{FPATH} to find shell functions, so avoid
13415 @env{FPATH} in portable scripts.  @env{FPATH} is consulted after
13416 @env{PATH}, but you still need to be wary of tests that use @env{PATH}
13417 to find whether a command exists, since they might report the wrong
13418 result if @env{FPATH} is also set.
13420 @item IFS
13421 @evindex IFS
13422 Long ago, shell scripts inherited @env{IFS} from the environment,
13423 but this caused many problems so modern shells ignore any environment
13424 settings for @env{IFS}.
13426 Don't set the first character of @code{IFS} to backslash.  Indeed,
13427 Bourne shells use the first character (backslash) when joining the
13428 components in @samp{"$@@"} and some shells then reinterpret (!)@: the
13429 backslash escapes, so you can end up with backspace and other strange
13430 characters.
13432 The proper value for @code{IFS} (in regular code, not when performing
13433 splits) is @samp{@key{SPC}@key{TAB}@key{RET}}.  The first character is
13434 especially important, as it is used to join the arguments in @samp{$*};
13435 however, note that traditional shells, but also bash-2.04, fail to adhere
13436 to this and join with a space anyway.
13438 @item LANG
13439 @itemx LC_ALL
13440 @itemx LC_COLLATE
13441 @itemx LC_CTYPE
13442 @itemx LC_MESSAGES
13443 @itemx LC_MONETARY
13444 @itemx LC_NUMERIC
13445 @itemx LC_TIME
13446 @evindex LANG
13447 @evindex LC_ALL
13448 @evindex LC_COLLATE
13449 @evindex LC_CTYPE
13450 @evindex LC_MESSAGES
13451 @evindex LC_MONETARY
13452 @evindex LC_NUMERIC
13453 @evindex LC_TIME
13455 Autoconf-generated scripts normally set all these variables to
13456 @samp{C} because so much configuration code assumes the C locale and
13457 Posix requires that locale environment variables be set to
13458 @samp{C} if the C locale is desired.  However, some older, nonstandard
13459 systems (notably @acronym{SCO}) break if locale environment variables
13460 are set to @samp{C}, so when running on these systems
13461 Autoconf-generated scripts unset the variables instead.
13463 @item LANGUAGE
13464 @evindex LANGUAGE
13466 @env{LANGUAGE} is not specified by Posix, but it is a @acronym{GNU}
13467 extension that overrides @env{LC_ALL} in some cases, so
13468 Autoconf-generated scripts set it too.
13470 @item LC_ADDRESS
13471 @itemx LC_IDENTIFICATION
13472 @itemx LC_MEASUREMENT
13473 @itemx LC_NAME
13474 @itemx LC_PAPER
13475 @itemx LC_TELEPHONE
13476 @evindex LC_ADDRESS
13477 @evindex LC_IDENTIFICATION
13478 @evindex LC_MEASUREMENT
13479 @evindex LC_NAME
13480 @evindex LC_PAPER
13481 @evindex LC_TELEPHONE
13483 These locale environment variables are @acronym{GNU} extensions.  They
13484 are treated like their Posix brethren (@env{LC_COLLATE},
13485 etc.)@: as described above.
13487 @item LINENO
13488 Most modern shells provide the current line number in @code{LINENO}.
13489 Its value is the line number of the beginning of the current command.
13490 Autoconf attempts to execute @command{configure} with a shell that
13491 supports @code{LINENO}.
13492 If no such shell is available, it attempts to implement @code{LINENO}
13493 with a Sed prepass that replaces each instance of the string
13494 @code{$LINENO} (not followed by an alphanumeric character) with the
13495 line's number.
13497 You should not rely on @code{LINENO} within @command{eval}, as the
13498 behavior differs in practice.  Also, the possibility of the Sed
13499 prepass means that you should not rely on @code{$LINENO} when quoted,
13500 when in here-documents, or when in long commands that cross line
13501 boundaries.  Subshells should be OK, though.  In the following
13502 example, lines 1, 6, and 9 are portable, but the other instances of
13503 @code{LINENO} are not:
13505 @example
13506 @group
13507 $ @kbd{cat lineno}
13508 echo 1. $LINENO
13509 cat <<EOF
13510 3. $LINENO
13511 4. $LINENO
13513 ( echo 6. $LINENO )
13514 eval 'echo 7. $LINENO'
13515 echo 8. '$LINENO'
13516 echo 9. $LINENO '
13517 10.' $LINENO
13518 @end group
13519 @group
13520 $ @kbd{bash-2.05 lineno}
13521 1. 1
13522 3. 2
13523 4. 2
13524 6. 6
13525 7. 1
13526 8. $LINENO
13527 9. 9
13528 10. 9
13529 @end group
13530 @group
13531 $ @kbd{zsh-3.0.6 lineno}
13532 1. 1
13533 3. 2
13534 4. 2
13535 6. 6
13536 7. 7
13537 8. $LINENO
13538 9. 9
13539 10. 9
13540 @end group
13541 @group
13542 $ @kbd{pdksh-5.2.14 lineno}
13543 1. 1
13544 3. 2
13545 4. 2
13546 6. 6
13547 7. 0
13548 8. $LINENO
13549 9. 9
13550 10. 9
13551 @end group
13552 @group
13553 $ @kbd{sed '=' <lineno |}
13554 > @kbd{  sed '}
13555 > @kbd{    N}
13556 > @kbd{    s,$,-,}
13557 > @kbd{    t loop}
13558 > @kbd{    :loop}
13559 > @kbd{    s,^\([0-9]*\)\(.*\)[$]LINENO\([^a-zA-Z0-9_]\),\1\2\1\3,}
13560 > @kbd{    t loop}
13561 > @kbd{    s,-$,,}
13562 > @kbd{    s,^[0-9]*\n,,}
13563 > @kbd{  ' |}
13564 > @kbd{  sh}
13565 1. 1
13566 3. 3
13567 4. 4
13568 6. 6
13569 7. 7
13570 8. 8
13571 9. 9
13572 10. 10
13573 @end group
13574 @end example
13576 @item NULLCMD
13577 @evindex NULLCMD
13578 When executing the command @samp{>foo}, @command{zsh} executes
13579 @samp{$NULLCMD >foo} unless it is operating in Bourne shell
13580 compatibility mode and the @command{zsh} version is newer
13581 than 3.1.6-dev-18.  If you are using an older @command{zsh}
13582 and forget to set @env{NULLCMD},
13583 your script might be suspended waiting for data on its standard input.
13585 @item PATH_SEPARATOR
13586 @evindex PATH_SEPARATOR
13587 On @acronym{DJGPP} systems, the @env{PATH_SEPARATOR} environment
13588 variable can be set to either @samp{:} or @samp{;} to control the path
13589 separator Bash uses to set up certain environment variables (such as
13590 @env{PATH}).  You can set this variable to @samp{;} if you want
13591 @command{configure} to use @samp{;} as a separator; this might be useful
13592 if you plan to use non-Posix shells to execute files.  @xref{File System
13593 Conventions}, for more information about @code{PATH_SEPARATOR}.
13595 @item PWD
13596 @evindex PWD
13597 Posix 1003.1-2001 requires that @command{cd} and
13598 @command{pwd} must update the @env{PWD} environment variable to point
13599 to the logical name of the current directory, but traditional shells
13600 do not support this.  This can cause confusion if one shell instance
13601 maintains @env{PWD} but a subsidiary and different shell does not know
13602 about @env{PWD} and executes @command{cd}; in this case @env{PWD}
13603 points to the wrong directory.  Use @samp{`pwd`} rather than
13604 @samp{$PWD}.
13606 @item RANDOM
13607 Many shells provide @code{RANDOM}, a variable that returns a different
13608 integer each time it is used.  Most of the time, its value does not
13609 change when it is not used, but on @sc{irix} 6.5 the value changes all
13610 the time.  This can be observed by using @command{set}.  It is common
13611 practice to use @code{$RANDOM} as part of a file name, but code
13612 shouldn't rely on @code{$RANDOM} expanding to a nonempty string.
13614 @item status
13615 This variable is an alias to @samp{$?} for @code{zsh} (at least 3.1.6),
13616 hence read-only.  Do not use it.
13617 @end table
13619 @node Shell Functions
13620 @section Shell Functions
13621 @cindex Shell Functions
13623 Nowadays, it is difficult to find a shell that does not support
13624 shell functions at all.  However, some differences should be expected:
13626 Inside a shell function, you should not rely on the error status of a
13627 subshell if the last command of that subshell was @code{exit} or
13628 @code{trap}, as this triggers bugs in zsh 4.x; while Autoconf tries to
13629 find a shell that does not exhibit the bug, zsh might be the only shell
13630 present on the user's machine.
13632 Shell variables and functions may share the same namespace, for example
13633 with Solaris 10 @command{/bin/sh}:
13635 @example
13636 $ @kbd{f () @{ :; @}; f=; f}
13637 f: not found
13638 @end example
13640 @noindent
13641 For this reason, Autotest uses the prefix @samp{at_func_} for its
13642 functions.
13644 Handling of positional parameters and shell options varies among shells.
13645 For example, Korn shells reset and restore trace output (@samp{set -x})
13646 and other options upon function entry and exit.  Inside a function,
13647 @acronym{IRIX} sh sets @samp{$0} to the function name.
13649 Some ancient Bourne shell variants with function support did not reset
13650 @samp{$@var{i}, @var{i} >= 0}, upon function exit, so effectively the
13651 arguments of the script were lost after the first function invocation.
13652 It is probably not worth worrying about these shells any more.
13654 With @acronym{AIX} sh, a @command{trap} on 0 installed in a shell function
13655 triggers at function exit rather than at script exit, see @xref{Limitations
13656 of Builtins}.
13658 @node Limitations of Builtins
13659 @section Limitations of Shell Builtins
13660 @cindex Shell builtins
13661 @cindex Limitations of shell builtins
13663 No, no, we are serious: some shells do have limitations!  :)
13665 You should always keep in mind that any builtin or command may support
13666 options, and therefore differ in behavior with arguments
13667 starting with a dash.  For instance, the innocent @samp{echo "$word"}
13668 can give unexpected results when @code{word} starts with a dash.  It is
13669 often possible to avoid this problem using @samp{echo "x$word"}, taking
13670 the @samp{x} into account later in the pipe.
13672 @table @asis
13673 @item @command{.}
13674 @c --------------
13675 @prindex @command{.}
13676 Use @command{.} only with regular files (use @samp{test -f}).  Bash
13677 2.03, for instance, chokes on @samp{. /dev/null}.  Remember that
13678 @command{.} uses @env{PATH} if its argument contains no slashes.  Also,
13679 some shells, including bash 3.2, implicitly append the current directory
13680 to this @env{PATH} search, even though Posix forbids it.  So if you want
13681 to use @command{.} on a file @file{foo} in the current directory, you
13682 must use @samp{. ./foo}.
13684 @item @command{!}
13685 @c --------------
13686 @prindex @command{!}
13687 The Unix version 7 shell did not support
13688 negating the exit status of commands with @command{!}, and this feature
13689 is still absent from some shells (e.g., Solaris @command{/bin/sh}).
13690 Shell code like this:
13692 @example
13693 if ! cmp file1 file2 >/dev/null 2>&1; then
13694   echo files differ or trouble
13696 @end example
13698 is therefore not portable in practice.  Typically it is easy to rewrite
13699 such code, e.g.:
13701 @example
13702 cmp file1 file2 >/dev/null 2>&1 ||
13703   echo files differ or trouble
13704 @end example
13706 More generally, one can always rewrite @samp{! @var{command}} as:
13708 @example
13709 if @var{command}; then (exit 1); else :; fi
13710 @end example
13713 @item @command{@{...@}}
13714 @c --------------------
13715 @prindex @command{@{...@}}
13716 Bash 3.2 (and earlier versions) sometimes does not properly set
13717 @samp{$?} when failing to write redirected output of a compound command.
13718 This problem is most commonly observed with @samp{@{@dots{}@}}; it does
13719 not occur with @samp{(@dots{})}.  For example:
13721 @example
13722 $ @kbd{bash -c '@{ echo foo; @} >/bad; echo $?'}
13723 bash: line 1: /bad: Permission denied
13725 $ @kbd{bash -c 'while :; do echo; done >/bad; echo $?'}
13726 bash: line 1: /bad: Permission denied
13728 @end example
13730 To work around the bug, prepend @samp{:;}:
13732 @example
13733 $ @kbd{bash -c ':;@{ echo foo; @} >/bad; echo $?'}
13734 bash: line 1: /bad: Permission denied
13736 @end example
13739 @item @command{break}
13740 @c ------------------
13741 @prindex @command{break}
13742 The use of @samp{break 2} etc.@: is safe.
13745 @item @command{case}
13746 @c -----------------
13747 @prindex @command{case}
13748 You don't need to quote the argument; no splitting is performed.
13750 You don't need the final @samp{;;}, but you should use it.
13752 Posix requires support for @code{case} patterns with opening
13753 parentheses like this:
13755 @example
13756 case $file_name in
13757 (*.c) echo "C source code";;
13758 esac
13759 @end example
13761 @noindent
13762 but the @code{(} in this example is not portable to many Bourne
13763 shell implementations.  It can be omitted safely.
13765 Zsh handles pattern fragments derived from parameter expansions or
13766 command substitutions as though quoted:
13768 @example
13769 $ pat=\?; case aa in ?$pat) echo match;; esac
13770 $ pat=\?; case a? in ?$pat) echo match;; esac
13771 match
13772 @end example
13774 @noindent
13775 Because of a bug in its @code{fnmatch}, Bash fails to properly
13776 handle backslashes in character classes:
13778 @example
13779 bash-2.02$ @kbd{case /tmp in [/\\]*) echo OK;; esac}
13780 bash-2.02$
13781 @end example
13783 @noindent
13784 This is extremely unfortunate, since you are likely to use this code to
13785 handle Posix or @sc{ms-dos} absolute file names.  To work around this
13786 bug, always put the backslash first:
13788 @example
13789 bash-2.02$ @kbd{case '\TMP' in [\\/]*) echo OK;; esac}
13791 bash-2.02$ @kbd{case /tmp in [\\/]*) echo OK;; esac}
13793 @end example
13795 Many Bourne shells cannot handle closing brackets in character classes
13796 correctly.
13798 Some shells also have problems with backslash escaping in case you do not want
13799 to match the backslash: both a backslash and the escaped character match this
13800 pattern.  To work around this, specify the character class in a variable, so
13801 that quote removal does not apply afterwards, and the special characters don't
13802 have to be backslash-escaped:
13804 @example
13805 $ @kbd{case '\' in [\<]) echo OK;; esac}
13807 $ @kbd{scanset='[<]'; case '\' in $scanset) echo OK;; esac}
13809 @end example
13811 Even with this, Solaris @command{ksh} matches a backslash if the set
13812 contains any
13813 of the characters @samp{|}, @samp{&}, @samp{(}, or @samp{)}.
13815 Conversely, Tru64 @command{ksh} (circa 2003) erroneously always matches
13816 a closing parenthesis if not specified in a character class:
13818 @example
13819 $ @kbd{case foo in *\)*) echo fail ;; esac}
13820 fail
13821 $ @kbd{case foo in *')'*) echo fail ;; esac}
13822 fail
13823 @end example
13825 Some shells, such as Ash 0.3.8, are confused by an empty
13826 @code{case}/@code{esac}:
13828 @example
13829 ash-0.3.8 $ @kbd{case foo in esac;}
13830 @error{}Syntax error: ";" unexpected (expecting ")")
13831 @end example
13833 Many shells still do not support parenthesized cases, which is a pity
13834 for those of us using tools that rely on balanced parentheses.  For
13835 instance, Solaris @command{/bin/sh}:
13837 @example
13838 $ @kbd{case foo in (foo) echo foo;; esac}
13839 @error{}syntax error: `(' unexpected
13840 @end example
13843 @item @command{cd}
13844 @c ---------------
13845 @prindex @command{cd}
13846 Posix 1003.1-2001 requires that @command{cd} must support
13847 the @option{-L} (``logical'') and @option{-P} (``physical'') options,
13848 with @option{-L} being the default.  However, traditional shells do
13849 not support these options, and their @command{cd} command has the
13850 @option{-P} behavior.
13852 Portable scripts should assume neither option is supported, and should
13853 assume neither behavior is the default.  This can be a bit tricky,
13854 since the Posix default behavior means that, for example,
13855 @samp{ls ..} and @samp{cd ..} may refer to different directories if
13856 the current logical directory is a symbolic link.  It is safe to use
13857 @command{cd @var{dir}} if @var{dir} contains no @file{..} components.
13858 Also, Autoconf-generated scripts check for this problem when computing
13859 variables like @code{ac_top_srcdir} (@pxref{Configuration Actions}),
13860 so it is safe to @command{cd} to these variables.
13862 See @xref{Special Shell Variables}, for portability problems involving
13863 @command{cd} and the @env{CDPATH} environment variable.
13864 Also please see the discussion of the @command{pwd} command.
13867 @item @command{echo}
13868 @c -----------------
13869 @prindex @command{echo}
13870 The simple @command{echo} is probably the most surprising source of
13871 portability troubles.  It is not possible to use @samp{echo} portably
13872 unless both options and escape sequences are omitted.  New applications
13873 which are not aiming at portability should use @samp{printf} instead of
13874 @samp{echo}.
13876 Don't expect any option.  @xref{Preset Output Variables}, @code{ECHO_N}
13877 etc.@: for a means to simulate @option{-n}.
13879 Do not use backslashes in the arguments, as there is no consensus on
13880 their handling.  For @samp{echo '\n' | wc -l}, the @command{sh} of
13881 Solaris outputs 2, but Bash and Zsh (in @command{sh} emulation mode) output 1.
13882 The problem is truly @command{echo}: all the shells
13883 understand @samp{'\n'} as the string composed of a backslash and an
13884 @samp{n}.
13886 Because of these problems, do not pass a string containing arbitrary
13887 characters to @command{echo}.  For example, @samp{echo "$foo"} is safe
13888 if you know that @var{foo}'s value cannot contain backslashes and cannot
13889 start with @samp{-}, but otherwise you should use a here-document like
13890 this:
13892 @example
13893 cat <<EOF
13894 $foo
13896 @end example
13899 @item @command{eval}
13900 @c -----------------
13901 @prindex @command{eval}
13902 The @command{eval} command is useful in limited circumstances, e.g.,
13903 using commands like @samp{eval table_$key=\$value} and @samp{eval
13904 value=table_$key} to simulate a hash table when the key is known to be
13905 alphanumeric.  However, @command{eval} is tricky to use on arbitrary
13906 arguments, even when it is implemented correctly.
13908 It is obviously unwise to use @samp{eval $cmd} if the string value of
13909 @samp{cmd} was derived from an untrustworthy source.  But even if the
13910 string value is valid, @samp{eval $cmd} might not work as intended,
13911 since it causes field splitting and file name expansion to occur twice,
13912 once for the @command{eval} and once for the command itself.  It is
13913 therefore safer to use @samp{eval "$cmd"}.  For example, if @var{cmd}
13914 has the value @samp{cat test?.c}, @samp{eval $cmd} might expand to the
13915 equivalent of @samp{cat test;.c} if there happens to be a file named
13916 @file{test;.c} in the current directory; and this in turn
13917 mistakenly attempts to invoke @command{cat} on the file @file{test} and
13918 then execute the command @command{.c}.  To avoid this problem, use
13919 @samp{eval "$cmd"} rather than @samp{eval $cmd}.
13921 However, suppose that you want to output the text of the evaluated
13922 command just before executing it.  Assuming the previous example,
13923 @samp{echo "Executing: $cmd"} outputs @samp{Executing: cat test?.c}, but
13924 this output doesn't show the user that @samp{test;.c} is the actual name
13925 of the copied file.  Conversely, @samp{eval "echo Executing: $cmd"}
13926 works on this example, but it fails with @samp{cmd='cat foo >bar'},
13927 since it mistakenly replaces the contents of @file{bar} by the
13928 string @samp{cat foo}.  No simple, general, and portable solution to
13929 this problem is known.
13931 You should also be wary of common bugs in @command{eval} implementations.
13932 In some shell implementations (e.g., older @command{ash}, Open@acronym{BSD} 3.8
13933 @command{sh}, @command{pdksh} v5.2.14 99/07/13.2, and @command{zsh}
13934 4.2.5), the arguments of @samp{eval} are evaluated in a context where
13935 @samp{$?} is 0, so they exhibit behavior like this:
13937 @example
13938 $ @kbd{false; eval 'echo $?'}
13940 @end example
13942 The correct behavior here is to output a nonzero value,
13943 but portable scripts should not rely on this.
13945 You should not rely on @code{LINENO} within @command{eval}.
13946 @xref{Special Shell Variables}.
13948 @item @command{exec}
13949 @c -----------------
13950 @prindex @command{exec}
13951 Posix describes several categories of shell built-ins.  Special
13952 built-ins (such as @command{exit}) must impact the environment of the
13953 current shell, and need not be available through @command{exec}.  All
13954 other built-ins are regular, and must not propagate variable assignments
13955 to the environment of the current shell.  However, the group of regular
13956 built-ins is further distinguished by commands that do not require a
13957 @env{PATH} search (such as @command{cd}), in contrast to built-ins that
13958 are offered as a more efficient version of something that must still be
13959 found in a @env{PATH} search (such as @command{echo}).  Posix is not
13960 clear on whether @command{exec} must work with the list of 17 utilities
13961 that are invoked without a @env{PATH} search, and many platforms lack an
13962 executable for some of those built-ins:
13964 @example
13965 $ @kbd{sh -c 'exec cd /tmp'}
13966 sh: line 0: exec: cd: not found
13967 @end example
13969 All other built-ins that provide utilities specified by Posix must have
13970 a counterpart executable that exists on @env{PATH}, although Posix
13971 allows @command{exec} to use the built-in instead of the executable.
13972 For example, contrast @command{bash} 3.2 and @command{pdksh} 5.2.14:
13974 @example
13975 $ @kbd{bash -c 'pwd --version' | head -n1}
13976 bash: line 0: pwd: --: invalid option
13977 pwd: usage: pwd [-LP]
13978 $ @kbd{bash -c 'exec pwd --version' | head -n1}
13979 pwd (GNU coreutils) 6.10
13980 $ @kbd{pdksh -c 'exec pwd --version' | head -n1}
13981 pdksh: pwd: --: unknown option
13982 @end example
13984 When it is desired to avoid a regular shell built-in, the workaround is
13985 to use some other forwarding command, such as @command{env} or
13986 @command{nice}, that will ensure a path search:
13988 @example
13989 $ @kbd{pdksh -c 'exec true --version' | head -n1}
13990 $ @kbd{pdksh -c 'nice true --version' | head -n1}
13991 true (GNU coreutils) 6.10
13992 $ @kbd{pdksh -c 'env true --version' | head -n1}
13993 true (GNU coreutils) 6.10
13994 @end example
13996 @item @command{exit}
13997 @c -----------------
13998 @prindex @command{exit}
13999 The default value of @command{exit} is supposed to be @code{$?};
14000 unfortunately, some shells, such as the @acronym{DJGPP} port of Bash 2.04, just
14001 perform @samp{exit 0}.
14003 @example
14004 bash-2.04$ @kbd{foo=`exit 1` || echo fail}
14005 fail
14006 bash-2.04$ @kbd{foo=`(exit 1)` || echo fail}
14007 fail
14008 bash-2.04$ @kbd{foo=`(exit 1); exit` || echo fail}
14009 bash-2.04$
14010 @end example
14012 Using @samp{exit $?} restores the expected behavior.
14014 Some shell scripts, such as those generated by @command{autoconf}, use a
14015 trap to clean up before exiting.  If the last shell command exited with
14016 nonzero status, the trap also exits with nonzero status so that the
14017 invoker can tell that an error occurred.
14019 Unfortunately, in some shells, such as Solaris @command{/bin/sh}, an exit
14020 trap ignores the @code{exit} command's argument.  In these shells, a trap
14021 cannot determine whether it was invoked by plain @code{exit} or by
14022 @code{exit 1}.  Instead of calling @code{exit} directly, use the
14023 @code{AC_MSG_ERROR} macro that has a workaround for this problem.
14026 @item @command{export}
14027 @c -------------------
14028 @prindex @command{export}
14029 The builtin @command{export} dubs a shell variable @dfn{environment
14030 variable}.  Each update of exported variables corresponds to an update
14031 of the environment variables.  Conversely, each environment variable
14032 received by the shell when it is launched should be imported as a shell
14033 variable marked as exported.
14035 Alas, many shells, such as Solaris @command{/bin/sh},
14036 @sc{irix} 6.3, @sc{irix} 5.2,
14037 @acronym{AIX} 4.1.5, and Digital Unix 4.0, forget to
14038 @command{export} the environment variables they receive.  As a result,
14039 two variables coexist: the environment variable and the shell
14040 variable.  The following code demonstrates this failure:
14042 @example
14043 #!/bin/sh
14044 echo $FOO
14045 FOO=bar
14046 echo $FOO
14047 exec /bin/sh $0
14048 @end example
14050 @noindent
14051 when run with @samp{FOO=foo} in the environment, these shells print
14052 alternately @samp{foo} and @samp{bar}, although they should print only
14053 @samp{foo} and then a sequence of @samp{bar}s.
14055 Therefore you should @command{export} again each environment variable
14056 that you update.
14059 @item @command{false}
14060 @c ------------------
14061 @prindex @command{false}
14062 Don't expect @command{false} to exit with status 1: in native
14063 Solaris @file{/bin/false} exits with status 255.
14066 @item @command{for}
14067 @c ----------------
14068 @prindex @command{for}
14069 To loop over positional arguments, use:
14071 @example
14072 for arg
14074   echo "$arg"
14075 done
14076 @end example
14078 @noindent
14079 You may @emph{not} leave the @code{do} on the same line as @code{for},
14080 since some shells improperly grok:
14082 @example
14083 for arg; do
14084   echo "$arg"
14085 done
14086 @end example
14088 If you want to explicitly refer to the positional arguments, given the
14089 @samp{$@@} bug (@pxref{Shell Substitutions}), use:
14091 @example
14092 for arg in $@{1+"$@@"@}; do
14093   echo "$arg"
14094 done
14095 @end example
14097 @noindent
14098 But keep in mind that Zsh, even in Bourne shell emulation mode, performs
14099 word splitting on @samp{$@{1+"$@@"@}}; see @ref{Shell Substitutions},
14100 item @samp{$@@}, for more.
14103 @item @command{if}
14104 @c ---------------
14105 @prindex @command{if}
14106 Using @samp{!} is not portable.  Instead of:
14108 @example
14109 if ! cmp -s file file.new; then
14110   mv file.new file
14112 @end example
14114 @noindent
14115 use:
14117 @example
14118 if cmp -s file file.new; then :; else
14119   mv file.new file
14121 @end example
14123 There are shells that do not reset the exit status from an @command{if}:
14125 @example
14126 $ @kbd{if (exit 42); then true; fi; echo $?}
14128 @end example
14130 @noindent
14131 whereas a proper shell should have printed @samp{0}.  This is especially
14132 bad in makefiles since it produces false failures.  This is why properly
14133 written makefiles, such as Automake's, have such hairy constructs:
14135 @example
14136 if test -f "$file"; then
14137   install "$file" "$dest"
14138 else
14139   :
14141 @end example
14144 @item @command{printf}
14145 @c ------------------
14146 @prindex @command{printf}
14147 A format string starting with a @samp{-} can cause problems.
14148 Bash interprets it as an option and
14149 gives an error.  And @samp{--} to mark the end of options is not good
14150 in the Net@acronym{BSD} Almquist shell (e.g., 0.4.6) which takes that
14151 literally as the format string.  Putting the @samp{-} in a @samp{%c}
14152 or @samp{%s} is probably easiest:
14154 @example
14155 printf %s -foo
14156 @end example
14158 Bash 2.03 mishandles an escape sequence that happens to evaluate to @samp{%}:
14160 @example
14161 $ @kbd{printf '\045'}
14162 bash: printf: `%': missing format character
14163 @end example
14165 Large outputs may cause trouble.  On Solaris 2.5.1 through 10, for
14166 example, @file{/usr/bin/printf} is buggy, so when using
14167 @command{/bin/sh} the command @samp{printf %010000x 123} normally dumps
14168 core.
14171 @item @command{read}
14172 @c ------------------
14173 @prindex @command{read}
14174 Not all shells support @option{-r} (Solaris @command{/bin/sh} for example).
14177 @item @command{pwd}
14178 @c ----------------
14179 @prindex @command{pwd}
14180 With modern shells, plain @command{pwd} outputs a ``logical''
14181 directory name, some of whose components may be symbolic links.  These
14182 directory names are in contrast to ``physical'' directory names, whose
14183 components are all directories.
14185 Posix 1003.1-2001 requires that @command{pwd} must support
14186 the @option{-L} (``logical'') and @option{-P} (``physical'') options,
14187 with @option{-L} being the default.  However, traditional shells do
14188 not support these options, and their @command{pwd} command has the
14189 @option{-P} behavior.
14191 Portable scripts should assume neither option is supported, and should
14192 assume neither behavior is the default.  Also, on many hosts
14193 @samp{/bin/pwd} is equivalent to @samp{pwd -P}, but Posix
14194 does not require this behavior and portable scripts should not rely on
14197 Typically it's best to use plain @command{pwd}.  On modern hosts this
14198 outputs logical directory names, which have the following advantages:
14200 @itemize @bullet
14201 @item
14202 Logical names are what the user specified.
14203 @item
14204 Physical names may not be portable from one installation
14205 host to another due to network file system gymnastics.
14206 @item
14207 On modern hosts @samp{pwd -P} may fail due to lack of permissions to
14208 some parent directory, but plain @command{pwd} cannot fail for this
14209 reason.
14210 @end itemize
14212 Also please see the discussion of the @command{cd} command.
14215 @item @command{set}
14216 @c ----------------
14217 @prindex @command{set}
14218 With the Free@acronym{BSD} 6.0 shell, the @command{set} command (without
14219 any options) does not sort its output.
14221 The @command{set} builtin faces the usual problem with arguments
14222 starting with a
14223 dash.  Modern shells such as Bash or Zsh understand @option{--} to specify
14224 the end of the options (any argument after @option{--} is a parameter,
14225 even @samp{-x} for instance), but many traditional shells (e.g., Solaris
14226 10 @command{/bin/sh}) simply stop option
14227 processing as soon as a non-option argument is found.  Therefore, use
14228 @samp{dummy} or simply @samp{x} to end the option processing, and use
14229 @command{shift} to pop it out:
14231 @example
14232 set x $my_list; shift
14233 @end example
14235 Avoid @samp{set -}, e.g., @samp{set - $my_list}.  Posix no
14236 longer requires support for this command, and in traditional shells
14237 @samp{set - $my_list} resets the @option{-v} and @option{-x} options, which
14238 makes scripts harder to debug.
14240 Some nonstandard shells do not recognize more than one option
14241 (e.g., @samp{set -e -x} assigns @samp{-x} to the command line).  It is
14242 better to combine them:
14244 @example
14245 set -ex
14246 @end example
14248 The @acronym{BSD} shell has had several problems with the @option{-e}
14249 option, partly because @acronym{BSD} @command{make} traditionally used
14250 @option{-e} even though this was incompatible with Posix
14251 (@pxref{Failure in Make Rules}).  Older versions of the @acronym{BSD}
14252 shell (circa 1990) mishandled @samp{&&}, @samp{||}, @samp{if}, and
14253 @samp{case} when @option{-e} was in effect, causing the shell to exit
14254 unexpectedly in some cases.  This was particularly a problem with
14255 makefiles, and led to circumlocutions like @samp{sh -c 'test -f file ||
14256 touch file'}, where the seemingly-unnecessary @samp{sh -c '@dots{}'}
14257 wrapper works around the bug.
14259 Even relatively-recent versions of the @acronym{BSD} shell (e.g.,
14260 Open@acronym{BSD} 3.4) wrongly exit with @option{-e} if a command within
14261 @samp{&&} fails inside a compound statement.  For example:
14263 @example
14264 #! /bin/sh
14265 set -e
14266 foo=''
14267 test -n "$foo" && exit 1
14268 echo one
14269 if :; then
14270   test -n "$foo" && exit 1
14272 echo two
14273 @end example
14275 @noindent
14276 does not print @samp{two}.  One workaround is to use @samp{if test -n
14277 "$foo"; then exit 1; fi} rather than @samp{test -n "$foo" && exit 1}.
14278 Another possibility is to warn @acronym{BSD} users not to use @samp{sh -e}.
14281 @item @command{shift}
14282 @c ------------------
14283 @prindex @command{shift}
14284 Not only is @command{shift}ing a bad idea when there is nothing left to
14285 shift, but in addition it is not portable: the shell of @acronym{MIPS
14286 RISC/OS} 4.52 refuses to do it.
14288 Don't use @samp{shift 2} etc.; it was not in the 7th Edition Bourne shell,
14289 and it is also absent in many pre-Posix shells.
14292 @item @command{source}
14293 @c -------------------
14294 @prindex @command{source}
14295 This command is not portable, as Posix does not require it; use
14296 @command{.} instead.
14299 @item @command{test}
14300 @c -----------------
14301 @prindex @command{test}
14302 The @code{test} program is the way to perform many file and string
14303 tests.  It is often invoked by the alternate name @samp{[}, but using
14304 that name in Autoconf code is asking for trouble since it is an M4 quote
14305 character.
14307 The @option{-a}, @option{-o}, @samp{(}, and @samp{)} operands are not
14308 portable and should be avoided.  Thus, portable uses of @command{test}
14309 should never have more than four arguments, and scripts should use shell
14310 constructs like @samp{&&} and @samp{||} instead.  If you combine
14311 @samp{&&} and @samp{||} in the same statement, keep in mind that they
14312 have equal precedence, so it is often better to parenthesize even when
14313 this is redundant.  For example:
14315 @smallexample
14316 # Not portable:
14317 test "X$a" = "X$b" -a \
14318   '(' "X$c" != "X$d" -o "X$e" = "X$f" ')'
14320 # Portable:
14321 test "X$a" = "X$b" &&
14322   @{ test "X$c" != "X$d" || test "X$e" = "X$f"; @}
14323 @end smallexample
14325 @command{test} does not process options like most other commands do; for
14326 example, it does not recognize the @option{--} argument as marking the
14327 end of options.
14329 It is safe to use @samp{!} as a @command{test} operator.  For example,
14330 @samp{if test ! -d foo; @dots{}} is portable even though @samp{if ! test
14331 -d foo; @dots{}} is not.
14334 @item @command{test} (files)
14335 @c -------------------------
14336 To enable @command{configure} scripts to support cross-compilation, they
14337 shouldn't do anything that tests features of the build system instead of
14338 the host system.  But occasionally you may find it necessary to check
14339 whether some arbitrary file exists.  To do so, use @samp{test -f} or
14340 @samp{test -r}.  Do not use @samp{test -x}, because 4.3@acronym{BSD} does not
14341 have it.  Do not use @samp{test -e} either, because Solaris @command{/bin/sh}
14342 lacks it.  To test for symbolic links on systems that have them, use
14343 @samp{test -h} rather than @samp{test -L}; either form conforms to
14344 Posix 1003.1-2001, but older shells like Solaris 8
14345 @code{/bin/sh} support only @option{-h}.
14347 @item @command{test} (strings)
14348 @c ---------------------------
14349 Posix says that @samp{test "@var{string}"} succeeds if @var{string} is
14350 not null, but this usage is not portable to traditional platforms like
14351 Solaris 10 @command{/bin/sh}, which mishandle strings like @samp{!} and
14352 @samp{-n}.
14354 Posix also says that @samp{test ! "@var{string}"},
14355 @samp{test -n "@var{string}"} and
14356 @samp{test -z "@var{string}"} work with any string, but many
14357 shells (such as Solaris, @acronym{AIX} 3.2, @sc{unicos} 10.0.0.6,
14358 Digital Unix 4, etc.)@: get confused if
14359 @var{string} looks like an operator:
14361 @example
14362 $ @kbd{test -n =}
14363 test: argument expected
14364 $ @kbd{test ! -n}
14365 test: argument expected
14366 @end example
14368 Similarly, Posix says that both @samp{test "@var{string1}" = "@var{string2"}}
14369 and @samp{test "@var{string1}" != "@var{string2"}} work for any pairs of
14370 strings, but in practice this is not true for troublesome strings that
14371 look like operators or parentheses, or that begin with @samp{-}.
14373 It is best to protect such strings with a leading @samp{X}, e.g.,
14374 @samp{test "X@var{string}" != X} rather than @samp{test -n
14375 "@var{string}"} or @samp{test ! "@var{string}"}.
14377 It is common to find variations of the following idiom:
14379 @example
14380 test -n "`echo $ac_feature | sed 's/[-a-zA-Z0-9_]//g'`" &&
14381   @var{action}
14382 @end example
14384 @noindent
14385 to take an action when a token matches a given pattern.  Such constructs
14386 should be avoided by using:
14388 @example
14389 case $ac_feature in
14390   *[!-a-zA-Z0-9_]*) @var{action};;
14391 esac
14392 @end example
14394 If the pattern is a complicated regular expression that cannot be
14395 expressed as a shell pattern, use something like this instead:
14397 @example
14398 expr "X$ac_feature" : 'X.*[^-a-zA-Z0-9_]' >/dev/null &&
14399   @var{action}
14400 @end example
14402 @samp{expr "X@var{foo}" : "X@var{bar}"} is more robust than @samp{echo
14403 "X@var{foo}" | grep "^X@var{bar}"}, because it avoids problems when
14404 @samp{@var{foo}} contains backslashes.
14407 @item @command{trap}
14408 @c -----------------
14409 @prindex @command{trap}
14410 It is safe to trap at least the signals 1, 2, 13, and 15.  You can also
14411 trap 0, i.e., have the @command{trap} run when the script ends (either via an
14412 explicit @command{exit}, or the end of the script).  The trap for 0 should be
14413 installed outside of a shell function, or @acronym{AIX} 5.3 @command{/bin/sh}
14414 will invoke the trap at the end of this function.
14416 Posix says that @samp{trap - 1 2 13 15} resets the traps for the
14417 specified signals to their default values, but many common shells (e.g.,
14418 Solaris @command{/bin/sh}) misinterpret this and attempt to execute a
14419 ``command'' named @command{-} when the specified conditions arise.
14420 There is no portable workaround, except for @samp{trap - 0}, for which
14421 @samp{trap '' 0} is a portable substitute.
14423 Although Posix is not absolutely clear on this point, it is widely
14424 admitted that when entering the trap @samp{$?} should be set to the exit
14425 status of the last command run before the trap.  The ambiguity can be
14426 summarized as: ``when the trap is launched by an @command{exit}, what is
14427 the @emph{last} command run: that before @command{exit}, or
14428 @command{exit} itself?''
14430 Bash considers @command{exit} to be the last command, while Zsh and
14431 Solaris @command{/bin/sh} consider that when the trap is run it is
14432 @emph{still} in the @command{exit}, hence it is the previous exit status
14433 that the trap receives:
14435 @example
14436 $ @kbd{cat trap.sh}
14437 trap 'echo $?' 0
14438 (exit 42); exit 0
14439 $ @kbd{zsh trap.sh}
14441 $ @kbd{bash trap.sh}
14443 @end example
14445 The portable solution is then simple: when you want to @samp{exit 42},
14446 run @samp{(exit 42); exit 42}, the first @command{exit} being used to
14447 set the exit status to 42 for Zsh, and the second to trigger the trap
14448 and pass 42 as exit status for Bash.
14450 The shell in Free@acronym{BSD} 4.0 has the following bug: @samp{$?} is
14451 reset to 0 by empty lines if the code is inside @command{trap}.
14453 @example
14454 $ @kbd{trap 'false}
14456 echo $?' 0
14457 $ @kbd{exit}
14459 @end example
14461 @noindent
14462 Fortunately, this bug only affects @command{trap}.
14464 @item @command{true}
14465 @c -----------------
14466 @prindex @command{true}
14467 @c Info cannot handle `:' in index entries.
14468 @c @prindex @command{:}
14469 Don't worry: as far as we know @command{true} is portable.
14470 Nevertheless, it's not always a builtin (e.g., Bash 1.x), and the
14471 portable shell community tends to prefer using @command{:}.  This has a
14472 funny side effect: when asked whether @command{false} is more portable
14473 than @command{true} Alexandre Oliva answered:
14475 @quotation
14476 In a sense, yes, because if it doesn't exist, the shell will produce an
14477 exit status of failure, which is correct for @command{false}, but not
14478 for @command{true}.
14479 @end quotation
14482 @item @command{unset}
14483 @c ------------------
14484 @prindex @command{unset}
14485 In some nonconforming shells (e.g., Bash 2.05a), @code{unset FOO} fails
14486 when @code{FOO} is not set.  Also, Bash 2.01 mishandles @code{unset
14487 MAIL} in some cases and dumps core.
14489 A few ancient shells lack @command{unset} entirely.  Nevertheless, because
14490 it is extremely useful to disable embarrassing variables such as
14491 @code{PS1}, you can test for its existence and use
14492 it @emph{provided} you give a neutralizing value when @command{unset} is
14493 not supported:
14495 @smallexample
14496 # "|| exit" suppresses any "Segmentation fault" message.
14497 if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; then
14498   unset=unset
14499 else
14500   unset=false
14502 $unset PS1 || PS1='$ '
14503 @end smallexample
14505 @noindent
14506 @xref{Special Shell Variables}, for some neutralizing values.  Also, see
14507 @ref{Limitations of Builtins}, documentation of @command{export}, for
14508 the case of environment variables.
14509 @end table
14511 @node Limitations of Usual Tools
14512 @section Limitations of Usual Tools
14513 @cindex Limitations of usual tools
14515 The small set of tools you can expect to find on any machine can still
14516 include some limitations you should be aware of.
14518 @table @asis
14519 @item Awk
14520 @c ------
14521 @prindex Awk
14522 Don't leave white space before the opening parenthesis in a user function call.
14523 Posix does not allow this and @acronym{GNU} Awk rejects it:
14525 @example
14526 $ @kbd{gawk 'function die () @{ print "Aaaaarg!"  @}
14527         BEGIN @{ die () @}'}
14528 gawk: cmd. line:2:         BEGIN @{ die () @}
14529 gawk: cmd. line:2:                      ^ parse error
14530 $ @kbd{gawk 'function die () @{ print "Aaaaarg!"  @}
14531         BEGIN @{ die() @}'}
14532 Aaaaarg!
14533 @end example
14535 Posix says that if a program contains only @samp{BEGIN} actions, and
14536 contains no instances of @code{getline}, then the program merely
14537 executes the actions without reading input.  However, traditional Awk
14538 implementations (such as Solaris 10 @command{awk}) read and discard
14539 input in this case.  Portable scripts can redirect input from
14540 @file{/dev/null} to work around the problem.  For example:
14542 @example
14543 awk 'BEGIN @{print "hello world"@}' </dev/null
14544 @end example
14546 Posix says that in an @samp{END} action, @samp{$NF} (and presumably,
14547 @samp{$1}) retain their value from the last record read, if no
14548 intervening @samp{getline} occurred.  However, some implementations
14549 (such as Solaris 10 @samp{/usr/bin/awk}, @samp{nawk}, or Darwin
14550 @samp{awk}) reset these variables.  A workaround is to use an
14551 intermediate variable prior to the @samp{END} block.  For example:
14553 @example
14554 $ @kbd{cat end.awk}
14555 @{ tmp = $1 @}
14556 END @{ print "a", $1, $NF, "b", tmp @}
14557 $ @kbd{echo 1 | awk -f end.awk}
14558 a   b 1
14559 $ @kbd{echo 1 | gawk -f end.awk}
14560 a 1 1 b 1
14561 @end example
14563 If you want your program to be deterministic, don't depend on @code{for}
14564 on arrays:
14566 @example
14567 $ @kbd{cat for.awk}
14568 END @{
14569   arr["foo"] = 1
14570   arr["bar"] = 1
14571   for (i in arr)
14572     print i
14574 $ @kbd{gawk -f for.awk </dev/null}
14577 $ @kbd{nawk -f for.awk </dev/null}
14580 @end example
14582 Some Awk implementations, such as @acronym{HP-UX} 11.0's native one,
14583 mishandle anchors:
14585 @example
14586 $ @kbd{echo xfoo | $AWK '/foo|^bar/ @{ print @}'}
14587 $ @kbd{echo bar | $AWK '/foo|^bar/ @{ print @}'}
14589 $ @kbd{echo xfoo | $AWK '/^bar|foo/ @{ print @}'}
14590 xfoo
14591 $ @kbd{echo bar | $AWK '/^bar|foo/ @{ print @}'}
14593 @end example
14595 @noindent
14596 Either do not depend on such patterns (i.e., use @samp{/^(.*foo|bar)/},
14597 or use a simple test to reject such implementations.
14599 On @samp{ia64-hp-hpux11.23}, Awk mishandles @code{printf} conversions
14600 after @code{%u}:
14602 @example
14603 $ @kbd{awk 'BEGIN @{ printf "%u %d\n", 0, -1 @}'}
14604 0 0
14605 @end example
14607 @acronym{AIX} version 5.2 has an arbitrary limit of 399 on the
14608 length of regular expressions and literal strings in an Awk program.
14610 Traditional Awk implementations derived from Unix version 7, such as
14611 Solaris @command{/bin/awk}, have many limitations and do not
14612 conform to Posix.  Nowadays @code{AC_PROG_AWK} (@pxref{Particular
14613 Programs}) finds you an Awk that doesn't have these problems, but if
14614 for some reason you prefer not to use @code{AC_PROG_AWK} you may need to
14615 address them.
14617 Traditional Awk does not support multidimensional arrays or user-defined
14618 functions.
14620 Traditional Awk does not support the @option{-v} option.  You can use
14621 assignments after the program instead, e.g., @command{$AWK '@{print v
14622 $1@}' v=x}; however, don't forget that such assignments are not
14623 evaluated until they are encountered (e.g., after any @code{BEGIN}
14624 action).
14626 Traditional Awk does not support the keywords @code{delete} or @code{do}.
14628 Traditional Awk does not support the expressions
14629 @code{@var{a}?@var{b}:@var{c}}, @code{!@var{a}}, @code{@var{a}^@var{b}},
14630 or @code{@var{a}^=@var{b}}.
14632 Traditional Awk does not support the predefined @code{CONVFMT} variable.
14634 Traditional Awk supports only the predefined functions @code{exp}, @code{index},
14635 @code{int}, @code{length}, @code{log}, @code{split}, @code{sprintf},
14636 @code{sqrt}, and @code{substr}.
14638 Traditional Awk @code{getline} is not at all compatible with Posix;
14639 avoid it.
14641 Traditional Awk has @code{for (i in a) @dots{}} but no other uses of the
14642 @code{in} keyword.  For example, it lacks @code{if (i in a) @dots{}}.
14644 In code portable to both traditional and modern Awk, @code{FS} must be a
14645 string containing just one ordinary character, and similarly for the
14646 field-separator argument to @code{split}.
14648 Traditional Awk has a limit of 99 fields in a record.  Since some Awk
14649 implementations, like Tru64's, split the input even if you don't refer
14650 to any field in the script, to circumvent this problem, set @samp{FS}
14651 to an unusual character and use @code{split}.
14653 Traditional Awk has a limit of at most 99 bytes in a number formatted by
14654 @code{OFMT}; for example, @code{OFMT="%.300e"; print 0.1;} typically
14655 dumps core.
14657 The original version of Awk had a limit of at most 99 bytes per
14658 @code{split} field, 99 bytes per @code{substr} substring, and 99 bytes
14659 per run of non-special characters in a @code{printf} format, but these
14660 bugs have been fixed on all practical hosts that we know of.
14662 @item @command{basename}
14663 @c ---------------------
14664 @prindex @command{basename}
14665 Not all hosts have a working @command{basename}.
14666 You can use @command{expr} instead.
14668 @c AS_BASENAME is to be replaced by a better API.
14669 @ignore
14670 Not all hosts have a working @command{basename}, and you should instead
14671 use @code{AS_BASENAME} (@pxref{Programming in M4sh}), followed by
14672 @command{expr} if you need to strip a suffix.  For example:
14674 @example
14675 a=`basename "$aname"`       # This is not portable.
14676 a=`AS_BASENAME(["$aname"])` # This is more portable.
14678 # This is not portable.
14679 c=`basename "$cname" .c`
14681 # This is more portable.
14682 c=`AS_BASENAME(["$cname"])`
14683 case $c in
14684 ?*.c) c=`expr "X$c" : 'X\(.*\)\.c'`;;
14685 esac
14686 @end example
14687 @end ignore
14690 @item @command{cat}
14691 @c ----------------
14692 @prindex @command{cat}
14693 Don't rely on any option.
14696 @item @command{cc}
14697 @c ---------------
14698 @prindex @command{cc}
14699 The command @samp{cc -c foo.c} traditionally produces an object file
14700 named @file{foo.o}.  Most compilers allow @option{-c} to be combined
14701 with @option{-o} to specify a different object file name, but
14702 Posix does not require this combination and a few compilers
14703 lack support for it.  @xref{C Compiler}, for how @acronym{GNU} Make
14704 tests for this feature with @code{AC_PROG_CC_C_O}.
14706 When a compilation such as @samp{cc -o foo foo.c} fails, some compilers
14707 (such as @sc{cds} on Reliant Unix) leave a @file{foo.o}.
14709 @acronym{HP-UX} @command{cc} doesn't accept @file{.S} files to preprocess and
14710 assemble.  @samp{cc -c foo.S} appears to succeed, but in fact does
14711 nothing.
14713 The default executable, produced by @samp{cc foo.c}, can be
14715 @itemize
14716 @item @file{a.out} --- usual Posix convention.
14717 @item @file{b.out} --- i960 compilers (including @command{gcc}).
14718 @item @file{a.exe} --- @acronym{DJGPP} port of @command{gcc}.
14719 @item @file{a_out.exe} --- GNV @command{cc} wrapper for DEC C on OpenVMS.
14720 @item @file{foo.exe} --- various MS-DOS compilers.
14721 @end itemize
14723 The C compiler's traditional name is @command{cc}, but other names like
14724 @command{gcc} are common.  Posix 1003.1-2001 specifies the
14725 name @command{c99}, but older Posix editions specified
14726 @command{c89} and anyway these standard names are rarely used in
14727 practice.  Typically the C compiler is invoked from makefiles that use
14728 @samp{$(CC)}, so the value of the @samp{CC} make variable selects the
14729 compiler name.
14732 @item @command{chmod}
14733 @c ------------------
14734 @prindex @command{chmod}
14735 Avoid usages like @samp{chmod -w file}; use @samp{chmod a-w file}
14736 instead, for two reasons.  First, plain @option{-w} does not necessarily
14737 make the file unwritable, since it does not affect mode bits that
14738 correspond to bits in the file mode creation mask.  Second,
14739 Posix says that the @option{-w} might be interpreted as an
14740 implementation-specific option, not as a mode; Posix suggests
14741 using @samp{chmod -- -w file} to avoid this confusion, but unfortunately
14742 @samp{--} does not work on some older hosts.
14745 @item @command{cmp}
14746 @c ----------------
14747 @prindex @command{cmp}
14748 @command{cmp} performs a raw data comparison of two files, while
14749 @command{diff} compares two text files.  Therefore, if you might compare
14750 DOS files, even if only checking whether two files are different, use
14751 @command{diff} to avoid spurious differences due to differences of
14752 newline encoding.
14755 @item @command{cp}
14756 @c ---------------
14757 @prindex @command{cp}
14758 Avoid the @option{-r} option, since Posix 1003.1-2004 marks it as
14759 obsolescent and its behavior on special files is implementation-defined.
14760 Use @option{-R} instead.  On @acronym{GNU} hosts the two options
14761 are equivalent, but on Solaris hosts (for example) @command{cp -r}
14762 reads from pipes instead of replicating them.
14764 Some @command{cp} implementations (e.g., @acronym{BSD/OS} 4.2) do not allow
14765 trailing slashes at the end of nonexistent destination directories.  To
14766 avoid this problem, omit the trailing slashes.  For example, use
14767 @samp{cp -R source /tmp/newdir} rather than @samp{cp -R source
14768 /tmp/newdir/} if @file{/tmp/newdir} does not exist.
14770 @c This is thanks to Ian.
14771 The ancient SunOS 4 @command{cp} does not support @option{-f}, although
14772 its @command{mv} does.
14774 @cindex timestamp resolution
14775 Traditionally, file timestamps had 1-second resolution, and @samp{cp
14776 -p} copied the timestamps exactly.  However, many modern file systems
14777 have timestamps with 1-nanosecond resolution.  Unfortunately, @samp{cp
14778 -p} implementations truncate timestamps when copying files, so this
14779 can result in the destination file appearing to be older than the
14780 source.  The exact amount of truncation depends on the resolution of
14781 the system calls that @command{cp} uses; traditionally this was
14782 @code{utime}, which has 1-second resolution, but some newer
14783 @command{cp} implementations use @code{utimes}, which has
14784 1-microsecond resolution.  These newer implementations include @acronym{GNU}
14785 Core Utilities 5.0.91 or later, and Solaris 8 (sparc) patch 109933-02 or
14786 later.  Unfortunately as of January 2006 there is still no system
14787 call to set timestamps to the full nanosecond resolution.
14789 Bob Proulx notes that @samp{cp -p} always @emph{tries} to copy
14790 ownerships.  But whether it actually does copy ownerships or not is a
14791 system dependent policy decision implemented by the kernel.  If the
14792 kernel allows it then it happens.  If the kernel does not allow it then
14793 it does not happen.  It is not something @command{cp} itself has control
14794 over.
14796 In Unix System V any user can chown files to any other user, and System
14797 V also has a non-sticky @file{/tmp}.  That probably derives from the
14798 heritage of System V in a business environment without hostile users.
14799 @acronym{BSD} changed this
14800 to be a more secure model where only root can @command{chown} files and
14801 a sticky @file{/tmp} is used.  That undoubtedly derives from the heritage
14802 of @acronym{BSD} in a campus environment.
14804 @acronym{GNU}/Linux and Solaris by default follow @acronym{BSD}, but
14805 can be configured to allow a System V style @command{chown}.  On the
14806 other hand, @acronym{HP-UX} follows System V, but can
14807 be configured to use the modern security model and disallow
14808 @command{chown}.  Since it is an administrator-configurable parameter
14809 you can't use the name of the kernel as an indicator of the behavior.
14813 @item @command{date}
14814 @c -----------------
14815 @prindex @command{date}
14816 Some versions of @command{date} do not recognize special @samp{%} directives,
14817 and unfortunately, instead of complaining, they just pass them through,
14818 and exit with success:
14820 @example
14821 $ @kbd{uname -a}
14822 OSF1 medusa.sis.pasteur.fr V5.1 732 alpha
14823 $ @kbd{date "+%s"}
14825 @end example
14828 @item @command{diff}
14829 @c -----------------
14830 @prindex @command{diff}
14831 Option @option{-u} is nonportable.
14833 Some implementations, such as Tru64's, fail when comparing to
14834 @file{/dev/null}.  Use an empty file instead.
14837 @item @command{dirname}
14838 @c --------------------
14839 @prindex @command{dirname}
14840 Not all hosts have a working @command{dirname}, and you should instead
14841 use @code{AS_DIRNAME} (@pxref{Programming in M4sh}).  For example:
14843 @example
14844 dir=`dirname "$file"`       # This is not portable.
14845 dir=`AS_DIRNAME(["$file"])` # This is more portable.
14846 @end example
14849 @item @command{egrep}
14850 @c ------------------
14851 @prindex @command{egrep}
14852 Posix 1003.1-2001 no longer requires @command{egrep},
14853 but many hosts do not yet support the Posix
14854 replacement @code{grep -E}.  Also, some traditional implementations do
14855 not work on long input lines.  To work around these problems, invoke
14856 @code{AC_PROG_EGREP} and then use @code{$EGREP}.
14858 Portable extended regular expressions should use @samp{\} only to escape
14859 characters in the string @samp{$()*+.?[\^@{|}.  For example, @samp{\@}}
14860 is not portable, even though it typically matches @samp{@}}.
14862 The empty alternative is not portable.  Use @samp{?} instead.  For
14863 instance with Digital Unix v5.0:
14865 @example
14866 > printf "foo\n|foo\n" | $EGREP '^(|foo|bar)$'
14867 |foo
14868 > printf "bar\nbar|\n" | $EGREP '^(foo|bar|)$'
14869 bar|
14870 > printf "foo\nfoo|\n|bar\nbar\n" | $EGREP '^(foo||bar)$'
14872 |bar
14873 @end example
14875 @command{$EGREP} also suffers the limitations of @command{grep}.
14877 @item @command{expr}
14878 @c -----------------
14879 @prindex @command{expr}
14880 No @command{expr} keyword starts with @samp{X}, so use @samp{expr
14881 X"@var{word}" : 'X@var{regex}'} to keep @command{expr} from
14882 misinterpreting @var{word}.
14884 Don't use @code{length}, @code{substr}, @code{match} and @code{index}.
14886 @item @command{expr} (@samp{|})
14887 @prindex @command{expr} (@samp{|})
14888 You can use @samp{|}.  Although Posix does require that @samp{expr
14889 ''} return the empty string, it does not specify the result when you
14890 @samp{|} together the empty string (or zero) with the empty string.  For
14891 example:
14893 @example
14894 expr '' \| ''
14895 @end example
14897 Posix 1003.2-1992 returns the empty string
14898 for this case, but traditional Unix returns @samp{0} (Solaris is
14899 one such example).  In Posix 1003.1-2001, the specification was
14900 changed to match traditional Unix's behavior (which is
14901 bizarre, but it's too late to fix this).  Please note that the same
14902 problem does arise when the empty string results from a computation,
14903 as in:
14905 @example
14906 expr bar : foo \| foo : bar
14907 @end example
14909 @noindent
14910 Avoid this portability problem by avoiding the empty string.
14913 @item @command{expr} (@samp{:})
14914 @c ----------------------------
14915 @prindex @command{expr}
14916 Portable @command{expr} regular expressions should use @samp{\} to
14917 escape only characters in the string @samp{$()*.0123456789[\^n@{@}}.
14918 For example, alternation, @samp{\|}, is common but Posix does not
14919 require its support, so it should be avoided in portable scripts.
14920 Similarly, @samp{\+} and @samp{\?} should be avoided.
14922 Portable @command{expr} regular expressions should not begin with
14923 @samp{^}.  Patterns are automatically anchored so leading @samp{^} is
14924 not needed anyway.
14926 The Posix standard is ambiguous as to whether
14927 @samp{expr 'a' : '\(b\)'} outputs @samp{0} or the empty string.
14928 In practice, it outputs the empty string on most platforms, but portable
14929 scripts should not assume this.  For instance, the @acronym{QNX} 4.25 native
14930 @command{expr} returns @samp{0}.
14932 One might think that a way to get a uniform behavior would be to use
14933 the empty string as a default value:
14935 @example
14936 expr a : '\(b\)' \| ''
14937 @end example
14939 @noindent
14940 Unfortunately this behaves exactly as the original expression; see the
14941 @command{expr} (@samp{|}) entry for more information.
14943 Some ancient @command{expr} implementations (e.g., SunOS 4 @command{expr} and
14944 Solaris 8 @command{/usr/ucb/expr}) have a silly length limit that causes
14945 @command{expr} to fail if the matched substring is longer than 120
14946 bytes.  In this case, you might want to fall back on @samp{echo|sed} if
14947 @command{expr} fails.  Nowadays this is of practical importance only for
14948 the rare installer who mistakenly puts @file{/usr/ucb} before
14949 @file{/usr/bin} in @env{PATH}.
14951 On Mac OS X 10.4, @command{expr} mishandles the pattern @samp{[^-]} in
14952 some cases.  For example, the command
14953 @example
14954 expr Xpowerpc-apple-darwin8.1.0 : 'X[^-]*-[^-]*-\(.*\)'
14955 @end example
14957 @noindent
14958 outputs @samp{apple-darwin8.1.0} rather than the correct @samp{darwin8.1.0}.
14959 This particular case can be worked around by substituting @samp{[^--]}
14960 for @samp{[^-]}.
14962 Don't leave, there is some more!
14964 The @acronym{QNX} 4.25 @command{expr}, in addition of preferring @samp{0} to
14965 the empty string, has a funny behavior in its exit status: it's always 1
14966 when parentheses are used!
14968 @example
14969 $ @kbd{val=`expr 'a' : 'a'`; echo "$?: $val"}
14970 0: 1
14971 $ @kbd{val=`expr 'a' : 'b'`; echo "$?: $val"}
14972 1: 0
14974 $ @kbd{val=`expr 'a' : '\(a\)'`; echo "?: $val"}
14975 1: a
14976 $ @kbd{val=`expr 'a' : '\(b\)'`; echo "?: $val"}
14977 1: 0
14978 @end example
14980 @noindent
14981 In practice this can be a big problem if you are ready to catch failures
14982 of @command{expr} programs with some other method (such as using
14983 @command{sed}), since you may get twice the result.  For instance
14985 @example
14986 $ @kbd{expr 'a' : '\(a\)' || echo 'a' | sed 's/^\(a\)$/\1/'}
14987 @end example
14989 @noindent
14990 outputs @samp{a} on most hosts, but @samp{aa} on @acronym{QNX} 4.25.  A
14991 simple workaround consists of testing @command{expr} and using a variable
14992 set to @command{expr} or to @command{false} according to the result.
14994 Tru64 @command{expr} incorrectly treats the result as a number, if it
14995 can be interpreted that way:
14997 @example
14998 $ @kbd{expr 00001 : '.*\(...\)'}
15000 @end example
15003 @item @command{fgrep}
15004 @c ------------------
15005 @prindex @command{fgrep}
15006 Posix 1003.1-2001 no longer requires @command{fgrep},
15007 but many hosts do not yet support the Posix
15008 replacement @code{grep -F}.  Also, some traditional implementations do
15009 not work on long input lines.  To work around these problems, invoke
15010 @code{AC_PROG_FGREP} and then use @code{$FGREP}.
15013 @item @command{find}
15014 @c -----------------
15015 @prindex @command{find}
15016 The option @option{-maxdepth} seems to be @acronym{GNU} specific.
15017 Tru64 v5.1, Net@acronym{BSD} 1.5 and Solaris @command{find}
15018 commands do not understand it.
15020 The replacement of @samp{@{@}} is guaranteed only if the argument is
15021 exactly @emph{@{@}}, not if it's only a part of an argument.  For
15022 instance on DU, and @acronym{HP-UX} 10.20 and @acronym{HP-UX} 11:
15024 @example
15025 $ @kbd{touch foo}
15026 $ @kbd{find . -name foo -exec echo "@{@}-@{@}" \;}
15027 @{@}-@{@}
15028 @end example
15030 @noindent
15031 while @acronym{GNU} @command{find} reports @samp{./foo-./foo}.
15034 @item @command{grep}
15035 @c -----------------
15036 @prindex @command{grep}
15037 Portable scripts can rely on the @command{grep} options @option{-c},
15038 @option{-l}, @option{-n}, and @option{-v}, but should avoid other
15039 options.  For example, don't use @option{-w}, as Posix does not require
15040 it and Irix 6.5.16m's @command{grep} does not support it.  Also,
15041 portable scripts should not combine @option{-c} with @option{-l},
15042 as Posix does not allow this.
15044 Some of the options required by Posix are not portable in practice.
15045 Don't use @samp{grep -q} to suppress output, because many @command{grep}
15046 implementations (e.g., Solaris) do not support @option{-q}.
15047 Don't use @samp{grep -s} to suppress output either, because Posix
15048 says @option{-s} does not suppress output, only some error messages;
15049 also, the @option{-s} option of traditional @command{grep} behaved
15050 like @option{-q} does in most modern implementations.  Instead,
15051 redirect the standard output and standard error (in case the file
15052 doesn't exist) of @code{grep} to @file{/dev/null}.  Check the exit
15053 status of @code{grep} to determine whether it found a match.
15055 Some traditional @command{grep} implementations do not work on long
15056 input lines.  On AIX the default @code{grep} silently truncates long
15057 lines on the input before matching.
15059 Also, many implementations do not support multiple regexps
15060 with @option{-e}: they either reject @option{-e} entirely (e.g., Solaris)
15061 or honor only the last pattern (e.g., @acronym{IRIX} 6.5 and NeXT).  To
15062 work around these problems, invoke @code{AC_PROG_GREP} and then use
15063 @code{$GREP}.
15065 Another possible workaround for the multiple @option{-e} problem is to
15066 separate the patterns by newlines, for example:
15068 @example
15069 grep 'foo
15070 bar' in.txt
15071 @end example
15073 @noindent
15074 except that this fails with traditional @command{grep}
15075 implementations and with Open@acronym{BSD} 3.8 @command{grep}.
15077 Traditional @command{grep} implementations (e.g., Solaris) do not
15078 support the @option{-E} or @option{-F} options.  To work around these
15079 problems, invoke @code{AC_PROG_EGREP} and then use @code{$EGREP}, and
15080 similarly for @code{AC_PROG_FGREP} and @code{$FGREP}.  Even if you are
15081 willing to require support for Posix @command{grep}, your script should
15082 not use both @option{-E} and @option{-F}, since Posix does not allow
15083 this combination.
15085 Portable @command{grep} regular expressions should use @samp{\} only to
15086 escape characters in the string @samp{$()*.0123456789[\^@{@}}.  For example,
15087 alternation, @samp{\|}, is common but Posix does not require its
15088 support in basic regular expressions, so it should be avoided in
15089 portable scripts.  Solaris and HP-UX @command{grep} do not support it.
15090 Similarly, the following escape sequences should also be avoided:
15091 @samp{\<}, @samp{\>}, @samp{\+}, @samp{\?}, @samp{\`}, @samp{\'},
15092 @samp{\B}, @samp{\b}, @samp{\S}, @samp{\s}, @samp{\W}, and @samp{\w}.
15094 Posix does not specify the behavior of @command{grep} on binary files.
15095 An example where this matters is using @acronym{BSD} @command{grep} to
15096 search text that includes embedded @acronym{ANSI} escape sequences for
15097 colored output to terminals (@samp{\033[m} is the sequence to restore
15098 normal output); the behavior depends on whether input is seekable:
15100 @example
15101 $ @kbd{printf 'esc\033[mape\n' > sample}
15102 $ @kbd{grep . sample}
15103 Binary file sample matches
15104 $ @kbd{cat sample | grep .}
15105 escape
15106 @end example
15109 @item @command{join}
15110 @c -----------------
15111 @prindex @command{join}
15112 Solaris 8 @command{join} has bugs when the second operand is standard
15113 input, and when standard input is a pipe.  For example, the following
15114 shell script causes Solaris 8 @command{join} to loop forever:
15116 @example
15117 cat >file <<'EOF'
15118 1 x
15119 2 y
15121 cat file | join file -
15122 @end example
15124 Use @samp{join - file} instead.
15127 @item @command{ln}
15128 @c ---------------
15129 @prindex @command{ln}
15130 @cindex Symbolic links
15131 Don't rely on @command{ln} having a @option{-f} option.  Symbolic links
15132 are not available on old systems; use @samp{$(LN_S)} as a portable substitute.
15134 For versions of the @acronym{DJGPP} before 2.04,
15135 @command{ln} emulates symbolic links
15136 to executables by generating a stub that in turn calls the real
15137 program.  This feature also works with nonexistent files like in the
15138 Posix spec.  So @samp{ln -s file link} generates @file{link.exe},
15139 which attempts to call @file{file.exe} if run.  But this feature only
15140 works for executables, so @samp{cp -p} is used instead for these
15141 systems.  @acronym{DJGPP} versions 2.04 and later have full support
15142 for symbolic links.
15145 @item @command{ls}
15146 @c ---------------
15147 @prindex @command{ls}
15148 @cindex Listing directories
15149 The portable options are @option{-acdilrtu}.  Current practice is for
15150 @option{-l} to output both owner and group, even though ancient versions
15151 of @command{ls} omitted the group.
15153 On ancient hosts, @samp{ls foo} sent the diagnostic @samp{foo not found}
15154 to standard output if @file{foo} did not exist.  Hence a shell command
15155 like @samp{sources=`ls *.c 2>/dev/null`} did not always work, since it
15156 was equivalent to @samp{sources='*.c not found'} in the absence of
15157 @samp{.c} files.  This is no longer a practical problem, since current
15158 @command{ls} implementations send diagnostics to standard error.
15160 @item @command{mkdir}
15161 @c ------------------
15162 @prindex @command{mkdir}
15163 @cindex Making directories
15164 No @command{mkdir} option is portable to older systems.  Instead of
15165 @samp{mkdir -p @var{file-name}}, you should use
15166 @code{AS_MKDIR_P(@var{file-name})} (@pxref{Programming in M4sh})
15167 or @code{AC_PROG_MKDIR_P} (@pxref{Particular Programs}).
15169 Combining the @option{-m} and @option{-p} options, as in @samp{mkdir -m
15170 go-w -p @var{dir}}, often leads to trouble.  Free@acronym{BSD}
15171 @command{mkdir} incorrectly attempts to change the permissions of
15172 @var{dir} even if it already exists.  @acronym{HP-UX} 11.23 and
15173 @acronym{IRIX} 6.5 @command{mkdir} often assign the wrong permissions to
15174 any newly-created parents of @var{dir}.
15176 Posix does not clearly specify whether @samp{mkdir -p foo}
15177 should succeed when @file{foo} is a symbolic link to an already-existing
15178 directory.  The @acronym{GNU} Core Utilities 5.1.0 @command{mkdir}
15179 succeeds, but Solaris @command{mkdir} fails.
15181 Traditional @code{mkdir -p} implementations suffer from race conditions.
15182 For example, if you invoke @code{mkdir -p a/b} and @code{mkdir -p a/c}
15183 at the same time, both processes might detect that @file{a} is missing,
15184 one might create @file{a}, then the other might try to create @file{a}
15185 and fail with a @code{File exists} diagnostic.  The @acronym{GNU} Core
15186 Utilities (@samp{fileutils} version 4.1), Free@acronym{BSD} 5.0,
15187 Net@acronym{BSD} 2.0.2, and Open@acronym{BSD} 2.4 are known to be
15188 race-free when two processes invoke @code{mkdir -p} simultaneously, but
15189 earlier versions are vulnerable.  Solaris @command{mkdir} is still
15190 vulnerable as of Solaris 10, and other traditional Unix systems are
15191 probably vulnerable too.  This possible race is harmful in parallel
15192 builds when several Make rules call @code{mkdir -p} to
15193 construct directories.  You may use
15194 @code{install-sh -d} as a safe replacement, provided this script is
15195 recent enough; the copy shipped with Autoconf 2.60 and Automake 1.10 is
15196 OK, but copies from older versions are vulnerable.
15199 @item @command{mktemp}
15200 @c -------------------
15201 @prindex @command{mktemp}
15202 @cindex Creating temporary files
15203 Shell scripts can use temporary files safely with @command{mktemp}, but
15204 it does not exist on all systems.  A portable way to create a safe
15205 temporary file name is to create a temporary directory with mode 700 and
15206 use a file inside this directory.  Both methods prevent attackers from
15207 gaining control, though @command{mktemp} is far less likely to fail
15208 gratuitously under attack.
15210 Here is sample code to create a new temporary directory safely:
15212 @example
15213 # Create a temporary directory $tmp in $TMPDIR (default /tmp).
15214 # Use mktemp if possible; otherwise fall back on mkdir,
15215 # with $RANDOM to make collisions less likely.
15216 : $@{TMPDIR=/tmp@}
15218   tmp=`
15219     (umask 077 && mktemp -d "$TMPDIR/fooXXXXXX") 2>/dev/null
15220   ` &&
15221   test -n "$tmp" && test -d "$tmp"
15222 @} || @{
15223   tmp=$TMPDIR/foo$$-$RANDOM
15224   (umask 077 && mkdir "$tmp")
15225 @} || exit $?
15226 @end example
15229 @item @command{mv}
15230 @c ---------------
15231 @prindex @command{mv}
15232 @cindex Moving open files
15233 The only portable options are @option{-f} and @option{-i}.
15235 Moving individual files between file systems is portable (it was in Unix
15236 version 6),
15237 but it is not always atomic: when doing @samp{mv new existing}, there's
15238 a critical section where neither the old nor the new version of
15239 @file{existing} actually exists.
15241 On some systems moving files from @file{/tmp} can sometimes cause
15242 undesirable (but perfectly valid) warnings, even if you created these
15243 files.  This is because @file{/tmp} belongs to a group that ordinary
15244 users are not members of, and files created in @file{/tmp} inherit
15245 the group of @file{/tmp}.  When the file is copied, @command{mv} issues
15246 a diagnostic without failing:
15248 @smallexample
15249 $ @kbd{touch /tmp/foo}
15250 $ @kbd{mv /tmp/foo .}
15251 @error{}mv: ./foo: set owner/group (was: 100/0): Operation not permitted
15252 $ @kbd{echo $?}
15254 $ @kbd{ls foo}
15256 @end smallexample
15258 @noindent
15259 This annoying behavior conforms to Posix, unfortunately.
15261 Moving directories across mount points is not portable, use @command{cp}
15262 and @command{rm}.
15264 @acronym{DOS} variants cannot rename or remove open files, and do not
15265 support commands like @samp{mv foo bar >foo}, even though this is
15266 perfectly portable among Posix hosts.
15269 @item @command{od}
15270 @c ---------------
15271 @prindex @command{od}
15273 In Mac OS X 10.3, @command{od} does not support the
15274 standard Posix options @option{-A}, @option{-j}, @option{-N}, or
15275 @option{-t}, or the @acronym{XSI} option @option{-s}.  The only
15276 supported Posix option is @option{-v}, and the only supported
15277 @acronym{XSI} options are those in @option{-bcdox}.  The @acronym{BSD}
15278 @command{hexdump} program can be used instead.
15280 This problem no longer exists in Mac OS X 10.4.3.
15283 @item @command{rm}
15284 @c ---------------
15285 @prindex @command{rm}
15286 The @option{-f} and @option{-r} options are portable.
15288 It is not portable to invoke @command{rm} without operands.  For
15289 example, on many systems @samp{rm -f -r} (with no other arguments)
15290 silently succeeds without doing anything, but it fails with a diagnostic
15291 on Net@acronym{BSD} 2.0.2.
15293 A file might not be removed even if its parent directory is writable
15294 and searchable.  Many Posix hosts cannot remove a mount point, a named
15295 stream, a working directory, or a last link to a file that is being
15296 executed.
15298 @acronym{DOS} variants cannot rename or remove open files, and do not
15299 support commands like @samp{rm foo >foo}, even though this is
15300 perfectly portable among Posix hosts.
15303 @item @command{sed}
15304 @c ----------------
15305 @prindex @command{sed}
15306 Patterns should not include the separator (unless escaped), even as part
15307 of a character class.  In conformance with Posix, the Cray
15308 @command{sed} rejects @samp{s/[^/]*$//}: use @samp{s,[^/]*$,,}.
15310 Avoid empty patterns within parentheses (i.e., @samp{\(\)}).  Posix does
15311 not require support for empty patterns, and Unicos 9 @command{sed} rejects
15312 them.
15314 Unicos 9 @command{sed} loops endlessly on patterns like @samp{.*\n.*}.
15316 Sed scripts should not use branch labels longer than 7 characters and
15317 should not contain comments.  @acronym{HP-UX} sed has a limit of 99 commands
15318 (not counting @samp{:} commands) and
15319 48 labels, which can not be circumvented by using more than one script
15320 file.  It can execute up to 19 reads with the @samp{r} command per cycle.
15321 Solaris @command{/usr/ucb/sed} rejects usages that exceed an limit of
15322 about 6000 bytes for the internal representation of commands.
15324 Avoid redundant @samp{;}, as some @command{sed} implementations, such as
15325 Net@acronym{BSD} 1.4.2's, incorrectly try to interpret the second
15326 @samp{;} as a command:
15328 @example
15329 $ @kbd{echo a | sed 's/x/x/;;s/x/x/'}
15330 sed: 1: "s/x/x/;;s/x/x/": invalid command code ;
15331 @end example
15333 Input should not have unreasonably long lines, since some @command{sed}
15334 implementations have an input buffer limited to 4000 bytes.
15336 Portable @command{sed} regular expressions should use @samp{\} only to escape
15337 characters in the string @samp{$()*.0123456789[\^n@{@}}.  For example,
15338 alternation, @samp{\|}, is common but Posix does not require its
15339 support, so it should be avoided in portable scripts.  Solaris
15340 @command{sed} does not support alternation; e.g., @samp{sed '/a\|b/d'}
15341 deletes only lines that contain the literal string @samp{a|b}.
15342 Similarly, @samp{\+} and @samp{\?} should be avoided.
15344 Anchors (@samp{^} and @samp{$}) inside groups are not portable.
15346 Nested parentheses in patterns (e.g., @samp{\(\(a*\)b*)\)}) are
15347 quite portable to current hosts, but was not supported by some ancient
15348 @command{sed} implementations like SVR3.
15350 Some @command{sed} implementations, e.g., Solaris,
15351 restrict the special role of the asterisk to one-character regular expressions.
15352 This may lead to unexpected behavior:
15354 @example
15355 $ @kbd{echo '1*23*4' | /usr/bin/sed 's/\(.\)*/x/g'}
15356 x2x4
15357 $ @kbd{echo '1*23*4' | /usr/xpg4/bin/sed 's/\(.\)*/x/g'}
15359 @end example
15361 The @option{-e} option is mostly portable.
15362 However, its argument
15363 cannot start with @samp{a}, @samp{c}, or @samp{i},
15364 as this runs afoul of a Tru64 5.1 bug.
15365 Also, its argument cannot be empty, as this fails on @acronym{AIX} 5.3.
15366 Some people prefer to use @samp{-e}:
15368 @example
15369 sed -e '@var{command-1}' \
15370     -e '@var{command-2}'
15371 @end example
15373 @noindent
15374 as opposed to the equivalent:
15376 @example
15377 sed '
15378   @var{command-1}
15379   @var{command-2}
15381 @end example
15383 @noindent
15384 The following usage is sometimes equivalent:
15386 @example
15387 sed '@var{command-1};@var{command-2}'
15388 @end example
15390 but Posix says that this use of a semicolon has undefined effect if
15391 @var{command-1}'s verb is @samp{@{}, @samp{a}, @samp{b}, @samp{c},
15392 @samp{i}, @samp{r}, @samp{t}, @samp{w}, @samp{:}, or @samp{#}, so you
15393 should use semicolon only with simple scripts that do not use these
15394 verbs.
15396 Commands inside @{ @} brackets are further restricted.  Posix says that
15397 they cannot be preceded by addresses, @samp{!}, or @samp{;}, and that
15398 each command must be followed immediately by a newline, without any
15399 intervening blanks or semicolons.  The closing bracket must be alone on
15400 a line, other than white space preceding or following it.
15402 Contrary to yet another urban legend, you may portably use @samp{&} in
15403 the replacement part of the @code{s} command to mean ``what was
15404 matched''.  All descendants of Unix version 7 @command{sed}
15405 (at least; we
15406 don't have first hand experience with older @command{sed} implementations) have
15407 supported it.
15409 Posix requires that you must not have any white space between
15410 @samp{!} and the following command.  It is OK to have blanks between
15411 the address and the @samp{!}.  For instance, on Solaris:
15413 @example
15414 $ @kbd{echo "foo" | sed -n '/bar/ ! p'}
15415 @error{}Unrecognized command: /bar/ ! p
15416 $ @kbd{echo "foo" | sed -n '/bar/! p'}
15417 @error{}Unrecognized command: /bar/! p
15418 $ @kbd{echo "foo" | sed -n '/bar/ !p'}
15420 @end example
15422 Posix also says that you should not combine @samp{!} and @samp{;}.  If
15423 you use @samp{!}, it is best to put it on a command that is delimited by
15424 newlines rather than @samp{;}.
15426 Also note that Posix requires that the @samp{b}, @samp{t}, @samp{r}, and
15427 @samp{w} commands be followed by exactly one space before their argument.
15428 On the other hand, no white space is allowed between @samp{:} and the
15429 subsequent label name.
15431 If a sed script is specified on the command line and ends in an
15432 @samp{a}, @samp{c}, or @samp{i} command, the last line of inserted text
15433 should be followed by a newline.  Otherwise some @command{sed}
15434 implementations (e.g., Open@acronym{BSD} 3.9) do not append a newline to the
15435 inserted text.
15437 Many @command{sed} implementations (e.g., MacOS X 10.4,
15438 Open@acronym{BSD} 3.9, Solaris 10
15439 @command{/usr/ucb/sed}) strip leading white space from the text of
15440 @samp{a}, @samp{c}, and @samp{i} commands.  Prepend a backslash to
15441 work around this incompatibility with Posix:
15443 @example
15444 $ @kbd{echo flushleft | sed 'a\}
15445 > @kbd{   indented}
15446 > @kbd{'}
15447 flushleft
15448 indented
15449 $ @kbd{echo foo | sed 'a\}
15450 > @kbd{\   indented}
15451 > @kbd{'}
15452 flushleft
15453    indented
15454 @end example
15456 Posix requires that with an empty regular expression, the last non-empty
15457 regular expression from either an address specification or substitution
15458 command is applied.  However, busybox 1.6.1 complains when using a
15459 substitution command with a replacement containing a back-reference to
15460 an empty regular expression; the workaround is repeating the regular
15461 expression.
15463 @example
15464 $ @kbd{echo abc | busybox sed '/a\(b\)c/ s//\1/'}
15465 sed: No previous regexp.
15466 $ @kbd{echo abc | busybox sed '/a\(b\)c/ s/a\(b\)c/\1/'}
15468 @end example
15471 @item @command{sed} (@samp{t})
15472 @c ---------------------------
15473 @prindex @command{sed} (@samp{t})
15474 Some old systems have @command{sed} that ``forget'' to reset their
15475 @samp{t} flag when starting a new cycle.  For instance on @acronym{MIPS
15476 RISC/OS}, and on @sc{irix} 5.3, if you run the following @command{sed}
15477 script (the line numbers are not actual part of the texts):
15479 @example
15480 s/keep me/kept/g  # a
15481 t end             # b
15482 s/.*/deleted/g    # c
15483 :end              # d
15484 @end example
15486 @noindent
15489 @example
15490 delete me         # 1
15491 delete me         # 2
15492 keep me           # 3
15493 delete me         # 4
15494 @end example
15496 @noindent
15497 you get
15499 @example
15500 deleted
15501 delete me
15502 kept
15503 deleted
15504 @end example
15506 @noindent
15507 instead of
15509 @example
15510 deleted
15511 deleted
15512 kept
15513 deleted
15514 @end example
15516 Why?  When processing line 1, (c) matches, therefore sets the @samp{t}
15517 flag, and the output is produced.  When processing
15518 line 2, the @samp{t} flag is still set (this is the bug).  Command (a)
15519 fails to match, but @command{sed} is not supposed to clear the @samp{t}
15520 flag when a substitution fails.  Command (b) sees that the flag is set,
15521 therefore it clears it, and jumps to (d), hence you get @samp{delete me}
15522 instead of @samp{deleted}.  When processing line (3), @samp{t} is clear,
15523 (a) matches, so the flag is set, hence (b) clears the flags and jumps.
15524 Finally, since the flag is clear, line 4 is processed properly.
15526 There are two things one should remember about @samp{t} in @command{sed}.
15527 Firstly, always remember that @samp{t} jumps if @emph{some} substitution
15528 succeeded, not only the immediately preceding substitution.  Therefore,
15529 always use a fake @samp{t clear} followed by a @samp{:clear} on the next
15530 line, to reset the @samp{t} flag where needed.
15532 Secondly, you cannot rely on @command{sed} to clear the flag at each new
15533 cycle.
15535 One portable implementation of the script above is:
15537 @example
15538 t clear
15539 :clear
15540 s/keep me/kept/g
15541 t end
15542 s/.*/deleted/g
15543 :end
15544 @end example
15546 @item @command{touch}
15547 @c ------------------
15548 @prindex @command{touch}
15549 @cindex timestamp resolution
15550 If you specify the desired timestamp (e.g., with the @option{-r}
15551 option), @command{touch} typically uses the @code{utime} or
15552 @code{utimes} system call, which can result in the same kind of
15553 timestamp truncation problems that @samp{cp -p} has.
15555 On ancient @acronym{BSD} systems, @command{touch} or any command that
15556 results in an empty file does not update the timestamps, so use a
15557 command like @command{echo} as a workaround.
15558 Also,
15559 @acronym{GNU} @command{touch} 3.16r (and presumably all before that)
15560 fails to work on SunOS 4.1.3 when the empty file is on an
15561 @acronym{NFS}-mounted 4.2 volume.
15562 However, these problems are no longer of practical concern.
15564 @end table
15567 @node Portable Make
15568 @chapter Portable Make Programming
15569 @prindex @command{make}
15570 @cindex Limitations of @command{make}
15572 Writing portable makefiles is an art.  Since a makefile's commands are
15573 executed by the shell, you must consider the shell portability issues
15574 already mentioned.  However, other issues are specific to @command{make}
15575 itself.
15577 @menu
15578 * $< in Ordinary Make Rules::   $< in ordinary rules
15579 * Failure in Make Rules::       Failing portably in rules
15580 * Special Chars in Names::      Special Characters in Macro Names
15581 * Backslash-Newline-Newline::   Empty last lines in macro definitions
15582 * Backslash-Newline Comments::  Spanning comments across line boundaries
15583 * Long Lines in Makefiles::     Line length limitations
15584 * Macros and Submakes::         @code{make macro=value} and submakes
15585 * The Make Macro MAKEFLAGS::    @code{$(MAKEFLAGS)} portability issues
15586 * The Make Macro SHELL::        @code{$(SHELL)} portability issues
15587 * Comments in Make Rules::      Other problems with Make comments
15588 * obj/ and Make::               Don't name a subdirectory @file{obj}
15589 * make -k Status::              Exit status of @samp{make -k}
15590 * VPATH and Make::              @code{VPATH} woes
15591 * Single Suffix Rules::         Single suffix rules and separated dependencies
15592 * Timestamps and Make::         Subsecond timestamp resolution
15593 @end menu
15595 @node $< in Ordinary Make Rules
15596 @section @code{$<} in Ordinary Make Rules
15598 Posix says that the @samp{$<} construct in makefiles can be
15599 used only in inference rules and in the @samp{.DEFAULT} rule; its
15600 meaning in ordinary rules is unspecified.  Solaris @command{make}
15601 for instance replaces it with the empty string.  Open@acronym{BSD} (3.0 and
15602 later) @command{make} diagnoses these uses and errors out.
15604 @node Failure in Make Rules
15605 @section Failure in Make Rules
15607 Since 1992 Posix has required that @command{make} must invoke
15608 each command with the equivalent of a @samp{sh -c} subshell.  However,
15609 many @command{make} implementations, including @acronym{BSD} make through 2004,
15610 use @samp{sh -e -c} instead, and the @option{-e} option causes the
15611 subshell to exit immediately if a subsidiary simple-command fails.  For
15612 example, the command @samp{touch T; rm -f U} always attempts to
15613 remove @file{U} with Posix make, but incompatible
15614 @command{make} implementations skip the @command{rm} if the
15615 @command{touch} fails.  One way to work around this is to reword the
15616 affected simple-commands so that they always succeed, e.g., @samp{touch
15617 T || :; rm -f U}.
15618 However, even this approach can run into common bugs in @acronym{BSD}
15619 implementations of the @option{-e} option of @command{sh} and
15620 @command{set} (@pxref{Limitations of Builtins}), so if you are worried
15621 about porting to buggy @acronym{BSD} shells it may be simpler to migrate
15622 complicated @command{make} actions into separate scripts.
15624 @node Special Chars in Names
15625 @section Special Characters in Make Macro Names
15627 Posix limits macro names to nonempty strings containing only
15628 @acronym{ASCII} letters and digits, @samp{.}, and @samp{_}.  Many
15629 @command{make} implementations allow a wider variety of characters, but
15630 portable makefiles should avoid them.  It is portable to start a name
15631 with a special character, e.g., @samp{$(.FOO)}.
15633 Some ancient @command{make} implementations don't support leading
15634 underscores in macro names.  An example is @acronym{NEWS-OS} 4.2R.
15636 @example
15637 $ @kbd{cat Makefile}
15638 _am_include = #
15639 _am_quote =
15640 all:; @@echo this is test
15641 $ @kbd{make}
15642 Make: Must be a separator on rules line 2.  Stop.
15643 $ @kbd{cat Makefile2}
15644 am_include = #
15645 am_quote =
15646 all:; @@echo this is test
15647 $ @kbd{make -f Makefile2}
15648 this is test
15649 @end example
15651 @noindent
15652 However, this problem is no longer of practical concern.
15654 @node Backslash-Newline-Newline
15655 @section Backslash-Newline-Newline in Make Macro Values
15657 @c  This has been seen on ia64 hpux 11.20, and on one hppa hpux 10.20,
15658 @c  but another hppa hpux 10.20 didn't have it.  Bob Proulx
15659 @c  <bob@proulx.com> thinks it was in hpux 8.0 too.
15660 On some versions of @acronym{HP-UX}, @command{make} reads multiple newlines
15661 following a backslash, continuing to the next non-empty line.  For
15662 example,
15664 @example
15665 FOO = one \
15667 BAR = two
15669 test:
15670         : FOO is "$(FOO)"
15671         : BAR is "$(BAR)"
15672 @end example
15674 @noindent
15675 shows @code{FOO} equal to @code{one BAR = two}.  Other implementations
15676 sensibly let a backslash continue only to the immediately following
15677 line.
15679 @node Backslash-Newline Comments
15680 @section Backslash-Newline in Make Comments
15682 According to Posix, Make comments start with @code{#}
15683 and continue until an unescaped newline is reached.
15685 @example
15686 $ @kbd{cat Makefile}
15687 # A = foo \
15688       bar \
15689       baz
15691 all:
15692         @@echo ok
15693 $ @kbd{make}   # GNU make
15695 @end example
15697 @noindent
15698 However this is not always the case.  Some implementations
15699 discard everything from @code{#} through the end of the line, ignoring any
15700 trailing backslash.
15702 @example
15703 $ @kbd{pmake}  # BSD make
15704 "Makefile", line 3: Need an operator
15705 Fatal errors encountered -- cannot continue
15706 @end example
15708 @noindent
15709 Therefore, if you want to comment out a multi-line definition, prefix each
15710 line with @code{#}, not only the first.
15712 @example
15713 # A = foo \
15714 #     bar \
15715 #     baz
15716 @end example
15718 @node Long Lines in Makefiles
15719 @section Long Lines in Makefiles
15721 Tru64 5.1's @command{make} has been reported to crash when given a
15722 makefile with lines longer than around 20 kB.  Earlier versions are
15723 reported to exit with @code{Line too long} diagnostics.
15725 @node Macros and Submakes
15726 @section @code{make macro=value} and Submakes
15728 A command-line variable definition such as @code{foo=bar} overrides any
15729 definition of @code{foo} in a makefile.  Some @command{make}
15730 implementations (such as @acronym{GNU} @command{make}) propagate this
15731 override to subsidiary invocations of @command{make}.  Some other
15732 implementations do not pass the substitution along to submakes.
15734 @example
15735 $ @kbd{cat Makefile}
15736 foo = foo
15737 one:
15738         @@echo $(foo)
15739         $(MAKE) two
15740 two:
15741         @@echo $(foo)
15742 $ @kbd{make foo=bar}            # GNU make 3.79.1
15744 make two
15745 make[1]: Entering directory `/home/adl'
15747 make[1]: Leaving directory `/home/adl'
15748 $ @kbd{pmake foo=bar}           # BSD make
15750 pmake two
15752 @end example
15754 You have a few possibilities if you do want the @code{foo=bar} override
15755 to propagate to submakes.  One is to use the @option{-e}
15756 option, which causes all environment variables to have precedence over
15757 the makefile macro definitions, and declare foo as an environment
15758 variable:
15760 @example
15761 $ @kbd{env foo=bar make -e}
15762 @end example
15764 The @option{-e} option is propagated to submakes automatically,
15765 and since the environment is inherited between @command{make}
15766 invocations, the @code{foo} macro is overridden in
15767 submakes as expected.
15769 This syntax (@code{foo=bar make -e}) is portable only when used
15770 outside of a makefile, for instance from a script or from the
15771 command line.  When run inside a @command{make} rule, @acronym{GNU}
15772 @command{make} 3.80 and prior versions forget to propagate the
15773 @option{-e} option to submakes.
15775 Moreover, using @option{-e} could have unexpected side effects if your
15776 environment contains some other macros usually defined by the
15777 makefile.  (See also the note about @code{make -e} and @code{SHELL}
15778 below.)
15780 Another way to propagate overrides to submakes is to do it
15781 manually, from your makefile:
15783 @example
15784 foo = foo
15785 one:
15786         @@echo $(foo)
15787         $(MAKE) foo=$(foo) two
15788 two:
15789         @@echo $(foo)
15790 @end example
15792 You need to foresee all macros that a user might want to override if
15793 you do that.
15795 @node The Make Macro MAKEFLAGS
15796 @section The Make Macro MAKEFLAGS
15797 @cindex @code{MAKEFLAGS} and @command{make}
15798 @cindex @command{make} and @code{MAKEFLAGS}
15800 Posix requires @command{make} to use @code{MAKEFLAGS} to affect the
15801 current and recursive invocations of make, but allows implementations
15802 several formats for the variable.  It is tricky to parse
15803 @code{$MAKEFLAGS} to determine whether @option{-s} for silent execution
15804 or @option{-k} for continued execution are in effect.  For example, you
15805 cannot assume that the first space-separated word in @code{$MAKEFLAGS}
15806 contains single-letter options, since in the Cygwin version of
15807 @acronym{GNU} @command{make} it is either @option{--unix} or
15808 @option{--win32} with the second word containing single-letter options.
15810 @example
15811 $ @kbd{cat Makefile}
15812 all:
15813         @@echo MAKEFLAGS = $(MAKEFLAGS)
15814 $ @kbd{make}
15815 MAKEFLAGS = --unix
15816 $ @kbd{make -k}
15817 MAKEFLAGS = --unix -k
15818 @end example
15820 @node The Make Macro SHELL
15821 @section The Make Macro @code{SHELL}
15822 @cindex @code{SHELL} and @command{make}
15823 @cindex @command{make} and @code{SHELL}
15825 Posix-compliant @command{make} internally uses the @code{$(SHELL)}
15826 macro to spawn shell processes and execute Make rules.  This
15827 is a builtin macro supplied by @command{make}, but it can be modified
15828 by a makefile or by a command-line argument.
15830 Not all @command{make} implementations define this @code{SHELL} macro.
15831 Tru64
15832 @command{make} is an example; this implementation always uses
15833 @code{/bin/sh}.  So it's a good idea to always define @code{SHELL} in
15834 your makefiles.  If you use Autoconf, do
15836 @example
15837 SHELL = @@SHELL@@
15838 @end example
15840 Do not force @code{SHELL = /bin/sh} because that is not correct
15841 everywhere.  For instance @acronym{DJGPP} lacks @code{/bin/sh}, and when
15842 its @acronym{GNU} @code{make} port sees such a setting it enters a special
15843 emulation mode where features like pipes and redirections are emulated
15844 on top of DOS's @command{command.com}.  Unfortunately this emulation is
15845 incomplete; for instance it does not handle command substitutions.
15846 On @acronym{DJGPP} @code{SHELL} should point to Bash.
15848 Posix-compliant @command{make} should never acquire the value of
15849 $(SHELL) from the environment, even when @code{make -e} is used
15850 (otherwise, think about what would happen to your rules if
15851 @code{SHELL=/bin/tcsh}).
15853 However not all @command{make} implementations have this exception.
15854 For instance it's not surprising that Tru64 @command{make} doesn't
15855 protect @code{SHELL}, since it doesn't use it.
15857 @example
15858 $ @kbd{cat Makefile}
15859 SHELL = /bin/sh
15860 FOO = foo
15861 all:
15862         @@echo $(SHELL)
15863         @@echo $(FOO)
15864 $ @kbd{env SHELL=/bin/tcsh FOO=bar make -e}   # Tru64 Make
15865 /bin/tcsh
15867 $ @kbd{env SHELL=/bin/tcsh FOO=bar gmake -e}  # GNU make
15868 /bin/sh
15870 @end example
15872 @node Comments in Make Rules
15873 @section Comments in Make Rules
15874 @cindex Comments in @file{Makefile} rules
15875 @cindex @file{Makefile} rules and comments
15877 Never put comments in a rule.
15879 Some @command{make} treat anything starting with a tab as a command for
15880 the current rule, even if the tab is immediately followed by a @code{#}.
15881 The @command{make} from Tru64 Unix V5.1 is one of them.  The following
15882 makefile runs @code{# foo} through the shell.
15884 @example
15885 all:
15886         # foo
15887 @end example
15889 @node obj/ and Make
15890 @section The @file{obj/} Subdirectory and Make
15891 @cindex @file{obj/}, subdirectory
15892 @cindex @acronym{BSD} @command{make} and @file{obj/}
15894 Never name one of your subdirectories @file{obj/} if you don't like
15895 surprises.
15897 If an @file{obj/} directory exists, @acronym{BSD} @command{make} enters it
15898 before reading the makefile.  Hence the makefile in the
15899 current directory is not read.
15901 @example
15902 $ @kbd{cat Makefile}
15903 all:
15904         echo Hello
15905 $ @kbd{cat obj/Makefile}
15906 all:
15907         echo World
15908 $ @kbd{make}      # GNU make
15909 echo Hello
15910 Hello
15911 $ @kbd{pmake}     # BSD make
15912 echo World
15913 World
15914 @end example
15916 @node make -k Status
15917 @section Exit Status of @code{make -k}
15918 @cindex @code{make -k}
15920 Do not rely on the exit status of @code{make -k}.  Some implementations
15921 reflect whether they encountered an error in their exit status; other
15922 implementations always succeed.
15924 @example
15925 $ @kbd{cat Makefile}
15926 all:
15927         false
15928 $ @kbd{make -k; echo exit status: $?}    # GNU make
15929 false
15930 make: *** [all] Error 1
15931 exit status: 2
15932 $ @kbd{pmake -k; echo exit status: $?}   # BSD make
15933 false
15934 *** Error code 1 (continuing)
15935 exit status: 0
15936 @end example
15938 @node VPATH and Make
15939 @section @code{VPATH} and Make
15940 @cindex @code{VPATH}
15942 Posix does not specify the semantics of @code{VPATH}.  Typically,
15943 @command{make} supports @code{VPATH}, but its implementation is not
15944 consistent.
15946 Autoconf and Automake support makefiles whose usages of @code{VPATH} are
15947 portable to recent-enough popular implementations of @command{make}, but
15948 to keep the resulting makefiles portable, a package's makefile
15949 prototypes must take the following issues into account.  These issues
15950 are complicated and are often poorly understood, and installers who use
15951 @code{VPATH} should expect to find many bugs in this area.  If you use
15952 @code{VPATH}, the simplest way to avoid these portability bugs is to
15953 stick with @acronym{GNU} @command{make}, since it is the most
15954 commonly-used @command{make} among Autoconf users.
15956 Here are some known issues with some @code{VPATH}
15957 implementations.
15959 @menu
15960 * VPATH and Double-colon::      Problems with @samp{::} on ancient hosts
15961 * $< in Explicit Rules::        @code{$<} does not work in ordinary rules
15962 * Automatic Rule Rewriting::    @code{VPATH} goes wild on Solaris
15963 * Tru64 Directory Magic::       @command{mkdir} goes wild on Tru64
15964 * Make Target Lookup::          More details about @code{VPATH} lookup
15965 @end menu
15967 @node VPATH and Double-colon
15968 @subsection @code{VPATH} and Double-colon Rules
15969 @cindex @code{VPATH} and double-colon rules
15970 @cindex double-colon rules and @code{VPATH}
15972 With ancient versions of Sun @command{make},
15973 any assignment to @code{VPATH} causes @command{make} to execute only
15974 the first set of double-colon rules.
15975 However, this problem is no longer of practical concern.
15977 @node $< in Explicit Rules
15978 @subsection @code{$<} Not Supported in Explicit Rules
15979 @cindex explicit rules, @code{$<}, and @code{VPATH}
15980 @cindex @code{$<}, explicit rules, and @code{VPATH}
15981 @cindex @code{VPATH}, explicit rules, and @code{$<}
15983 Using @code{$<} in explicit rules is not portable.
15984 The prerequisite file must be named explicitly in the rule.  If you want
15985 to find the prerequisite via a @code{VPATH} search, you have to code the
15986 whole thing manually.  @xref{Build Directories}.
15988 @node Automatic Rule Rewriting
15989 @subsection Automatic Rule Rewriting
15990 @cindex @code{VPATH} and automatic rule rewriting
15991 @cindex automatic rule rewriting and @code{VPATH}
15993 Some @command{make} implementations, such as Solaris and Tru64,
15994 search for prerequisites in @code{VPATH} and
15995 then rewrite each occurrence as a plain word in the rule.
15996 For instance:
15998 @example
15999 # This isn't portable to GNU make.
16000 VPATH = ../pkg/src
16001 f.c: if.c
16002         cp if.c f.c
16003 @end example
16005 @noindent
16006 executes @code{cp ../pkg/src/if.c f.c} if @file{if.c} is
16007 found in @file{../pkg/src}.
16009 However, this rule leads to real problems in practice.  For example, if
16010 the source directory contains an ordinary file named @file{test} that is
16011 used in a dependency, Solaris @command{make} rewrites commands like
16012 @samp{if test -r foo; @dots{}} to @samp{if ../pkg/src/test -r foo;
16013 @dots{}}, which is typically undesirable.  To avoid this problem,
16014 portable makefiles should never mention a source file whose name is that
16015 of a shell keyword like @file{until} or a shell command like
16016 @command{cat} or @command{gcc} or @command{test}.
16018 Because of these problems @acronym{GNU} @command{make} and many other
16019 @command{make} implementations do not rewrite commands, so portable
16020 makefiles should
16021 search @code{VPATH} manually.  It is tempting to write this:
16023 @smallexample
16024 # This isn't portable to Solaris make.
16025 VPATH = ../pkg/src
16026 f.c: if.c
16027         cp `test -f if.c || echo $(VPATH)/`if.c f.c
16028 @end smallexample
16030 @noindent
16031 However, the ``prerequisite rewriting'' still applies here.  So if
16032 @file{if.c} is in @file{../pkg/src}, Solaris and Tru64 @command{make}
16033 execute
16035 @smallexample
16036 cp `test -f ../pkg/src/if.c || echo ../pkg/src/`if.c f.c
16037 @end smallexample
16039 @noindent
16040 which reduces to
16042 @example
16043 cp if.c f.c
16044 @end example
16046 @noindent
16047 and thus fails.  Oops.
16049 A simple workaround, and good practice anyway, is to use @samp{$?} and
16050 @samp{$@@} when possible:
16052 @smallexample
16053 VPATH = ../pkg/src
16054 f.c: if.c
16055         cp $? $@@
16056 @end smallexample
16058 @noindent
16059 but this does not generalize well to commands with multiple
16060 prerequisites.  A more general workaround is to rewrite the rule so that
16061 the prerequisite @file{if.c} never appears as a plain word.  For
16062 example, these three rules would be safe, assuming @file{if.c} is in
16063 @file{../pkg/src} and the other files are in the working directory:
16065 @smallexample
16066 VPATH = ../pkg/src
16067 f.c: if.c f1.c
16068         cat `test -f ./if.c || echo $(VPATH)/`if.c f1.c >$@@
16069 g.c: if.c g1.c
16070         cat `test -f 'if.c' || echo $(VPATH)/`if.c g1.c >$@@
16071 h.c: if.c h1.c
16072         cat `test -f "if.c" || echo $(VPATH)/`if.c h1.c >$@@
16073 @end smallexample
16075 Things get worse when your prerequisites are in a macro.
16077 @example
16078 VPATH = ../pkg/src
16079 HEADERS = f.h g.h h.h
16080 install-HEADERS: $(HEADERS)
16081         for i in $(HEADERS); do \
16082           $(INSTALL) -m 644 \
16083             `test -f $$i || echo $(VPATH)/`$$i \
16084             $(DESTDIR)$(includedir)/$$i; \
16085         done
16086 @end example
16088 The above @code{install-HEADERS} rule is not Solaris-proof because @code{for
16089 i in $(HEADERS);} is expanded to @code{for i in f.h g.h h.h;}
16090 where @code{f.h} and @code{g.h} are plain words and are hence
16091 subject to @code{VPATH} adjustments.
16093 If the three files are in @file{../pkg/src}, the rule is run as:
16095 @example
16096 for i in ../pkg/src/f.h ../pkg/src/g.h h.h; do \
16097   install -m 644 \
16098      `test -f $i || echo ../pkg/src/`$i \
16099      /usr/local/include/$i; \
16100 done
16101 @end example
16103 where the two first @command{install} calls fail.  For instance,
16104 consider the @code{f.h} installation:
16106 @example
16107 install -m 644 \
16108   `test -f ../pkg/src/f.h || \
16109     echo ../pkg/src/ \
16110   `../pkg/src/f.h \
16111   /usr/local/include/../pkg/src/f.h;
16112 @end example
16114 @noindent
16115 It reduces to:
16117 @example
16118 install -m 644 \
16119   ../pkg/src/f.h \
16120   /usr/local/include/../pkg/src/f.h;
16121 @end example
16123 Note that the manual @code{VPATH} search did not cause any problems here;
16124 however this command installs @file{f.h} in an incorrect directory.
16126 Trying to quote @code{$(HEADERS)} in some way, as we did for
16127 @code{foo.c} a few makefiles ago, does not help:
16129 @example
16130 install-HEADERS: $(HEADERS)
16131         headers='$(HEADERS)'; \
16132         for i in $$headers; do \
16133           $(INSTALL) -m 644 \
16134             `test -f $$i || echo $(VPATH)/`$$i \
16135             $(DESTDIR)$(includedir)/$$i; \
16136         done
16137 @end example
16139 Now, @code{headers='$(HEADERS)'} macro-expands to:
16141 @example
16142 headers='f.h g.h h.h'
16143 @end example
16145 @noindent
16146 but @code{g.h} is still a plain word.  (As an aside, the idiom
16147 @code{headers='$(HEADERS)'; for i in $$headers;} is a good
16148 idea if @code{$(HEADERS)} can be empty, because some shells diagnose a
16149 syntax error on @code{for i in;}.)
16151 One workaround is to strip this unwanted @file{../pkg/src/} prefix manually:
16153 @example
16154 VPATH = ../pkg/src
16155 HEADERS = f.h g.h h.h
16156 install-HEADERS: $(HEADERS)
16157         headers='$(HEADERS)'; \
16158         for i in $$headers; do \
16159           i=`expr "$$i" : '$(VPATH)/\(.*\)'`;
16160           $(INSTALL) -m 644 \
16161             `test -f $$i || echo $(VPATH)/`$$i \
16162             $(DESTDIR)$(includedir)/$$i; \
16163         done
16164 @end example
16166 Automake does something similar.  However the above hack works only if
16167 the files listed in @code{HEADERS} are in the current directory or a
16168 subdirectory; they should not be in an enclosing directory.  If we had
16169 @code{HEADERS = ../f.h}, the above fragment would fail in a VPATH
16170 build with Tru64 @command{make}.  The reason is that not only does
16171 Tru64 @command{make} rewrite dependencies, but it also simplifies
16172 them.  Hence @code{../f.h} becomes @code{../pkg/f.h} instead of
16173 @code{../pkg/src/../f.h}.  This obviously defeats any attempt to strip
16174 a leading @file{../pkg/src/} component.
16176 The following example makes the behavior of Tru64 @command{make}
16177 more apparent.
16179 @example
16180 $ @kbd{cat Makefile}
16181 VPATH = sub
16182 all: ../foo
16183         echo ../foo
16184 $ @kbd{ls}
16185 Makefile foo
16186 $ @kbd{make}
16187 echo foo
16189 @end example
16191 @noindent
16192 Dependency @file{../foo} was found in @file{sub/../foo}, but Tru64
16193 @command{make} simplified it as @file{foo}.  (Note that the @file{sub/}
16194 directory does not even exist, this just means that the simplification
16195 occurred before the file was checked for.)
16197 For the record here is how SunOS 4 @command{make} behaves on this
16198 example.
16200 @smallexample
16201 $ @kbd{make}
16202 make: Fatal error: Don't know how to make target `../foo'
16203 $ @kbd{mkdir sub}
16204 $ @kbd{make}
16205 echo sub/../foo
16206 sub/../foo
16207 @end smallexample
16210 @node Tru64 Directory Magic
16211 @subsection Tru64 @command{make} Creates Prerequisite Directories Magically
16212 @cindex @code{VPATH} and prerequisite directories
16213 @cindex prerequisite directories and @code{VPATH}
16215 When a prerequisite is a subdirectory of @code{VPATH}, Tru64
16216 @command{make} creates it in the current directory.
16218 @example
16219 $ @kbd{mkdir -p foo/bar build}
16220 $ @kbd{cd build}
16221 $ @kbd{cat >Makefile <<END
16222 VPATH = ..
16223 all: foo/bar
16224 END}
16225 $ @kbd{make}
16226 mkdir foo
16227 mkdir foo/bar
16228 @end example
16230 This can yield unexpected results if a rule uses a manual @code{VPATH}
16231 search as presented before.
16233 @example
16234 VPATH = ..
16235 all : foo/bar
16236         command `test -d foo/bar || echo ../`foo/bar
16237 @end example
16239 The above @command{command} is run on the empty @file{foo/bar}
16240 directory that was created in the current directory.
16242 @node Make Target Lookup
16243 @subsection Make Target Lookup
16244 @cindex @code{VPATH}, resolving target pathnames
16246 @acronym{GNU} @command{make} uses a complex algorithm to decide when it
16247 should use files found via a @code{VPATH} search.  @xref{Search
16248 Algorithm, , How Directory Searches are Performed, make, The @acronym{GNU} Make
16249 Manual}.
16251 If a target needs to be rebuilt, @acronym{GNU} @command{make} discards the
16252 file name found during the @code{VPATH} search for this target, and
16253 builds the file locally using the file name given in the makefile.
16254 If a target does not need to be rebuilt, @acronym{GNU} @command{make} uses the
16255 file name found during the @code{VPATH} search.
16257 Other @command{make} implementations, like Net@acronym{BSD} @command{make}, are
16258 easier to describe: the file name found during the @code{VPATH} search
16259 is used whether the target needs to be rebuilt or not.  Therefore
16260 new files are created locally, but existing files are updated at their
16261 @code{VPATH} location.
16263 Open@acronym{BSD} and Free@acronym{BSD} @command{make}, however,
16264 never perform a
16265 @code{VPATH} search for a dependency that has an explicit rule.
16266 This is extremely annoying.
16268 When attempting a @code{VPATH} build for an autoconfiscated package
16269 (e.g., @code{mkdir build && cd build && ../configure}), this means
16270 @acronym{GNU}
16271 @command{make} builds everything locally in the @file{build}
16272 directory, while @acronym{BSD} @command{make} builds new files locally and
16273 updates existing files in the source directory.
16275 @example
16276 $ @kbd{cat Makefile}
16277 VPATH = ..
16278 all: foo.x bar.x
16279 foo.x bar.x: newer.x
16280         @@echo Building $@@
16281 $ @kbd{touch ../bar.x}
16282 $ @kbd{touch ../newer.x}
16283 $ @kbd{make}        # GNU make
16284 Building foo.x
16285 Building bar.x
16286 $ @kbd{pmake}       # NetBSD make
16287 Building foo.x
16288 Building ../bar.x
16289 $ @kbd{fmake}       # FreeBSD make, OpenBSD make
16290 Building foo.x
16291 Building bar.x
16292 $ @kbd{tmake}       # Tru64 make
16293 Building foo.x
16294 Building bar.x
16295 $ @kbd{touch ../bar.x}
16296 $ @kbd{make}        # GNU make
16297 Building foo.x
16298 $ @kbd{pmake}       # NetBSD make
16299 Building foo.x
16300 $ @kbd{fmake}       # FreeBSD make, OpenBSD make
16301 Building foo.x
16302 Building bar.x
16303 $ @kbd{tmake}       # Tru64 make
16304 Building foo.x
16305 Building bar.x
16306 @end example
16308 Note how Net@acronym{BSD} @command{make} updates @file{../bar.x} in its
16309 VPATH location, and how Free@acronym{BSD}, Open@acronym{BSD}, and Tru64
16310 @command{make} always
16311 update @file{bar.x}, even when @file{../bar.x} is up to date.
16313 Another point worth mentioning is that once @acronym{GNU} @command{make} has
16314 decided to ignore a @code{VPATH} file name (e.g., it ignored
16315 @file{../bar.x} in the above example) it continues to ignore it when
16316 the target occurs as a prerequisite of another rule.
16318 The following example shows that @acronym{GNU} @command{make} does not look up
16319 @file{bar.x} in @code{VPATH} before performing the @code{.x.y} rule,
16320 because it ignored the @code{VPATH} result of @file{bar.x} while running
16321 the @code{bar.x: newer.x} rule.
16323 @example
16324 $ @kbd{cat Makefile}
16325 VPATH = ..
16326 all: bar.y
16327 bar.x: newer.x
16328         @@echo Building $@@
16329 .SUFFIXES: .x .y
16330 .x.y:
16331         cp $< $@@
16332 $ @kbd{touch ../bar.x}
16333 $ @kbd{touch ../newer.x}
16334 $ @kbd{make}        # GNU make
16335 Building bar.x
16336 cp bar.x bar.y
16337 cp: cannot stat `bar.x': No such file or directory
16338 make: *** [bar.y] Error 1
16339 $ @kbd{pmake}       # NetBSD make
16340 Building ../bar.x
16341 cp ../bar.x bar.y
16342 $ @kbd{rm bar.y}
16343 $ @kbd{fmake}       # FreeBSD make, OpenBSD make
16344 echo Building bar.x
16345 cp bar.x bar.y
16346 cp: cannot stat `bar.x': No such file or directory
16347 *** Error code 1
16348 $ @kbd{tmake}       # Tru64 make
16349 Building bar.x
16350 cp: bar.x: No such file or directory
16351 *** Exit 1
16352 @end example
16354 Note that if you drop away the command from the @code{bar.x: newer.x}
16355 rule, @acronym{GNU} @command{make} magically starts to work: it
16356 knows that @code{bar.x} hasn't been updated, therefore it doesn't
16357 discard the result from @code{VPATH} (@file{../bar.x}) in succeeding
16358 uses.  Tru64 also works, but Free@acronym{BSD} and Open@acronym{BSD}
16359 still don't.
16361 @example
16362 $ @kbd{cat Makefile}
16363 VPATH = ..
16364 all: bar.y
16365 bar.x: newer.x
16366 .SUFFIXES: .x .y
16367 .x.y:
16368         cp $< $@@
16369 $ @kbd{touch ../bar.x}
16370 $ @kbd{touch ../newer.x}
16371 $ @kbd{make}        # GNU make
16372 cp ../bar.x bar.y
16373 $ @kbd{rm bar.y}
16374 $ @kbd{pmake}       # NetBSD make
16375 cp ../bar.x bar.y
16376 $ @kbd{rm bar.y}
16377 $ @kbd{fmake}       # FreeBSD make, OpenBSD make
16378 cp bar.x bar.y
16379 cp: cannot stat `bar.x': No such file or directory
16380 *** Error code 1
16381 $ @kbd{tmake}       # Tru64 make
16382 cp ../bar.x bar.y
16383 @end example
16385 It seems the sole solution that would please every @command{make}
16386 implementation is to never rely on @code{VPATH} searches for targets.
16387 In other words, @code{VPATH} should be reserved to unbuilt sources.
16390 @node Single Suffix Rules
16391 @section Single Suffix Rules and Separated Dependencies
16392 @cindex Single Suffix Inference Rule
16393 @cindex Rule, Single Suffix Inference
16394 A @dfn{Single Suffix Rule} is basically a usual suffix (inference) rule
16395 (@samp{.from.to:}), but which @emph{destination} suffix is empty
16396 (@samp{.from:}).
16398 @cindex Separated Dependencies
16399 @dfn{Separated dependencies} simply refers to listing the prerequisite
16400 of a target, without defining a rule.  Usually one can list on the one
16401 hand side, the rules, and on the other hand side, the dependencies.
16403 Solaris @command{make} does not support separated dependencies for
16404 targets defined by single suffix rules:
16406 @example
16407 $ @kbd{cat Makefile}
16408 .SUFFIXES: .in
16409 foo: foo.in
16410 .in:
16411         cp $< $@@
16412 $ @kbd{touch foo.in}
16413 $ @kbd{make}
16414 $ @kbd{ls}
16415 Makefile  foo.in
16416 @end example
16418 @noindent
16419 while @acronym{GNU} Make does:
16421 @example
16422 $ @kbd{gmake}
16423 cp foo.in foo
16424 $ @kbd{ls}
16425 Makefile  foo       foo.in
16426 @end example
16428 Note it works without the @samp{foo: foo.in} dependency.
16430 @example
16431 $ @kbd{cat Makefile}
16432 .SUFFIXES: .in
16433 .in:
16434         cp $< $@@
16435 $ @kbd{make foo}
16436 cp foo.in foo
16437 @end example
16439 @noindent
16440 and it works with double suffix inference rules:
16442 @example
16443 $ @kbd{cat Makefile}
16444 foo.out: foo.in
16445 .SUFFIXES: .in .out
16446 .in.out:
16447         cp $< $@@
16448 $ @kbd{make}
16449 cp foo.in foo.out
16450 @end example
16452 As a result, in such a case, you have to write target rules.
16454 @node Timestamps and Make
16455 @section Timestamp Resolution and Make
16456 @cindex timestamp resolution
16457 Traditionally, file timestamps had 1-second resolution, and
16458 @command{make} used those timestamps to determine whether one file was
16459 newer than the other.  However, many modern file systems have
16460 timestamps with 1-nanosecond resolution.  Some @command{make}
16461 implementations look at the entire timestamp; others ignore the
16462 fractional part, which can lead to incorrect results.  Normally this
16463 is not a problem, but in some extreme cases you may need to use tricks
16464 like @samp{sleep 1} to work around timestamp truncation bugs.
16466 Commands like @samp{cp -p} and @samp{touch -r} typically do not copy
16467 file timestamps to their full resolutions (@pxref{Limitations of Usual
16468 Tools}).  Hence you should be wary of rules like this:
16470 @example
16471 dest: src
16472         cp -p src dest
16473 @end example
16475 as @file{dest} often appears to be older than @file{src} after the
16476 timestamp is truncated, and this can cause @command{make} to do
16477 needless rework the next time it is invoked.  To work around this
16478 problem, you can use a timestamp file, e.g.:
16480 @example
16481 dest-stamp: src
16482         cp -p src dest
16483         date >dest-stamp
16484 @end example
16489 @c ======================================== Portable C and C++ Programming
16491 @node Portable C and C++
16492 @chapter Portable C and C++ Programming
16493 @cindex Portable C and C++ programming
16495 C and C++ programs often use low-level features of the underlying
16496 system, and therefore are often more difficult to make portable to other
16497 platforms.
16499 Several standards have been developed to help make your programs more
16500 portable.  If you write programs with these standards in mind, you can
16501 have greater confidence that your programs work on a wide variety
16502 of systems.  @xref{Standards, , Language Standards Supported by
16503 @acronym{GCC}, gcc, Using the @acronym{GNU} Compiler Collection
16504 (@acronym{GCC})}, for a list of C-related
16505 standards.  Many programs also assume the
16506 @uref{http://www.opengroup.org/susv3, Posix standard}.
16508 Some old code is written to be portable to K&R C, which predates any C
16509 standard.  K&R C compilers are no longer of practical interest, though,
16510 and the rest of section assumes at least C89, the first C standard.
16512 Program portability is a huge topic, and this section can only briefly
16513 introduce common pitfalls.  @xref{System Portability, , Portability
16514 between System Types, standards, @acronym{GNU} Coding Standards}, for
16515 more information.
16517 @menu
16518 * Varieties of Unportability::  How to make your programs unportable
16519 * Integer Overflow::            When integers get too large
16520 * Preprocessor Arithmetic::     @code{#if} expression problems
16521 * Null Pointers::               Properties of null pointers
16522 * Buffer Overruns::             Subscript errors and the like
16523 * Volatile Objects::            @code{volatile} and signals
16524 * Floating Point Portability::  Portable floating-point arithmetic
16525 * Exiting Portably::            Exiting and the exit status
16526 @end menu
16528 @node Varieties of Unportability
16529 @section Varieties of Unportability
16530 @cindex portability
16532 Autoconf tests and ordinary programs often need to test what is allowed
16533 on a system, and therefore they may need to deliberately exceed the
16534 boundaries of what the standards allow, if only to see whether an
16535 optional feature is present.  When you write such a program, you should
16536 keep in mind the difference between constraints, unspecified behavior,
16537 and undefined behavior.
16539 In C, a @dfn{constraint} is a rule that the compiler must enforce.  An
16540 example constraint is that C programs must not declare a bit-field with
16541 negative width.  Tests can therefore reliably assume that programs with
16542 negative-width bit-fields are rejected by a compiler that conforms
16543 to the standard.
16545 @dfn{Unspecified behavior} is valid behavior, where the standard allows
16546 multiple possibilities.  For example, the order of evaluation of
16547 function arguments is unspecified.  Some unspecified behavior is
16548 @dfn{implementation-defined}, i.e., documented by the implementation,
16549 but since Autoconf tests cannot read the documentation they cannot
16550 distinguish between implementation-defined and other unspecified
16551 behavior.  It is common for Autoconf tests to probe implementations to
16552 determine otherwise-unspecified behavior.
16554 @dfn{Undefined behavior} is invalid behavior, where the standard allows
16555 the implementation to do anything it pleases.  For example,
16556 dereferencing a null pointer leads to undefined behavior.  If possible,
16557 test programs should avoid undefined behavior, since a program with
16558 undefined behavior might succeed on a test that should fail.
16560 The above rules apply to programs that are intended to conform to the
16561 standard.  However, strictly-conforming programs are quite rare, since
16562 the standards are so limiting.  A major goal of Autoconf is to support
16563 programs that use implementation features not described by the standard,
16564 and it is fairly common for test programs to violate the above rules, if
16565 the programs work well enough in practice.
16567 @node Integer Overflow
16568 @section Integer Overflow
16569 @cindex integer overflow
16570 @cindex overflow, signed integer
16571 @cindex signed integer overflow
16572 @cindex wraparound arithmetic
16574 In practice many portable C programs assume that signed integer overflow wraps
16575 around reliably using two's complement arithmetic.  Yet the C standard
16576 says that program behavior is undefined on overflow, and in a few cases
16577 C programs do not work on some modern implementations because their
16578 overflows do not wrap around as their authors expected.  Conversely, in
16579 signed integer remainder, the C standard requires overflow
16580 behavior that is commonly not implemented.
16582 @menu
16583 * Integer Overflow Basics::      Why integer overflow is a problem
16584 * Signed Overflow Examples::     Examples of code assuming wraparound
16585 * Optimization and Wraparound::  Optimizations that break uses of wraparound
16586 * Signed Overflow Advice::       Practical advice for signed overflow issues
16587 * Signed Integer Division::      @code{INT_MIN / -1} and @code{INT_MIN % -1}
16588 @end menu
16590 @node Integer Overflow Basics
16591 @subsection Basics of Integer Overflow
16592 @cindex integer overflow
16593 @cindex overflow, signed integer
16594 @cindex signed integer overflow
16595 @cindex wraparound arithmetic
16597 In languages like C, unsigned integer overflow reliably wraps around;
16598 e.g., @code{UINT_MAX + 1} yields zero.
16599 This is guaranteed by the C standard and is
16600 portable in practice, unless you specify aggressive,
16601 nonstandard optimization options
16602 suitable only for special applications.
16604 In contrast, the C standard says that signed integer overflow leads to
16605 undefined behavior where a program can do anything, including dumping
16606 core or overrunning a buffer.  The misbehavior can even precede the
16607 overflow.  Such an overflow can occur during addition, subtraction,
16608 multiplication, division, and left shift.
16610 Despite this requirement of the standard, many C programs and Autoconf
16611 tests assume that signed integer overflow silently wraps around modulo a
16612 power of two, using two's complement arithmetic, so long as you cast the
16613 resulting value to a signed integer type or store it into a signed
16614 integer variable.  If you use conservative optimization flags, such
16615 programs are generally portable to the vast majority of modern
16616 platforms, with a few exceptions discussed later.
16618 For historical reasons the C standard also allows implementations with
16619 ones' complement or signed magnitude arithmetic, but it is safe to
16620 assume two's complement nowadays.
16622 Also, overflow can occur when converting an out-of-range value to a
16623 signed integer type.  Here a standard implementation must define what
16624 happens, but this might include raising an exception.  In practice all
16625 known implementations support silent wraparound in this case, so you need
16626 not worry about other possibilities.
16628 @node Signed Overflow Examples
16629 @subsection Examples of Code Assuming Wraparound Overflow
16630 @cindex integer overflow
16631 @cindex overflow, signed integer
16632 @cindex signed integer overflow
16633 @cindex wraparound arithmetic
16635 There has long been a tension between what the C standard requires for
16636 signed integer overflow, and what C programs commonly assume.  The
16637 standard allows aggressive optimizations based on assumptions that
16638 overflow never occurs, but many practical C programs rely on overflow
16639 wrapping around.  These programs do not conform to the standard, but
16640 they commonly work in practice because compiler writers are
16641 understandably reluctant to implement optimizations that would break
16642 many programs, unless perhaps a user specifies aggressive optimization.
16644 The C Standard says that if a program has signed integer overflow its
16645 behavior is undefined, and the undefined behavior can even precede the
16646 overflow.  To take an extreme example:
16648 @c Inspired by Robert Dewar's example in
16649 @c <http://gcc.gnu.org/ml/gcc/2007-01/msg00038.html> (2007-01-01).
16650 @example
16651 if (password == expected_password)
16652   allow_superuser_privileges ();
16653 else if (counter++ == INT_MAX)
16654   abort ();
16655 else
16656   printf ("%d password mismatches\n", counter);
16657 @end example
16659 @noindent
16660 If the @code{int} variable @code{counter} equals @code{INT_MAX},
16661 @code{counter++} must overflow and the behavior is undefined, so the C
16662 standard allows the compiler to optimize away the test against
16663 @code{INT_MAX} and the @code{abort} call.
16664 Worse, if an earlier bug in the program lets the compiler deduce that
16665 @code{counter == INT_MAX} or that @code{counter} previously overflowed,
16666 the C standard allows the compiler to optimize away the password test
16667 and generate code that allows superuser privileges unconditionally.
16669 Despite this requirement by the standard, it has long been common for C
16670 code to assume wraparound arithmetic after signed overflow, and all
16671 known practical C implementations support some C idioms that assume
16672 wraparound signed arithmetic, even if the idioms do not conform
16673 strictly to the standard.  If your code looks like the following
16674 examples it will almost surely work with real-world compilers.
16676 Here is an example derived from the 7th Edition Unix implementation of
16677 @code{atoi} (1979-01-10):
16679 @example
16680 char *p;
16681 int f, n;
16682 @dots{}
16683 while (*p >= '0' && *p <= '9')
16684   n = n * 10 + *p++ - '0';
16685 return (f ? -n : n);
16686 @end example
16688 @noindent
16689 Even if the input string is in range, on most modern machines this has
16690 signed overflow when computing the most negative integer (the @code{-n}
16691 overflows) or a value near an extreme integer (the first @code{+}
16692 overflows).
16694 Here is another example, derived from the 7th Edition implementation of
16695 @code{rand} (1979-01-10).  Here the programmer expects both
16696 multiplication and addition to wrap on overflow:
16698 @example
16699 static long int randx = 1;
16700 @dots{}
16701 randx = randx * 1103515245 + 12345;
16702 return (randx >> 16) & 077777;
16703 @end example
16705 In the following example, derived from the @acronym{GNU} C Library 2.5
16706 implementation of @code{mktime} (2006-09-09), the code assumes
16707 wraparound arithmetic in @code{+} to detect signed overflow:
16709 @example
16710 time_t t, t1, t2;
16711 int sec_requested, sec_adjustment;
16712 @dots{}
16713 t1 = t + sec_requested;
16714 t2 = t1 + sec_adjustment;
16715 if (((t1 < t) != (sec_requested < 0))
16716     | ((t2 < t1) != (sec_adjustment < 0)))
16717   return -1;
16718 @end example
16720 If your code looks like these examples, it is probably safe even though
16721 it does not strictly conform to the C standard.  This might lead one to
16722 believe that one can generally assume wraparound on overflow, but that
16723 is not always true, as can be seen in the next section.
16725 @node Optimization and Wraparound
16726 @subsection Optimizations That Break Wraparound Arithmetic
16727 @cindex loop induction
16729 Compilers sometimes generate code that is incompatible with wraparound
16730 integer arithmetic.  A simple example is an algebraic simplification: a
16731 compiler might translate @code{(i * 2000) / 1000} to @code{i * 2}
16732 because it assumes that @code{i * 2000} does not overflow.  The
16733 translation is not equivalent to the original when overflow occurs:
16734 e.g., in the typical case of 32-bit signed two's complement wraparound
16735 @code{int}, if @code{i} has type @code{int} and value @code{1073742},
16736 the original expression returns @minus{}2147483 but the optimized
16737 version returns the mathematically correct value 2147484.
16739 More subtly, loop induction optimizations often exploit the undefined
16740 behavior of signed overflow.  Consider the following contrived function
16741 @code{sumc}:
16743 @example
16745 sumc (int lo, int hi)
16747   int sum = 0;
16748   int i;
16749   for (i = lo; i <= hi; i++)
16750     sum ^= i * 53;
16751   return sum;
16753 @end example
16755 @noindent
16756 To avoid multiplying by 53 each time through the loop, an optimizing
16757 compiler might internally transform @code{sumc} to the equivalent of the
16758 following:
16760 @example
16762 transformed_sumc (int lo, int hi)
16764   int sum = 0;
16765   int hic = hi * 53;
16766   int ic;
16767   for (ic = lo * 53; ic <= hic; ic += 53)
16768     sum ^= ic;
16769   return sum;
16771 @end example
16773 @noindent
16774 This transformation is allowed by the C standard, but it is invalid for
16775 wraparound arithmetic when @code{INT_MAX / 53 < hi}, because then the
16776 overflow in computing expressions like @code{hi * 53} can cause the
16777 expression @code{i <= hi} to yield a different value from the
16778 transformed expression @code{ic <= hic}.
16780 For this reason, compilers that use loop induction and similar
16781 techniques often do not support reliable wraparound arithmetic when a
16782 loop induction variable like @code{ic} is involved.  Since loop
16783 induction variables are generated by the compiler, and are not visible
16784 in the source code, it is not always trivial to say whether the problem
16785 affects your code.
16787 Hardly any code actually depends on wraparound arithmetic in cases like
16788 these, so in practice these loop induction optimizations are almost
16789 always useful.  However, edge cases in this area can cause problems.
16790 For example:
16792 @example
16793 int j;
16794 for (j = 1; 0 < j; j *= 2)
16795   test (j);
16796 @end example
16798 @noindent
16799 Here, the loop attempts to iterate through all powers of 2 that
16800 @code{int} can represent, but the C standard allows a compiler to
16801 optimize away the comparison and generate an infinite loop,
16802 under the argument that behavior is undefined on overflow.  As of this
16803 writing this optimization is not done by any production version of
16804 @acronym{GCC} with @option{-O2}, but it might be performed by other
16805 compilers, or by more aggressive @acronym{GCC} optimization options,
16806 and the @acronym{GCC} developers have not decided whether it will
16807 continue to work with @acronym{GCC} and @option{-O2}.
16809 @node Signed Overflow Advice
16810 @subsection Practical Advice for Signed Overflow Issues
16811 @cindex integer overflow
16812 @cindex overflow, signed integer
16813 @cindex signed integer overflow
16814 @cindex wraparound arithmetic
16816 Ideally the safest approach is to avoid signed integer overflow
16817 entirely.  For example, instead of multiplying two signed integers, you
16818 can convert them to unsigned integers, multiply the unsigned values,
16819 then test whether the result is in signed range.
16821 Rewriting code in this way will be inconvenient, though, particularly if
16822 the signed values might be negative.  Also, it may hurt
16823 performance.  Using unsigned arithmetic to check for overflow is
16824 particularly painful to do portably and efficiently when dealing with an
16825 integer type like @code{uid_t} whose width and signedness vary from
16826 platform to platform.
16828 Furthermore, many C applications pervasively assume wraparound behavior
16829 and typically it is not easy to find and remove all these assumptions.
16830 Hence it is often useful to maintain nonstandard code that assumes
16831 wraparound on overflow, instead of rewriting the code.  The rest of this
16832 section attempts to give practical advice for this situation.
16834 If your code wants to detect signed integer overflow in @code{sum = a +
16835 b}, it is generally safe to use an expression like @code{(sum < a) != (b
16836 < 0)}.
16838 If your code uses a signed loop index, make sure that the index cannot
16839 overflow, along with all signed expressions derived from the index.
16840 Here is a contrived example of problematic code with two instances of
16841 overflow.
16843 @example
16844 for (i = INT_MAX - 10; i <= INT_MAX; i++)
16845   if (i + 1 < 0)
16846     @{
16847       report_overflow ();
16848       break;
16849     @}
16850 @end example
16852 @noindent
16853 Because of the two overflows, a compiler might optimize away or
16854 transform the two comparisons in a way that is incompatible with the
16855 wraparound assumption.
16857 If your code uses an expression like @code{(i * 2000) / 1000} and you
16858 actually want the multiplication to wrap around on overflow, use
16859 unsigned arithmetic
16860 to do it, e.g., @code{((int) (i * 2000u)) / 1000}.
16862 If your code assumes wraparound behavior and you want to insulate it
16863 against any @acronym{GCC} optimizations that would fail to support that
16864 behavior, you should use @acronym{GCC}'s @option{-fwrapv} option, which
16865 causes signed overflow to wrap around reliably (except for division and
16866 remainder, as discussed in the next section).
16868 If you need to port to platforms where signed integer overflow does not
16869 reliably wrap around (e.g., due to hardware overflow checking, or to
16870 highly aggressive optimizations), you should consider debugging with
16871 @acronym{GCC}'s @option{-ftrapv} option, which causes signed overflow to
16872 raise an exception.
16874 @node Signed Integer Division
16875 @subsection Signed Integer Division and Integer Overflow
16876 @cindex division, integer
16878 Overflow in signed
16879 integer division is not always harmless: for example, on CPUs of the
16880 i386 family, dividing @code{INT_MIN} by @code{-1} yields a SIGFPE signal
16881 which by default terminates the program.  Worse, taking the remainder
16882 of these two values typically yields the same signal on these CPUs,
16883 even though the C standard requires @code{INT_MIN % -1} to yield zero
16884 because the expression does not overflow.
16886 @node Preprocessor Arithmetic
16887 @section Preprocessor Arithmetic
16888 @cindex preprocessor arithmetic
16890 In C99, preprocessor arithmetic, used for @code{#if} expressions, must
16891 be evaluated as if all signed values are of type @code{intmax_t} and all
16892 unsigned values of type @code{uintmax_t}.  Many compilers are buggy in
16893 this area, though.  For example, as of 2007, Sun C mishandles @code{#if
16894 LLONG_MIN < 0} on a platform with 32-bit @code{long int} and 64-bit
16895 @code{long long int}.  Also, some older preprocessors mishandle
16896 constants ending in @code{LL}.  To work around these problems, you can
16897 compute the value of expressions like @code{LONG_MAX < LLONG_MAX} at
16898 @code{configure}-time rather than at @code{#if}-time.
16900 @node Null Pointers
16901 @section Properties of Null Pointers
16902 @cindex null pointers
16904 Most modern hosts reliably fail when you attempt to dereference a null
16905 pointer.
16907 On almost all modern hosts, null pointers use an all-bits-zero internal
16908 representation, so you can reliably use @code{memset} with 0 to set all
16909 the pointers in an array to null values.
16911 If @code{p} is a null pointer to an object type, the C expression
16912 @code{p + 0} always evaluates to @code{p} on modern hosts, even though
16913 the standard says that it has undefined behavior.
16915 @node Buffer Overruns
16916 @section Buffer Overruns and Subscript Errors
16917 @cindex buffer overruns
16919 Buffer overruns and subscript errors are the most common dangerous
16920 errors in C programs.  They result in undefined behavior because storing
16921 outside an array typically modifies storage that is used by some other
16922 object, and most modern systems lack runtime checks to catch these
16923 errors.  Programs should not rely on buffer overruns being caught.
16925 There is one exception to the usual rule that a portable program cannot
16926 address outside an array.  In C, it is valid to compute the address just
16927 past an object, e.g., @code{&a[N]} where @code{a} has @code{N} elements,
16928 so long as you do not dereference the resulting pointer.  But it is not
16929 valid to compute the address just before an object, e.g., @code{&a[-1]};
16930 nor is it valid to compute two past the end, e.g., @code{&a[N+1]}.  On
16931 most platforms @code{&a[-1] < &a[0] && &a[N] < &a[N+1]}, but this is not
16932 reliable in general, and it is usually easy enough to avoid the
16933 potential portability problem, e.g., by allocating an extra unused array
16934 element at the start or end.
16936 @uref{http://valgrind.org/, Valgrind} can catch many overruns.
16937 @acronym{GCC}
16938 users might also consider using the @option{-fmudflap} option to catch
16939 overruns.
16941 Buffer overruns are usually caused by off-by-one errors, but there are
16942 more subtle ways to get them.
16944 Using @code{int} values to index into an array or compute array sizes
16945 causes problems on typical 64-bit hosts where an array index might
16946 be @math{2^31} or larger.  Index values of type @code{size_t} avoid this
16947 problem, but cannot be negative.  Index values of type @code{ptrdiff_t}
16948 are signed, and are wide enough in practice.
16950 If you add or multiply two numbers to calculate an array size, e.g.,
16951 @code{malloc (x * sizeof y + z)}, havoc ensues if the addition or
16952 multiplication overflows.
16954 Many implementations of the @code{alloca} function silently misbehave
16955 and can generate buffer overflows if given sizes that are too large.
16956 The size limits are implementation dependent, but are at least 4000
16957 bytes on all platforms that we know about.
16959 The standard functions @code{asctime}, @code{asctime_r}, @code{ctime},
16960 @code{ctime_r}, and @code{gets} are prone to buffer overflows, and
16961 portable code should not use them unless the inputs are known to be
16962 within certain limits.  The time-related functions can overflow their
16963 buffers if given timestamps out of range (e.g., a year less than -999
16964 or greater than 9999).  Time-related buffer overflows cannot happen with
16965 recent-enough versions of the @acronym{GNU} C library, but are possible
16966 with other
16967 implementations.  The @code{gets} function is the worst, since it almost
16968 invariably overflows its buffer when presented with an input line larger
16969 than the buffer.
16971 @node Volatile Objects
16972 @section Volatile Objects
16973 @cindex volatile objects
16975 The keyword @code{volatile} is often misunderstood in portable code.
16976 Its use inhibits some memory-access optimizations, but programmers often
16977 wish that it had a different meaning than it actually does.
16979 @code{volatile} was designed for code that accesses special objects like
16980 memory-mapped device registers whose contents spontaneously change.
16981 Such code is inherently low-level, and it is difficult to specify
16982 portably what @code{volatile} means in these cases.  The C standard
16983 says, ``What constitutes an access to an object that has
16984 volatile-qualified type is implementation-defined,'' so in theory each
16985 implementation is supposed to fill in the gap by documenting what
16986 @code{volatile} means for that implementation.  In practice, though,
16987 this documentation is usually absent or incomplete.
16989 One area of confusion is the distinction between objects defined with
16990 volatile types, and volatile lvalues.  From the C standard's point of
16991 view, an object defined with a volatile type has externally visible
16992 behavior.  You can think of such objects as having little oscilloscope
16993 probes attached to them, so that the user can observe some properties of
16994 accesses to them, just as the user can observe data written to output
16995 files.  However, the standard does not make it clear whether users can
16996 observe accesses by volatile lvalues to ordinary objects.  For example:
16998 @example
16999 /* Declare and access a volatile object.
17000    Accesses to X are "visible" to users.  */
17001 static int volatile x;
17002 x = 1;
17004 /* Access two ordinary objects via a volatile lvalue.
17005    It's not clear whether accesses to *P are "visible".  */
17006 int y;
17007 int *z = malloc (sizeof (int));
17008 int volatile *p;
17009 p = &y;
17010 *p = 1;
17011 p = z;
17012 *p = 1;
17013 @end example
17015 Programmers often wish that @code{volatile} meant ``Perform the memory
17016 access here and now, without merging several memory accesses, without
17017 changing the memory word size, and without reordering.''  But the C
17018 standard does not require this.  For objects defined with a volatile
17019 type, accesses must be done before the next sequence point; but
17020 otherwise merging, reordering, and word-size change is allowed.  Worse,
17021 it is not clear from the standard whether volatile lvalues provide more
17022 guarantees in general than nonvolatile lvalues, if the underlying
17023 objects are ordinary.
17025 Even when accessing objects defined with a volatile type,
17026 the C standard allows only
17027 extremely limited signal handlers: the behavior is undefined if a signal
17028 handler reads any nonlocal object, or writes to any nonlocal object
17029 whose type is not @code{sig_atomic_t volatile}, or calls any standard
17030 library function other than @code{abort}, @code{signal}, and (if C99)
17031 @code{_Exit}.  Hence C compilers need not worry about a signal handler
17032 disturbing ordinary computation, unless the computation accesses a
17033 @code{sig_atomic_t volatile} lvalue that is not a local variable.
17034 (There is an obscure exception for accesses via a pointer to a volatile
17035 character, since it may point into part of a @code{sig_atomic_t
17036 volatile} object.)  Posix
17037 adds to the list of library functions callable from a portable signal
17038 handler, but otherwise is like the C standard in this area.
17040 Some C implementations allow memory-access optimizations within each
17041 translation unit, such that actual behavior agrees with the behavior
17042 required by the standard only when calling a function in some other
17043 translation unit, and a signal handler acts like it was called from a
17044 different translation unit.  The C standard hints that in these
17045 implementations, objects referred to by signal handlers ``would require
17046 explicit specification of @code{volatile} storage, as well as other
17047 implementation-defined restrictions.''  But unfortunately even for this
17048 special case these other restrictions are often not documented well.
17049 @xref{Volatiles, , When is a Volatile Object Accessed?, gcc, Using the
17050 @acronym{GNU} Compiler Collection (@acronym{GCC})}, for some
17051 restrictions imposed by @acronym{GCC}.  @xref{Defining Handlers, ,
17052 Defining Signal Handlers, libc, The @acronym{GNU} C Library}, for some
17053 restrictions imposed by the @acronym{GNU} C library.  Restrictions
17054 differ on other platforms.
17056 If possible, it is best to use a signal handler that fits within the
17057 limits imposed by the C and Posix standards.
17059 If this is not practical, you can try the following rules of thumb.  A
17060 signal handler should access only volatile lvalues, preferably lvalues
17061 that refer to objects defined with a volatile type, and should not
17062 assume that the accessed objects have an internally consistent state
17063 if they are larger than a machine word.  Furthermore, installers
17064 should employ compilers and compiler options that are commonly used
17065 for building operating system kernels, because kernels often need more
17066 from @code{volatile} than the C Standard requires, and installers who
17067 compile an application in a similar environment can sometimes benefit
17068 from the extra constraints imposed by kernels on compilers.
17069 Admittedly we are handwaving somewhat here, as there are few
17070 guarantees in this area; the rules of thumb may help to fix some bugs
17071 but there is a good chance that they will not fix them all.
17073 For @code{volatile}, C++ has the same problems that C does.
17074 Multithreaded applications have even more problems with @code{volatile},
17075 but they are beyond the scope of this section.
17077 The bottom line is that using @code{volatile} typically hurts
17078 performance but should not hurt correctness.  In some cases its use
17079 does help correctness, but these cases are often so poorly understood
17080 that all too often adding @code{volatile} to a data structure merely
17081 alleviates some symptoms of a bug while not fixing the bug in general.
17083 @node Floating Point Portability
17084 @section Floating Point Portability
17085 @cindex floating point
17087 Almost all modern systems use IEEE-754 floating point, and it is safe to
17088 assume IEEE-754 in most portable code these days.  For more information,
17089 please see David Goldberg's classic paper
17090 @uref{http://www.validlab.com/goldberg/paper.pdf, What Every Computer
17091 Scientist Should Know About Floating-Point Arithmetic}.
17093 @node Exiting Portably
17094 @section Exiting Portably
17095 @cindex exiting portably
17097 A C or C++ program can exit with status @var{N} by returning
17098 @var{N} from the @code{main} function.  Portable programs are supposed
17099 to exit either with status 0 or @code{EXIT_SUCCESS} to succeed, or with
17100 status @code{EXIT_FAILURE} to fail, but in practice it is portable to
17101 fail by exiting with status 1, and test programs that assume Posix can
17102 fail by exiting with status values from 1 through 255.  Programs on
17103 SunOS 2.0 (1985) through 3.5.2 (1988) incorrectly exited with zero
17104 status when @code{main} returned nonzero, but ancient systems like these
17105 are no longer of practical concern.
17107 A program can also exit with status @var{N} by passing @var{N} to the
17108 @code{exit} function, and a program can fail by calling the @code{abort}
17109 function.  If a program is specialized to just some platforms, it can fail
17110 by calling functions specific to those platforms, e.g., @code{_exit}
17111 (Posix) and @code{_Exit} (C99).  However, like other functions, an exit
17112 function should be declared, typically by including a header.  For
17113 example, if a C program calls @code{exit}, it should include @file{stdlib.h}
17114 either directly or via the default includes (@pxref{Default Includes}).
17116 A program can fail due to undefined behavior such as dereferencing a null
17117 pointer, but this is not recommended as undefined behavior allows an
17118 implementation to do whatever it pleases and this includes exiting
17119 successfully.
17122 @c ================================================== Manual Configuration
17124 @node Manual Configuration
17125 @chapter Manual Configuration
17127 A few kinds of features can't be guessed automatically by running test
17128 programs.  For example, the details of the object-file format, or
17129 special options that need to be passed to the compiler or linker.  You
17130 can check for such features using ad-hoc means, such as having
17131 @command{configure} check the output of the @code{uname} program, or
17132 looking for libraries that are unique to particular systems.  However,
17133 Autoconf provides a uniform method for handling unguessable features.
17135 @menu
17136 * Specifying Names::            Specifying the system type
17137 * Canonicalizing::              Getting the canonical system type
17138 * Using System Type::           What to do with the system type
17139 @end menu
17141 @node Specifying Names
17142 @section Specifying the System Type
17143 @cindex System type
17145 Autoconf-generated
17146 @command{configure} scripts can make decisions based on a canonical name
17147 for the system type, which has the form:
17148 @samp{@var{cpu}-@var{vendor}-@var{os}}, where @var{os} can be
17149 @samp{@var{system}} or @samp{@var{kernel}-@var{system}}
17151 @command{configure} can usually guess the canonical name for the type of
17152 system it's running on.  To do so it runs a script called
17153 @command{config.guess}, which infers the name using the @code{uname}
17154 command or symbols predefined by the C preprocessor.
17156 Alternately, the user can specify the system type with command line
17157 arguments to @command{configure}.  Doing so is necessary when
17158 cross-compiling.  In the most complex case of cross-compiling, three
17159 system types are involved.  The options to specify them are:
17161 @table @option
17162 @item --build=@var{build-type}
17163 the type of system on which the package is being configured and
17164 compiled.  It defaults to the result of running @command{config.guess}.
17166 @item --host=@var{host-type}
17167 the type of system on which the package runs.  By default it is the
17168 same as the build machine.  Specifying it enables the cross-compilation
17169 mode.
17171 @item --target=@var{target-type}
17172 the type of system for which any compiler tools in the package
17173 produce code (rarely needed).  By default, it is the same as host.
17174 @end table
17176 If you mean to override the result of @command{config.guess}, use
17177 @option{--build}, not @option{--host}, since the latter enables
17178 cross-compilation.  For historical reasons,
17179 whenever you specify @option{--host},
17180 be sure to specify @option{--build} too; this will be fixed in the
17181 future.  So, to enter cross-compilation mode, use a command like this
17183 @example
17184 ./configure --build=i686-pc-linux-gnu --host=m68k-coff
17185 @end example
17187 @noindent
17188 Note that if you do not specify @option{--host}, @command{configure}
17189 fails if it can't run the code generated by the specified compiler.  For
17190 example, configuring as follows fails:
17192 @example
17193 ./configure CC=m68k-coff-gcc
17194 @end example
17196 In the future, when cross-compiling Autoconf will @emph{not}
17197 accept tools (compilers, linkers, assemblers) whose name is not
17198 prefixed with the host type.  The only case when this may be
17199 useful is when you really are not cross-compiling, but only
17200 building for a least-common-denominator architecture: an example
17201 is building for @code{i386-pc-linux-gnu} while running on an
17202 @code{i686-pc-linux-gnu} architecture.  In this case, some particular
17203 pairs might be similar enough to let you get away with the system
17204 compilers, but in general the compiler might make bogus assumptions
17205 on the host: if you know what you are doing, please create symbolic
17206 links from the host compiler to the build compiler.
17208 @cindex @command{config.sub}
17209 @command{configure} recognizes short aliases for many system types; for
17210 example, @samp{decstation} can be used instead of
17211 @samp{mips-dec-ultrix4.2}.  @command{configure} runs a script called
17212 @command{config.sub} to canonicalize system type aliases.
17214 This section deliberately omits the description of the obsolete
17215 interface; see @ref{Hosts and Cross-Compilation}.
17218 @node Canonicalizing
17219 @section Getting the Canonical System Type
17220 @cindex System type
17221 @cindex Canonical system type
17223 The following macros make the system type available to @command{configure}
17224 scripts.
17226 @ovindex build_alias
17227 @ovindex host_alias
17228 @ovindex target_alias
17230 The variables @samp{build_alias}, @samp{host_alias}, and
17231 @samp{target_alias} are always exactly the arguments of @option{--build},
17232 @option{--host}, and @option{--target}; in particular, they are left empty
17233 if the user did not use them, even if the corresponding
17234 @code{AC_CANONICAL} macro was run.  Any configure script may use these
17235 variables anywhere.  These are the variables that should be used when in
17236 interaction with the user.
17238 If you need to recognize some special environments based on their system
17239 type, run the following macros to get canonical system names.  These
17240 variables are not set before the macro call.
17242 If you use these macros, you must distribute @command{config.guess} and
17243 @command{config.sub} along with your source code.  @xref{Output}, for
17244 information about the @code{AC_CONFIG_AUX_DIR} macro which you can use
17245 to control in which directory @command{configure} looks for those scripts.
17248 @defmac AC_CANONICAL_BUILD
17249 @acindex{CANONICAL_BUILD}
17250 @ovindex build
17251 @ovindex build_cpu
17252 @ovindex build_vendor
17253 @ovindex build_os
17254 Compute the canonical build-system type variable, @code{build}, and its
17255 three individual parts @code{build_cpu}, @code{build_vendor}, and
17256 @code{build_os}.
17258 If @option{--build} was specified, then @code{build} is the
17259 canonicalization of @code{build_alias} by @command{config.sub},
17260 otherwise it is determined by the shell script @command{config.guess}.
17261 @end defmac
17263 @defmac AC_CANONICAL_HOST
17264 @acindex{CANONICAL_HOST}
17265 @ovindex host
17266 @ovindex host_cpu
17267 @ovindex host_vendor
17268 @ovindex host_os
17269 Compute the canonical host-system type variable, @code{host}, and its
17270 three individual parts @code{host_cpu}, @code{host_vendor}, and
17271 @code{host_os}.
17273 If @option{--host} was specified, then @code{host} is the
17274 canonicalization of @code{host_alias} by @command{config.sub},
17275 otherwise it defaults to @code{build}.
17276 @end defmac
17278 @defmac AC_CANONICAL_TARGET
17279 @acindex{CANONICAL_TARGET}
17280 @ovindex target
17281 @ovindex target_cpu
17282 @ovindex target_vendor
17283 @ovindex target_os
17284 Compute the canonical target-system type variable, @code{target}, and its
17285 three individual parts @code{target_cpu}, @code{target_vendor}, and
17286 @code{target_os}.
17288 If @option{--target} was specified, then @code{target} is the
17289 canonicalization of @code{target_alias} by @command{config.sub},
17290 otherwise it defaults to @code{host}.
17291 @end defmac
17293 Note that there can be artifacts due to the backward compatibility
17294 code.  See @xref{Hosts and Cross-Compilation}, for more.
17296 @node Using System Type
17297 @section Using the System Type
17299 In @file{configure.ac} the system type is generally used by one or more
17300 @code{case} statements to select system-specifics.  Shell wildcards can
17301 be used to match a group of system types.
17303 For example, an extra assembler code object file could be chosen, giving
17304 access to a CPU cycle counter register.  @code{$(CYCLE_OBJ)} in the
17305 following would be used in a makefile to add the object to a
17306 program or library.
17308 @example
17309 case $host in
17310   alpha*-*-*) CYCLE_OBJ=rpcc.o ;;
17311   i?86-*-*)   CYCLE_OBJ=rdtsc.o ;;
17312   *)          CYCLE_OBJ= ;;
17313 esac
17314 AC_SUBST([CYCLE_OBJ])
17315 @end example
17317 @code{AC_CONFIG_LINKS} (@pxref{Configuration Links}) is another good way
17318 to select variant source files, for example optimized code for some
17319 CPUs.  The configured CPU type doesn't always indicate exact CPU types,
17320 so some runtime capability checks may be necessary too.
17322 @example
17323 case $host in
17324   alpha*-*-*)   AC_CONFIG_LINKS([dither.c:alpha/dither.c]) ;;
17325   powerpc*-*-*) AC_CONFIG_LINKS([dither.c:powerpc/dither.c]) ;;
17326   *-*-*)        AC_CONFIG_LINKS([dither.c:generic/dither.c]) ;;
17327 esac
17328 @end example
17330 The host system type can also be used to find cross-compilation tools
17331 with @code{AC_CHECK_TOOL} (@pxref{Generic Programs}).
17333 The above examples all show @samp{$host}, since this is where the code
17334 is going to run.  Only rarely is it necessary to test @samp{$build}
17335 (which is where the build is being done).
17337 Whenever you're tempted to use @samp{$host} it's worth considering
17338 whether some sort of probe would be better.  New system types come along
17339 periodically or previously missing features are added.  Well-written
17340 probes can adapt themselves to such things, but hard-coded lists of
17341 names can't.  Here are some guidelines,
17343 @itemize @bullet
17344 @item
17345 Availability of libraries and library functions should always be checked
17346 by probing.
17347 @item
17348 Variant behavior of system calls is best identified with runtime tests
17349 if possible, but bug workarounds or obscure difficulties might have to
17350 be driven from @samp{$host}.
17351 @item
17352 Assembler code is inevitably highly CPU-specific and is best selected
17353 according to @samp{$host_cpu}.
17354 @item
17355 Assembler variations like underscore prefix on globals or ELF versus
17356 COFF type directives are however best determined by probing, perhaps
17357 even examining the compiler output.
17358 @end itemize
17360 @samp{$target} is for use by a package creating a compiler or similar.
17361 For ordinary packages it's meaningless and should not be used.  It
17362 indicates what the created compiler should generate code for, if it can
17363 cross-compile.  @samp{$target} generally selects various hard-coded CPU
17364 and system conventions, since usually the compiler or tools under
17365 construction themselves determine how the target works.
17368 @c ===================================================== Site Configuration.
17370 @node Site Configuration
17371 @chapter Site Configuration
17373 @command{configure} scripts support several kinds of local configuration
17374 decisions.  There are ways for users to specify where external software
17375 packages are, include or exclude optional features, install programs
17376 under modified names, and set default values for @command{configure}
17377 options.
17379 @menu
17380 * Help Formatting::             Customizing @samp{configure --help}
17381 * External Software::           Working with other optional software
17382 * Package Options::             Selecting optional features
17383 * Pretty Help Strings::         Formatting help string
17384 * Option Checking::             Controlling checking of @command{configure} options
17385 * Site Details::                Configuring site details
17386 * Transforming Names::          Changing program names when installing
17387 * Site Defaults::               Giving @command{configure} local defaults
17388 @end menu
17390 @node Help Formatting
17391 @section Controlling Help Output
17393 Users consult @samp{configure --help} to learn of configuration
17394 decisions specific to your package.  By default, @command{configure}
17395 breaks this output into sections for each type of option; within each
17396 section, help strings appear in the order @file{configure.ac} defines
17397 them:
17399 @example
17400 Optional Features:
17401   @dots{}
17402   --enable-bar            include bar
17404 Optional Packages:
17405   @dots{}
17406   --with-foo              use foo
17407 @end example
17409 @defmac AC_PRESERVE_HELP_ORDER
17410 @acindex{PRESERVE_HELP_ORDER}
17412 Request an alternate @option{--help} format, in which options of all
17413 types appear together, in the order defined.  Call this macro before any
17414 @code{AC_ARG_ENABLE} or @code{AC_ARG_WITH}.
17416 @example
17417 Optional Features and Packages:
17418   @dots{}
17419   --enable-bar            include bar
17420   --with-foo              use foo
17421 @end example
17423 @end defmac
17425 @node External Software
17426 @section Working With External Software
17427 @cindex External software
17429 Some packages require, or can optionally use, other software packages
17430 that are already installed.  The user can give @command{configure}
17431 command line options to specify which such external software to use.
17432 The options have one of these forms:
17434 @c FIXME: Can't use @ovar here, Texinfo 4.0 goes lunatic and emits something
17435 @c awful.
17436 @example
17437 --with-@var{package}[=@var{arg}]
17438 --without-@var{package}
17439 @end example
17441 For example, @option{--with-gnu-ld} means work with the @acronym{GNU} linker
17442 instead of some other linker.  @option{--with-x} means work with The X
17443 Window System.
17445 The user can give an argument by following the package name with
17446 @samp{=} and the argument.  Giving an argument of @samp{no} is for
17447 packages that are used by default; it says to @emph{not} use the
17448 package.  An argument that is neither @samp{yes} nor @samp{no} could
17449 include a name or number of a version of the other package, to specify
17450 more precisely which other package this program is supposed to work
17451 with.  If no argument is given, it defaults to @samp{yes}.
17452 @option{--without-@var{package}} is equivalent to
17453 @option{--with-@var{package}=no}.
17455 Normally @command{configure} scripts complain about
17456 @option{--with-@var{package}} options that they do not support.
17457 @xref{Option Checking}, for details, and for how to override the
17458 defaults.
17460 For each external software package that may be used, @file{configure.ac}
17461 should call @code{AC_ARG_WITH} to detect whether the @command{configure}
17462 user asked to use it.  Whether each package is used or not by default,
17463 and which arguments are valid, is up to you.
17465 @anchor{AC_ARG_WITH}
17466 @defmac AC_ARG_WITH (@var{package}, @var{help-string}, @
17467   @ovar{action-if-given}, @ovar{action-if-not-given})
17468 @acindex{ARG_WITH}
17469 If the user gave @command{configure} the option @option{--with-@var{package}}
17470 or @option{--without-@var{package}}, run shell commands
17471 @var{action-if-given}.  If neither option was given, run shell commands
17472 @var{action-if-not-given}.  The name @var{package} indicates another
17473 software package that this program should work with.  It should consist
17474 only of alphanumeric characters, dashes, and dots.
17476 The option's argument is available to the shell commands
17477 @var{action-if-given} in the shell variable @code{withval}, which is
17478 actually just the value of the shell variable named
17479 @code{with_@var{package}}, with any non-alphanumeric characters in
17480 @var{package} changed into @samp{_}.  You may use that variable instead,
17481 if you wish.
17483 The argument @var{help-string} is a description of the option that
17484 looks like this:
17485 @example
17486   --with-readline         support fancy command line editing
17487 @end example
17489 @noindent
17490 @var{help-string} may be more than one line long, if more detail is
17491 needed.  Just make sure the columns line up in @samp{configure
17492 --help}.  Avoid tabs in the help string.  You'll need to enclose the
17493 help string in @samp{[} and @samp{]} in order to produce the leading
17494 blanks.
17496 You should format your @var{help-string} with the macro
17497 @code{AS_HELP_STRING} (@pxref{Pretty Help Strings}).
17499 The following example shows how to use the @code{AC_ARG_WITH} macro in
17500 a common situation.  You want to let the user decide whether to enable
17501 support for an external library (e.g., the readline library); if the user
17502 specified neither @option{--with-readline} nor @option{--without-readline},
17503 you want to enable support for readline only if the library is available
17504 on the system.
17506 @c FIXME: Remove AS_IF when the problem of AC_REQUIRE within `if' is solved.
17507 @example
17508 AC_ARG_WITH([readline],
17509   [AS_HELP_STRING([--with-readline],
17510     [support fancy command line editing @@<:@@default=check@@:>@@])],
17511   [],
17512   [with_readline=check])
17514 LIBREADLINE=
17515 AS_IF([test "x$with_readline" != xno],
17516   [AC_CHECK_LIB([readline], [main],
17517     [AC_SUBST([LIBREADLINE], ["-lreadline -lncurses"])
17518      AC_DEFINE([HAVE_LIBREADLINE], [1],
17519                [Define if you have libreadline])
17520     ],
17521     [if test "x$with_readline" != xcheck; then
17522        AC_MSG_FAILURE(
17523          [--with-readline was given, but test for readline failed])
17524      fi
17525     ], -lncurses)])
17526 @end example
17528 The next example shows how to use @code{AC_ARG_WITH} to give the user the
17529 possibility to enable support for the readline library, in case it is still
17530 experimental and not well tested, and is therefore disabled by default.
17532 @c FIXME: Remove AS_IF when the problem of AC_REQUIRE within `if' is solved.
17533 @example
17534 AC_ARG_WITH([readline],
17535   [AS_HELP_STRING([--with-readline],
17536     [enable experimental support for readline])],
17537   [],
17538   [with_readline=no])
17540 LIBREADLINE=
17541 AS_IF([test "x$with_readline" != xno],
17542   [AC_CHECK_LIB([readline], [main],
17543     [AC_SUBST([LIBREADLINE], ["-lreadline -lncurses"])
17544      AC_DEFINE([HAVE_LIBREADLINE], [1],
17545                [Define if you have libreadline])
17546     ],
17547     [AC_MSG_FAILURE(
17548        [--with-readline was given, but test for readline failed])],
17549     [-lncurses])])
17550 @end example
17552 The last example shows how to use @code{AC_ARG_WITH} to give the user the
17553 possibility to disable support for the readline library, given that it is
17554 an important feature and that it should be enabled by default.
17556 @c FIXME: Remove AS_IF when the problem of AC_REQUIRE within `if' is solved.
17557 @example
17558 AC_ARG_WITH([readline],
17559   [AS_HELP_STRING([--without-readline],
17560     [disable support for readline])],
17561   [],
17562   [with_readline=yes])
17564 LIBREADLINE=
17565 AS_IF([test "x$with_readline" != xno],
17566   [AC_CHECK_LIB([readline], [main],
17567     [AC_SUBST([LIBREADLINE], ["-lreadline -lncurses"])
17568      AC_DEFINE([HAVE_LIBREADLINE], [1],
17569                [Define if you have libreadline])
17570     ],
17571     [AC_MSG_FAILURE(
17572        [readline test failed (--without-readline to disable)])],
17573     [-lncurses])])
17574 @end example
17576 These three examples can be easily adapted to the case where
17577 @code{AC_ARG_ENABLE} should be preferred to @code{AC_ARG_WITH} (see
17578 @ref{Package Options}).
17579 @end defmac
17581 @node Package Options
17582 @section Choosing Package Options
17583 @cindex Package options
17584 @cindex Options, package
17586 If a software package has optional compile-time features, the user can
17587 give @command{configure} command line options to specify whether to
17588 compile them.  The options have one of these forms:
17590 @c FIXME: Can't use @ovar here, Texinfo 4.0 goes lunatic and emits something
17591 @c awful.
17592 @example
17593 --enable-@var{feature}[=@var{arg}]
17594 --disable-@var{feature}
17595 @end example
17597 These options allow users to choose which optional features to build and
17598 install.  @option{--enable-@var{feature}} options should never make a
17599 feature behave differently or cause one feature to replace another.
17600 They should only cause parts of the program to be built rather than left
17601 out.
17603 The user can give an argument by following the feature name with
17604 @samp{=} and the argument.  Giving an argument of @samp{no} requests
17605 that the feature @emph{not} be made available.  A feature with an
17606 argument looks like @option{--enable-debug=stabs}.  If no argument is
17607 given, it defaults to @samp{yes}.  @option{--disable-@var{feature}} is
17608 equivalent to @option{--enable-@var{feature}=no}.
17610 Normally @command{configure} scripts complain about
17611 @option{--enable-@var{package}} options that they do not support.
17612 @xref{Option Checking}, for details, and for how to override the
17613 defaults.
17615 For each optional feature, @file{configure.ac} should call
17616 @code{AC_ARG_ENABLE} to detect whether the @command{configure} user asked
17617 to include it.  Whether each feature is included or not by default, and
17618 which arguments are valid, is up to you.
17620 @anchor{AC_ARG_ENABLE}
17621 @defmac AC_ARG_ENABLE (@var{feature}, @var{help-string}, @
17622   @ovar{action-if-given}, @ovar{action-if-not-given})
17623 @acindex{ARG_ENABLE}
17624 If the user gave @command{configure} the option
17625 @option{--enable-@var{feature}} or @option{--disable-@var{feature}}, run
17626 shell commands @var{action-if-given}.  If neither option was given, run
17627 shell commands @var{action-if-not-given}.  The name @var{feature}
17628 indicates an optional user-level facility.  It should consist only of
17629 alphanumeric characters, dashes, and dots.
17631 The option's argument is available to the shell commands
17632 @var{action-if-given} in the shell variable @code{enableval}, which is
17633 actually just the value of the shell variable named
17634 @code{enable_@var{feature}}, with any non-alphanumeric characters in
17635 @var{feature} changed into @samp{_}.  You may use that variable instead,
17636 if you wish.  The @var{help-string} argument is like that of
17637 @code{AC_ARG_WITH} (@pxref{External Software}).
17639 You should format your @var{help-string} with the macro
17640 @code{AS_HELP_STRING} (@pxref{Pretty Help Strings}).
17642 See the examples suggested with the definition of @code{AC_ARG_WITH}
17643 (@pxref{External Software}) to get an idea of possible applications of
17644 @code{AC_ARG_ENABLE}.
17645 @end defmac
17647 @node Pretty Help Strings
17648 @section Making Your Help Strings Look Pretty
17649 @cindex Help strings
17651 Properly formatting the @samp{help strings} which are used in
17652 @code{AC_ARG_WITH} (@pxref{External Software}) and @code{AC_ARG_ENABLE}
17653 (@pxref{Package Options}) can be challenging.  Specifically, you want
17654 your own @samp{help strings} to line up in the appropriate columns of
17655 @samp{configure --help} just like the standard Autoconf @samp{help
17656 strings} do.  This is the purpose of the @code{AS_HELP_STRING} macro.
17658 @anchor{AS_HELP_STRING}
17659 @defmac AS_HELP_STRING (@var{left-hand-side}, @var{right-hand-side} @
17660   @dvar{indent-column, 26}, @dvar{wrap-column, 79})
17661 @asindex{HELP_STRING}
17663 Expands into an help string that looks pretty when the user executes
17664 @samp{configure --help}.  It is typically used in @code{AC_ARG_WITH}
17665 (@pxref{External Software}) or @code{AC_ARG_ENABLE} (@pxref{Package
17666 Options}).  The following example makes this clearer.
17668 @example
17669 AC_ARG_WITH([foo],
17670   [AS_HELP_STRING([--with-foo],
17671      [use foo (default is no)])],
17672   [use_foo=$withval],
17673   [use_foo=no])
17674 @end example
17676 Then the last few lines of @samp{configure --help} appear like
17677 this:
17679 @example
17680 --enable and --with options recognized:
17681   --with-foo              use foo (default is no)
17682 @end example
17684 Macro expansion is performed on the first argument.  However, the second
17685 argument of @code{AS_HELP_STRING} is treated as a whitespace separated
17686 list of text to be reformatted, and is not subject to macro expansion.
17687 Since it is not expanded, it should not be double quoted.
17688 @xref{Autoconf Language}, for a more detailed explanation.
17690 The @code{AS_HELP_STRING} macro is particularly helpful when the
17691 @var{left-hand-side} and/or @var{right-hand-side} are composed of macro
17692 arguments, as shown in the following example.  Be aware that
17693 @var{left-hand-side} may not contain unbalanced quotes or parentheses.
17695 @example
17696 AC_DEFUN([MY_ARG_WITH],
17697   [AC_ARG_WITH(m4_translit([[$1]], [_], [-]),
17698      [AS_HELP_STRING([--with-m4_translit([$1], [_], [-])],
17699                      [use $1 (default is $2)])],
17700      [use_[]$1=$withval],
17701      [use_[]$1=$2])])
17702 MY_ARG_WITH([a_b], [no])
17703 @end example
17704 @noindent
17705 Here, the last few lines of @samp{configure --help} will include:
17707 @example
17708 --enable and --with options recognized:
17709   --with-a-b              use a_b (default is no)
17710 @end example
17712 The parameters @var{indent-column} and @var{wrap-column} were introduced
17713 in Autoconf 2.62.  Generally, they should not be specified; they exist
17714 for fine-tuning of the wrapping.
17715 @example
17716 AS_HELP_STRING([--option], [description of option])
17717 @result{}  --option                description of option
17718 AS_HELP_STRING([--option], [description of option], [15], [30])
17719 @result{}  --option     description of
17720 @result{}               option
17721 @end example
17722 @end defmac
17725 @node Option Checking
17726 @section Controlling Checking of @command{configure} Options
17727 @cindex Options, Package
17729 The @command{configure} script checks its command-line options against a
17730 list of known options, like @option{--help} or @option{--config-cache}.
17731 An unknown option ordinarily indicates a mistake by the user and
17732 @command{configure} halts with an error.  However, by default unknown
17733 @option{--with-@var{package}} and @option{--enable-@var{feature}}
17734 options elicit only a warning, to support configuring entire source
17735 trees.
17737 Source trees often contain multiple packages with a top-level
17738 @command{configure} script that uses the @code{AC_CONFIG_SUBDIRS} macro
17739 (@pxref{Subdirectories}).  Because the packages generally support
17740 different @option{--with-@var{package}} and
17741 @option{--enable-@var{feature}} options, the @acronym{GNU} Coding
17742 Standards say they must accept unrecognized options without halting.
17743 Even a warning message is undesirable here, so @code{AC_CONFIG_SUBDIRS}
17744 automatically disables the warnings.
17746 This default behavior may be modified in two ways.  First, the installer
17747 can invoke @command{configure --disable-option-checking} to disable
17748 these warnings, or invoke @command{configure --enable-option-checking=fatal}
17749 options to turn them into fatal errors, respectively.  Second, the
17750 maintainer can use @code{AC_DISABLE_OPTION_CHECKING}.
17752 @defmac AC_DISABLE_OPTION_CHECKING
17753 @acindex{DISABLE_OPTION_CHECKING}
17755 By default, disable warnings related to any unrecognized
17756 @option{--with-@var{package}} or @option{--enable-@var{feature}}
17757 options.  This is implied by @code{AC_CONFIG_SUBDIRS}.
17759 The installer can override this behavior by passing
17760 @option{--enable-option-checking} (enable warnings) or
17761 @option{--enable-option-checking=fatal} (enable errors) to
17762 @command{configure}.
17763 @end defmac
17766 @node Site Details
17767 @section Configuring Site Details
17768 @cindex Site details
17770 Some software packages require complex site-specific information.  Some
17771 examples are host names to use for certain services, company names, and
17772 email addresses to contact.  Since some configuration scripts generated
17773 by Metaconfig ask for such information interactively, people sometimes
17774 wonder how to get that information in Autoconf-generated configuration
17775 scripts, which aren't interactive.
17777 Such site configuration information should be put in a file that is
17778 edited @emph{only by users}, not by programs.  The location of the file
17779 can either be based on the @code{prefix} variable, or be a standard
17780 location such as the user's home directory.  It could even be specified
17781 by an environment variable.  The programs should examine that file at
17782 runtime, rather than at compile time.  Runtime configuration is more
17783 convenient for users and makes the configuration process simpler than
17784 getting the information while configuring.  @xref{Directory Variables, ,
17785 Variables for Installation Directories, standards, @acronym{GNU} Coding
17786 Standards}, for more information on where to put data files.
17788 @node Transforming Names
17789 @section Transforming Program Names When Installing
17790 @cindex Transforming program names
17791 @cindex Program names, transforming
17793 Autoconf supports changing the names of programs when installing them.
17794 In order to use these transformations, @file{configure.ac} must call the
17795 macro @code{AC_ARG_PROGRAM}.
17797 @defmac AC_ARG_PROGRAM
17798 @acindex{ARG_PROGRAM}
17799 @ovindex program_transform_name
17800 Place in output variable @code{program_transform_name} a sequence of
17801 @code{sed} commands for changing the names of installed programs.
17803 If any of the options described below are given to @command{configure},
17804 program names are transformed accordingly.  Otherwise, if
17805 @code{AC_CANONICAL_TARGET} has been called and a @option{--target} value
17806 is given, the target type followed by a dash is used as a prefix.
17807 Otherwise, no program name transformation is done.
17808 @end defmac
17810 @menu
17811 * Transformation Options::      @command{configure} options to transform names
17812 * Transformation Examples::     Sample uses of transforming names
17813 * Transformation Rules::        Makefile uses of transforming names
17814 @end menu
17816 @node Transformation Options
17817 @subsection Transformation Options
17819 You can specify name transformations by giving @command{configure} these
17820 command line options:
17822 @table @option
17823 @item --program-prefix=@var{prefix}
17824 prepend @var{prefix} to the names;
17826 @item --program-suffix=@var{suffix}
17827 append @var{suffix} to the names;
17829 @item --program-transform-name=@var{expression}
17830 perform @code{sed} substitution @var{expression} on the names.
17831 @end table
17833 @node Transformation Examples
17834 @subsection Transformation Examples
17836 These transformations are useful with programs that can be part of a
17837 cross-compilation development environment.  For example, a
17838 cross-assembler running on a Sun 4 configured with
17839 @option{--target=i960-vxworks} is normally installed as
17840 @file{i960-vxworks-as}, rather than @file{as}, which could be confused
17841 with a native Sun 4 assembler.
17843 You can force a program name to begin with @file{g}, if you don't want
17844 @acronym{GNU} programs installed on your system to shadow other programs with
17845 the same name.  For example, if you configure @acronym{GNU} @code{diff} with
17846 @option{--program-prefix=g}, then when you run @samp{make install} it is
17847 installed as @file{/usr/local/bin/gdiff}.
17849 As a more sophisticated example, you could use
17851 @example
17852 --program-transform-name='s/^/g/; s/^gg/g/; s/^gless/less/'
17853 @end example
17854 @noindent
17856 to prepend @samp{g} to most of the program names in a source tree,
17857 excepting those like @code{gdb} that already have one and those like
17858 @code{less} and @code{lesskey} that aren't @acronym{GNU} programs.  (That is
17859 assuming that you have a source tree containing those programs that is
17860 set up to use this feature.)
17862 One way to install multiple versions of some programs simultaneously is
17863 to append a version number to the name of one or both.  For example, if
17864 you want to keep Autoconf version 1 around for awhile, you can configure
17865 Autoconf version 2 using @option{--program-suffix=2} to install the
17866 programs as @file{/usr/local/bin/autoconf2},
17867 @file{/usr/local/bin/autoheader2}, etc.  Nevertheless, pay attention
17868 that only the binaries are renamed, therefore you'd have problems with
17869 the library files which might overlap.
17871 @node Transformation Rules
17872 @subsection Transformation Rules
17874 Here is how to use the variable @code{program_transform_name} in a
17875 @file{Makefile.in}:
17877 @example
17878 PROGRAMS = cp ls rm
17879 transform = @@program_transform_name@@
17880 install:
17881         for p in $(PROGRAMS); do \
17882           $(INSTALL_PROGRAM) $$p $(DESTDIR)$(bindir)/`echo $$p | \
17883                                               sed '$(transform)'`; \
17884         done
17886 uninstall:
17887         for p in $(PROGRAMS); do \
17888           rm -f $(DESTDIR)$(bindir)/`echo $$p | sed '$(transform)'`; \
17889         done
17890 @end example
17892 It is guaranteed that @code{program_transform_name} is never empty, and
17893 that there are no useless separators.  Therefore you may safely embed
17894 @code{program_transform_name} within a sed program using @samp{;}:
17896 @example
17897 transform = @@program_transform_name@@
17898 transform_exe = s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/
17899 @end example
17901 Whether to do the transformations on documentation files (Texinfo or
17902 @code{man}) is a tricky question; there seems to be no perfect answer,
17903 due to the several reasons for name transforming.  Documentation is not
17904 usually particular to a specific architecture, and Texinfo files do not
17905 conflict with system documentation.  But they might conflict with
17906 earlier versions of the same files, and @code{man} pages sometimes do
17907 conflict with system documentation.  As a compromise, it is probably
17908 best to do name transformations on @code{man} pages but not on Texinfo
17909 manuals.
17911 @node Site Defaults
17912 @section Setting Site Defaults
17913 @cindex Site defaults
17915 Autoconf-generated @command{configure} scripts allow your site to provide
17916 default values for some configuration values.  You do this by creating
17917 site- and system-wide initialization files.
17919 @evindex CONFIG_SITE
17920 If the environment variable @code{CONFIG_SITE} is set, @command{configure}
17921 uses its value as the name of a shell script to read.  Otherwise, it
17922 reads the shell script @file{@var{prefix}/share/config.site} if it exists,
17923 then @file{@var{prefix}/etc/config.site} if it exists.  Thus,
17924 settings in machine-specific files override those in machine-independent
17925 ones in case of conflict.
17927 Site files can be arbitrary shell scripts, but only certain kinds of
17928 code are really appropriate to be in them.  Because @command{configure}
17929 reads any cache file after it has read any site files, a site file can
17930 define a default cache file to be shared between all Autoconf-generated
17931 @command{configure} scripts run on that system (@pxref{Cache Files}).  If
17932 you set a default cache file in a site file, it is a good idea to also
17933 set the output variable @code{CC} in that site file, because the cache
17934 file is only valid for a particular compiler, but many systems have
17935 several available.
17937 You can examine or override the value set by a command line option to
17938 @command{configure} in a site file; options set shell variables that have
17939 the same names as the options, with any dashes turned into underscores.
17940 The exceptions are that @option{--without-} and @option{--disable-} options
17941 are like giving the corresponding @option{--with-} or @option{--enable-}
17942 option and the value @samp{no}.  Thus, @option{--cache-file=localcache}
17943 sets the variable @code{cache_file} to the value @samp{localcache};
17944 @option{--enable-warnings=no} or @option{--disable-warnings} sets the variable
17945 @code{enable_warnings} to the value @samp{no}; @option{--prefix=/usr} sets the
17946 variable @code{prefix} to the value @samp{/usr}; etc.
17948 Site files are also good places to set default values for other output
17949 variables, such as @code{CFLAGS}, if you need to give them non-default
17950 values: anything you would normally do, repetitively, on the command
17951 line.  If you use non-default values for @var{prefix} or
17952 @var{exec_prefix} (wherever you locate the site file), you can set them
17953 in the site file if you specify it with the @code{CONFIG_SITE}
17954 environment variable.
17956 You can set some cache values in the site file itself.  Doing this is
17957 useful if you are cross-compiling, where it is impossible to check features
17958 that require running a test program.  You could ``prime the cache'' by
17959 setting those values correctly for that system in
17960 @file{@var{prefix}/etc/config.site}.  To find out the names of the cache
17961 variables you need to set, look for shell variables with @samp{_cv_} in
17962 their names in the affected @command{configure} scripts, or in the Autoconf
17963 M4 source code for those macros.
17965 The cache file is careful to not override any variables set in the site
17966 files.  Similarly, you should not override command-line options in the
17967 site files.  Your code should check that variables such as @code{prefix}
17968 and @code{cache_file} have their default values (as set near the top of
17969 @command{configure}) before changing them.
17971 Here is a sample file @file{/usr/share/local/gnu/share/config.site}.  The
17972 command @samp{configure --prefix=/usr/share/local/gnu} would read this
17973 file (if @code{CONFIG_SITE} is not set to a different file).
17975 @example
17976 # config.site for configure
17978 # Change some defaults.
17979 test "$prefix" = NONE && prefix=/usr/share/local/gnu
17980 test "$exec_prefix" = NONE && exec_prefix=/usr/local/gnu
17981 test "$sharedstatedir" = '$@{prefix@}/com' && sharedstatedir=/var
17982 test "$localstatedir" = '$@{prefix@}/var' && localstatedir=/var
17984 # Give Autoconf 2.x generated configure scripts a shared default
17985 # cache file for feature test results, architecture-specific.
17986 if test "$cache_file" = /dev/null; then
17987   cache_file="$prefix/var/config.cache"
17988   # A cache file is only valid for one C compiler.
17989   CC=gcc
17991 @end example
17993 @cindex Filesystem Hierarchy Standard
17994 @cindex FHS
17996 Another use of @file{config.site} is for priming the directory variables
17997 in a manner consistent with the Filesystem Hierarchy Standard
17998 (@acronym{FHS}).  Once the following file is installed at
17999 @file{/usr/share/config.site}, a user can execute simply
18000 @command{./configure --prefix=/usr} to get all the directories chosen in
18001 the locations recommended by @acronym{FHS}.
18003 @example
18004 # /usr/local/config.site for FHS defaults when installing below /usr,
18005 # and the respective settings were not changed on the command line.
18006 if test "$prefix" = /usr; then
18007   test "$sysconfdir" = '$@{prefix@}/etc' && sysconfdir=/etc
18008   test "$sharedstatedir" = '$@{prefix@}/com' && sharedstatedir=/var
18009   test "$localstatedir" = '$@{prefix@}/var' && localstatedir=/var
18011 @end example
18014 @c ============================================== Running configure Scripts.
18016 @node Running configure Scripts
18017 @chapter Running @command{configure} Scripts
18018 @cindex @command{configure}
18020 Below are instructions on how to configure a package that uses a
18021 @command{configure} script, suitable for inclusion as an @file{INSTALL}
18022 file in the package.  A plain-text version of @file{INSTALL} which you
18023 may use comes with Autoconf.
18025 @menu
18026 * Basic Installation::          Instructions for typical cases
18027 * Compilers and Options::       Selecting compilers and optimization
18028 * Multiple Architectures::      Compiling for multiple architectures at once
18029 * Installation Names::          Installing in different directories
18030 * Optional Features::           Selecting optional features
18031 * System Type::                 Specifying the system type
18032 * Sharing Defaults::            Setting site-wide defaults for @command{configure}
18033 * Defining Variables::          Specifying the compiler etc.
18034 * configure Invocation::        Changing how @command{configure} runs
18035 @end menu
18037 @set autoconf
18038 @include install.texi
18041 @c ============================================== config.status Invocation
18043 @node config.status Invocation
18044 @chapter config.status Invocation
18045 @cindex @command{config.status}
18047 The @command{configure} script creates a file named @file{config.status},
18048 which actually configures, @dfn{instantiates}, the template files.  It
18049 also records the configuration options that were specified when the
18050 package was last configured in case reconfiguring is needed.
18052 Synopsis:
18053 @example
18054 ./config.status @var{option}@dots{} [@var{file}@dots{}]
18055 @end example
18057 It configures the @var{files}; if none are specified, all the templates
18058 are instantiated.  The files must be specified without their
18059 dependencies, as in
18061 @example
18062 ./config.status foobar
18063 @end example
18065 @noindent
18068 @example
18069 ./config.status foobar:foo.in:bar.in
18070 @end example
18072 The supported options are:
18074 @table @option
18075 @item --help
18076 @itemx -h
18077 Print a summary of the command line options, the list of the template
18078 files, and exit.
18080 @item --version
18081 @itemx -V
18082 Print the version number of Autoconf and the configuration settings,
18083 and exit.
18085 @item --silent
18086 @itemx --quiet
18087 @itemx -q
18088 Do not print progress messages.
18090 @item --debug
18091 @itemx -d
18092 Don't remove the temporary files.
18094 @item --file=@var{file}[:@var{template}]
18095 Require that @var{file} be instantiated as if
18096 @samp{AC_CONFIG_FILES(@var{file}:@var{template})} was used.  Both
18097 @var{file} and @var{template} may be @samp{-} in which case the standard
18098 output and/or standard input, respectively, is used.  If a
18099 @var{template} file name is relative, it is first looked for in the build
18100 tree, and then in the source tree.  @xref{Configuration Actions}, for
18101 more details.
18103 This option and the following ones provide one way for separately
18104 distributed packages to share the values computed by @command{configure}.
18105 Doing so can be useful if some of the packages need a superset of the
18106 features that one of them, perhaps a common library, does.  These
18107 options allow a @file{config.status} file to create files other than the
18108 ones that its @file{configure.ac} specifies, so it can be used for a
18109 different package.
18111 @item --header=@var{file}[:@var{template}]
18112 Same as @option{--file} above, but with @samp{AC_CONFIG_HEADERS}.
18114 @item --recheck
18115 Ask @file{config.status} to update itself and exit (no instantiation).
18116 This option is useful if you change @command{configure}, so that the
18117 results of some tests might be different from the previous run.  The
18118 @option{--recheck} option reruns @command{configure} with the same arguments
18119 you used before, plus the @option{--no-create} option, which prevents
18120 @command{configure} from running @file{config.status} and creating
18121 @file{Makefile} and other files, and the @option{--no-recursion} option,
18122 which prevents @command{configure} from running other @command{configure}
18123 scripts in subdirectories.  (This is so other Make rules can
18124 run @file{config.status} when it changes; @pxref{Automatic Remaking},
18125 for an example).
18126 @end table
18128 @file{config.status} checks several optional environment variables that
18129 can alter its behavior:
18131 @defvar CONFIG_SHELL
18132 @evindex CONFIG_SHELL
18133 The shell with which to run @command{configure} for the @option{--recheck}
18134 option.  It must be Bourne-compatible.  The default is a shell that
18135 supports @code{LINENO} if available, and @file{/bin/sh} otherwise.
18136 Invoking @command{configure} by hand bypasses this setting, so you may
18137 need to use a command like @samp{CONFIG_SHELL=/bin/bash /bin/bash ./configure}
18138 to insure that the same shell is used everywhere.  The absolute name of the
18139 shell should be passed.
18140 @end defvar
18142 @defvar CONFIG_STATUS
18143 @evindex CONFIG_STATUS
18144 The file name to use for the shell script that records the
18145 configuration.  The default is @file{./config.status}.  This variable is
18146 useful when one package uses parts of another and the @command{configure}
18147 scripts shouldn't be merged because they are maintained separately.
18148 @end defvar
18150 You can use @file{./config.status} in your makefiles.  For example, in
18151 the dependencies given above (@pxref{Automatic Remaking}),
18152 @file{config.status} is run twice when @file{configure.ac} has changed.
18153 If that bothers you, you can make each run only regenerate the files for
18154 that rule:
18155 @example
18156 @group
18157 config.h: stamp-h
18158 stamp-h: config.h.in config.status
18159         ./config.status config.h
18160         echo > stamp-h
18162 Makefile: Makefile.in config.status
18163         ./config.status Makefile
18164 @end group
18165 @end example
18167 The calling convention of @file{config.status} has changed; see
18168 @ref{Obsolete config.status Use}, for details.
18171 @c =================================================== Obsolete Constructs
18173 @node Obsolete Constructs
18174 @chapter Obsolete Constructs
18175 @cindex Obsolete constructs
18177 Autoconf changes, and throughout the years some constructs have been
18178 obsoleted.  Most of the changes involve the macros, but in some cases
18179 the tools themselves, or even some concepts, are now considered
18180 obsolete.
18182 You may completely skip this chapter if you are new to Autoconf.  Its
18183 intention is mainly to help maintainers updating their packages by
18184 understanding how to move to more modern constructs.
18186 @menu
18187 * Obsolete config.status Use::  Obsolete convention for @command{config.status}
18188 * acconfig Header::             Additional entries in @file{config.h.in}
18189 * autoupdate Invocation::       Automatic update of @file{configure.ac}
18190 * Obsolete Macros::             Backward compatibility macros
18191 * Autoconf 1::                  Tips for upgrading your files
18192 * Autoconf 2.13::               Some fresher tips
18193 @end menu
18195 @node Obsolete config.status Use
18196 @section Obsolete @file{config.status} Invocation
18198 @file{config.status} now supports arguments to specify the files to
18199 instantiate; see @ref{config.status Invocation}, for more details.
18200 Before, environment variables had to be used.
18202 @defvar CONFIG_COMMANDS
18203 @evindex CONFIG_COMMANDS
18204 The tags of the commands to execute.  The default is the arguments given
18205 to @code{AC_OUTPUT} and @code{AC_CONFIG_COMMANDS} in
18206 @file{configure.ac}.
18207 @end defvar
18209 @defvar CONFIG_FILES
18210 @evindex CONFIG_FILES
18211 The files in which to perform @samp{@@@var{variable}@@} substitutions.
18212 The default is the arguments given to @code{AC_OUTPUT} and
18213 @code{AC_CONFIG_FILES} in @file{configure.ac}.
18214 @end defvar
18216 @defvar CONFIG_HEADERS
18217 @evindex CONFIG_HEADERS
18218 The files in which to substitute C @code{#define} statements.  The
18219 default is the arguments given to @code{AC_CONFIG_HEADERS}; if that
18220 macro was not called, @file{config.status} ignores this variable.
18221 @end defvar
18223 @defvar CONFIG_LINKS
18224 @evindex CONFIG_LINKS
18225 The symbolic links to establish.  The default is the arguments given to
18226 @code{AC_CONFIG_LINKS}; if that macro was not called,
18227 @file{config.status} ignores this variable.
18228 @end defvar
18230 In @ref{config.status Invocation}, using this old interface, the example
18231 would be:
18233 @example
18234 @group
18235 config.h: stamp-h
18236 stamp-h: config.h.in config.status
18237         CONFIG_COMMANDS= CONFIG_LINKS= CONFIG_FILES= \
18238           CONFIG_HEADERS=config.h ./config.status
18239         echo > stamp-h
18241 Makefile: Makefile.in config.status
18242         CONFIG_COMMANDS= CONFIG_LINKS= CONFIG_HEADERS= \
18243           CONFIG_FILES=Makefile ./config.status
18244 @end group
18245 @end example
18247 @noindent
18248 (If @file{configure.ac} does not call @code{AC_CONFIG_HEADERS}, there is
18249 no need to set @code{CONFIG_HEADERS} in the @code{make} rules.  Equally
18250 for @code{CONFIG_COMMANDS}, etc.)
18253 @node acconfig Header
18254 @section @file{acconfig.h}
18256 @cindex @file{acconfig.h}
18257 @cindex @file{config.h.top}
18258 @cindex @file{config.h.bot}
18260 In order to produce @file{config.h.in}, @command{autoheader} needs to
18261 build or to find templates for each symbol.  Modern releases of Autoconf
18262 use @code{AH_VERBATIM} and @code{AH_TEMPLATE} (@pxref{Autoheader
18263 Macros}), but in older releases a file, @file{acconfig.h}, contained the
18264 list of needed templates.  @command{autoheader} copied comments and
18265 @code{#define} and @code{#undef} statements from @file{acconfig.h} in
18266 the current directory, if present.  This file used to be mandatory if
18267 you @code{AC_DEFINE} any additional symbols.
18269 Modern releases of Autoconf also provide @code{AH_TOP} and
18270 @code{AH_BOTTOM} if you need to prepend/append some information to
18271 @file{config.h.in}.  Ancient versions of Autoconf had a similar feature:
18272 if @file{./acconfig.h} contains the string @samp{@@TOP@@},
18273 @command{autoheader} copies the lines before the line containing
18274 @samp{@@TOP@@} into the top of the file that it generates.  Similarly,
18275 if @file{./acconfig.h} contains the string @samp{@@BOTTOM@@},
18276 @command{autoheader} copies the lines after that line to the end of the
18277 file it generates.  Either or both of those strings may be omitted.  An
18278 even older alternate way to produce the same effect in ancient versions
18279 of Autoconf is to create the files @file{@var{file}.top} (typically
18280 @file{config.h.top}) and/or @file{@var{file}.bot} in the current
18281 directory.  If they exist, @command{autoheader} copies them to the
18282 beginning and end, respectively, of its output.
18284 In former versions of Autoconf, the files used in preparing a software
18285 package for distribution were:
18286 @example
18287 @group
18288 configure.ac --.   .------> autoconf* -----> configure
18289                +---+
18290 [aclocal.m4] --+   `---.
18291 [acsite.m4] ---'       |
18292                        +--> [autoheader*] -> [config.h.in]
18293 [acconfig.h] ----.     |
18294                  +-----'
18295 [config.h.top] --+
18296 [config.h.bot] --'
18297 @end group
18298 @end example
18300 Using only the @code{AH_} macros, @file{configure.ac} should be
18301 self-contained, and should not depend upon @file{acconfig.h} etc.
18304 @node autoupdate Invocation
18305 @section Using @command{autoupdate} to Modernize @file{configure.ac}
18306 @cindex @command{autoupdate}
18308 The @command{autoupdate} program updates a @file{configure.ac} file that
18309 calls Autoconf macros by their old names to use the current macro names.
18310 In version 2 of Autoconf, most of the macros were renamed to use a more
18311 uniform and descriptive naming scheme.  @xref{Macro Names}, for a
18312 description of the new scheme.  Although the old names still work
18313 (@pxref{Obsolete Macros}, for a list of the old macros and the corresponding
18314 new names), you can make your @file{configure.ac} files more readable
18315 and make it easier to use the current Autoconf documentation if you
18316 update them to use the new macro names.
18318 @evindex SIMPLE_BACKUP_SUFFIX
18319 If given no arguments, @command{autoupdate} updates @file{configure.ac},
18320 backing up the original version with the suffix @file{~} (or the value
18321 of the environment variable @code{SIMPLE_BACKUP_SUFFIX}, if that is
18322 set).  If you give @command{autoupdate} an argument, it reads that file
18323 instead of @file{configure.ac} and writes the updated file to the
18324 standard output.
18326 @noindent
18327 @command{autoupdate} accepts the following options:
18329 @table @option
18330 @item --help
18331 @itemx -h
18332 Print a summary of the command line options and exit.
18334 @item --version
18335 @itemx -V
18336 Print the version number of Autoconf and exit.
18338 @item --verbose
18339 @itemx -v
18340 Report processing steps.
18342 @item --debug
18343 @itemx -d
18344 Don't remove the temporary files.
18346 @item --force
18347 @itemx -f
18348 Force the update even if the file has not changed.  Disregard the cache.
18350 @item --include=@var{dir}
18351 @itemx -I @var{dir}
18352 Also look for input files in @var{dir}.  Multiple invocations accumulate.
18353 Directories are browsed from last to first.
18354 @end table
18356 @node Obsolete Macros
18357 @section Obsolete Macros
18359 Several macros are obsoleted in Autoconf, for various reasons (typically
18360 they failed to quote properly, couldn't be extended for more recent
18361 issues, etc.).  They are still supported, but deprecated: their use
18362 should be avoided.
18364 During the jump from Autoconf version 1 to version 2, most of the
18365 macros were renamed to use a more uniform and descriptive naming scheme,
18366 but their signature did not change.  @xref{Macro Names}, for a
18367 description of the new naming scheme.  Below, if there is just the mapping
18368 from old names to new names for these macros, the reader is invited to
18369 refer to the definition of the new macro for the signature and the
18370 description.
18372 @defmac AC_AIX
18373 @acindex{AIX}
18374 @cvindex _ALL_SOURCE
18375 This macro is a platform-specific subset of
18376 @code{AC_USE_SYSTEM_EXTENSIONS} (@pxref{AC_USE_SYSTEM_EXTENSIONS}).
18377 @end defmac
18379 @defmac AC_ALLOCA
18380 @acindex{ALLOCA}
18381 Replaced by @code{AC_FUNC_ALLOCA} (@pxref{AC_FUNC_ALLOCA}).
18382 @end defmac
18384 @defmac AC_ARG_ARRAY
18385 @acindex{ARG_ARRAY}
18386 Removed because of limited usefulness.
18387 @end defmac
18389 @defmac AC_C_CROSS
18390 @acindex{C_CROSS}
18391 This macro is obsolete; it does nothing.
18392 @end defmac
18394 @defmac AC_C_LONG_DOUBLE
18395 @acindex{C_LONG_DOUBLE}
18396 @cvindex HAVE_LONG_DOUBLE
18397 If the C compiler supports a working @code{long double} type with more
18398 range or precision than the @code{double} type, define
18399 @code{HAVE_LONG_DOUBLE}.
18401 You should use @code{AC_TYPE_LONG_DOUBLE} or
18402 @code{AC_TYPE_LONG_DOUBLE_WIDER} instead.  @xref{Particular Types}.
18403 @end defmac
18405 @defmac AC_CANONICAL_SYSTEM
18406 @acindex{CANONICAL_SYSTEM}
18407 Determine the system type and set output variables to the names of the
18408 canonical system types.  @xref{Canonicalizing}, for details about the
18409 variables this macro sets.
18411 The user is encouraged to use either @code{AC_CANONICAL_BUILD}, or
18412 @code{AC_CANONICAL_HOST}, or @code{AC_CANONICAL_TARGET}, depending on
18413 the needs.  Using @code{AC_CANONICAL_TARGET} is enough to run the two
18414 other macros (@pxref{Canonicalizing}).
18415 @end defmac
18417 @defmac AC_CHAR_UNSIGNED
18418 @acindex{CHAR_UNSIGNED}
18419 Replaced by @code{AC_C_CHAR_UNSIGNED} (@pxref{AC_C_CHAR_UNSIGNED}).
18420 @end defmac
18422 @defmac AC_CHECK_TYPE (@var{type}, @var{default})
18423 @acindex{CHECK_TYPE}
18424 Autoconf, up to 2.13, used to provide this version of
18425 @code{AC_CHECK_TYPE}, deprecated because of its flaws.  First, although
18426 it is a member of the @code{CHECK} clan, it does
18427 more than just checking.  Secondly, missing types are defined
18428 using @code{#define}, not @code{typedef}, and this can lead to
18429 problems in the case of pointer types.
18431 This use of @code{AC_CHECK_TYPE} is obsolete and discouraged; see
18432 @ref{Generic Types}, for the description of the current macro.
18434 If the type @var{type} is not defined, define it to be the C (or C++)
18435 builtin type @var{default}, e.g., @samp{short int} or @samp{unsigned int}.
18437 This macro is equivalent to:
18439 @example
18440 AC_CHECK_TYPE([@var{type}], [],
18441   [AC_DEFINE_UNQUOTED([@var{type}], [@var{default}],
18442      [Define to `@var{default}'
18443       if <sys/types.h> does not define.])])
18444 @end example
18446 In order to keep backward compatibility, the two versions of
18447 @code{AC_CHECK_TYPE} are implemented, selected using these heuristics:
18449 @enumerate
18450 @item
18451 If there are three or four arguments, the modern version is used.
18453 @item
18454 If the second argument appears to be a C or C++ type, then the
18455 obsolete version is used.  This happens if the argument is a C or C++
18456 @emph{builtin} type or a C identifier ending in @samp{_t}, optionally
18457 followed by one of @samp{[(* } and then by a string of zero or more
18458 characters taken from the set @samp{[]()* _a-zA-Z0-9}.
18460 @item
18461 If the second argument is spelled with the alphabet of valid C and C++
18462 types, the user is warned and the modern version is used.
18464 @item
18465 Otherwise, the modern version is used.
18466 @end enumerate
18468 @noindent
18469 You are encouraged either to use a valid builtin type, or to use the
18470 equivalent modern code (see above), or better yet, to use
18471 @code{AC_CHECK_TYPES} together with
18473 @example
18474 #ifndef HAVE_LOFF_T
18475 typedef loff_t off_t;
18476 #endif
18477 @end example
18478 @end defmac
18479 @c end of AC_CHECK_TYPE
18481 @defmac AC_CHECKING (@var{feature-description})
18482 @acindex{CHECKING}
18483 Same as
18485 @example
18486 AC_MSG_NOTICE([checking @var{feature-description}@dots{}]
18487 @end example
18489 @noindent
18490 @xref{AC_MSG_NOTICE}.
18491 @end defmac
18493 @defmac AC_COMPILE_CHECK (@var{echo-text}, @var{includes}, @
18494   @var{function-body}, @var{action-if-true}, @ovar{action-if-false})
18495 @acindex{COMPILE_CHECK}
18496 This is an obsolete version of @code{AC_TRY_COMPILE} itself replaced by
18497 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}), with the
18498 addition that it prints @samp{checking for @var{echo-text}} to the
18499 standard output first, if @var{echo-text} is non-empty.  Use
18500 @code{AC_MSG_CHECKING} and @code{AC_MSG_RESULT} instead to print
18501 messages (@pxref{Printing Messages}).
18502 @end defmac
18504 @defmac AC_CONST
18505 @acindex{CONST}
18506 Replaced by @code{AC_C_CONST} (@pxref{AC_C_CONST}).
18507 @end defmac
18509 @defmac AC_CROSS_CHECK
18510 @acindex{CROSS_CHECK}
18511 Same as @code{AC_C_CROSS}, which is obsolete too, and does nothing
18512 @code{:-)}.
18513 @end defmac
18515 @defmac AC_CYGWIN
18516 @acindex{CYGWIN}
18517 @evindex CYGWIN
18518 Check for the Cygwin environment in which case the shell variable
18519 @code{CYGWIN} is set to @samp{yes}.  Don't use this macro, the dignified
18520 means to check the nature of the host is using @code{AC_CANONICAL_HOST}
18521 (@pxref{Canonicalizing}).  As a matter of fact this macro is defined as:
18523 @example
18524 AC_REQUIRE([AC_CANONICAL_HOST])[]dnl
18525 case $host_os in
18526   *cygwin* ) CYGWIN=yes;;
18527          * ) CYGWIN=no;;
18528 esac
18529 @end example
18531 Beware that the variable @env{CYGWIN} has a special meaning when
18532 running Cygwin, and should not be changed.  That's yet another reason
18533 not to use this macro.
18534 @end defmac
18536 @defmac AC_DECL_SYS_SIGLIST
18537 @acindex{DECL_SYS_SIGLIST}
18538 @cvindex SYS_SIGLIST_DECLARED
18539 Same as:
18541 @example
18542 AC_CHECK_DECLS([sys_siglist], [], [],
18543 [#include <signal.h>
18544 /* NetBSD declares sys_siglist in unistd.h.  */
18545 #ifdef HAVE_UNISTD_H
18546 # include <unistd.h>
18547 #endif
18549 @end example
18551 @noindent
18552 @xref{AC_CHECK_DECLS}.
18553 @end defmac
18555 @defmac AC_DECL_YYTEXT
18556 @acindex{DECL_YYTEXT}
18557 Does nothing, now integrated in @code{AC_PROG_LEX} (@pxref{AC_PROG_LEX}).
18558 @end defmac
18560 @defmac AC_DIR_HEADER
18561 @acindex{DIR_HEADER}
18562 @cvindex DIRENT
18563 @cvindex SYSNDIR
18564 @cvindex SYSDIR
18565 @cvindex NDIR
18566 Like calling @code{AC_FUNC_CLOSEDIR_VOID}
18567 (@pxref{AC_FUNC_CLOSEDIR_VOID}) and @code{AC_HEADER_DIRENT}
18568 (@pxref{AC_HEADER_DIRENT}),
18569 but defines a different set of C preprocessor macros to indicate which
18570 header file is found:
18572 @multitable {@file{sys/ndir.h}} {Old Symbol} {@code{HAVE_SYS_NDIR_H}}
18573 @item Header            @tab Old Symbol     @tab New Symbol
18574 @item @file{dirent.h}   @tab @code{DIRENT}  @tab @code{HAVE_DIRENT_H}
18575 @item @file{sys/ndir.h} @tab @code{SYSNDIR} @tab @code{HAVE_SYS_NDIR_H}
18576 @item @file{sys/dir.h}  @tab @code{SYSDIR}  @tab @code{HAVE_SYS_DIR_H}
18577 @item @file{ndir.h}     @tab @code{NDIR}    @tab @code{HAVE_NDIR_H}
18578 @end multitable
18579 @end defmac
18581 @defmac AC_DYNIX_SEQ
18582 @acindex{DYNIX_SEQ}
18583 If on DYNIX/ptx, add @option{-lseq} to output variable
18584 @code{LIBS}.  This macro used to be defined as
18586 @example
18587 AC_CHECK_LIB([seq], [getmntent], [LIBS="-lseq $LIBS"])
18588 @end example
18590 @noindent
18591 now it is just @code{AC_FUNC_GETMNTENT} (@pxref{AC_FUNC_GETMNTENT}).
18592 @end defmac
18594 @defmac AC_EXEEXT
18595 @acindex{EXEEXT}
18596 @ovindex EXEEXT
18597 Defined the output variable @code{EXEEXT} based on the output of the
18598 compiler, which is now done automatically.  Typically set to empty
18599 string if Posix and @samp{.exe} if a @acronym{DOS} variant.
18600 @end defmac
18602 @defmac AC_EMXOS2
18603 @acindex{EMXOS2}
18604 Similar to @code{AC_CYGWIN} but checks for the EMX environment on OS/2
18605 and sets @code{EMXOS2}.  Don't use this macro, the dignified means to
18606 check the nature of the host is using @code{AC_CANONICAL_HOST}
18607 (@pxref{Canonicalizing}).
18608 @end defmac
18610 @defmac AC_ENABLE (@var{feature}, @var{action-if-given}, @
18611   @ovar{action-if-not-given})
18612 @acindex{ENABLE}
18613 This is an obsolete version of @code{AC_ARG_ENABLE} that does not
18614 support providing a help string (@pxref{AC_ARG_ENABLE}).
18615 @end defmac
18617 @defmac AC_ERROR
18618 @acindex{ERROR}
18619 Replaced by @code{AC_MSG_ERROR} (@pxref{AC_MSG_ERROR}).
18620 @end defmac
18622 @defmac AC_FIND_X
18623 @acindex{FIND_X}
18624 Replaced by @code{AC_PATH_X} (@pxref{AC_PATH_X}).
18625 @end defmac
18627 @defmac AC_FIND_XTRA
18628 @acindex{FIND_XTRA}
18629 Replaced by @code{AC_PATH_XTRA} (@pxref{AC_PATH_XTRA}).
18630 @end defmac
18632 @defmac AC_FOREACH
18633 @acindex{FOREACH}
18634 Replaced by @code{m4_foreach_w} (@pxref{m4_foreach_w}).
18635 @end defmac
18637 @defmac AC_FUNC_CHECK
18638 @acindex{FUNC_CHECK}
18639 Replaced by @code{AC_CHECK_FUNC} (@pxref{AC_CHECK_FUNC}).
18640 @end defmac
18642 @anchor{AC_FUNC_SETVBUF_REVERSED}
18643 @defmac AC_FUNC_SETVBUF_REVERSED
18644 @acindex{FUNC_SETVBUF_REVERSED}
18645 @cvindex SETVBUF_REVERSED
18646 @c @fuindex setvbuf
18647 @prindex @code{setvbuf}
18648 Do nothing.  Formerly, this macro checked whether @code{setvbuf} takes
18649 the buffering type as its second argument and the buffer pointer as the
18650 third, instead of the other way around, and defined
18651 @code{SETVBUF_REVERSED}.  However, the last systems to have the problem
18652 were those based on SVR2, which became obsolete in 1987, and the macro
18653 is no longer needed.
18654 @end defmac
18656 @defmac AC_FUNC_WAIT3
18657 @acindex{FUNC_WAIT3}
18658 @cvindex HAVE_WAIT3
18659 If @code{wait3} is found and fills in the contents of its third argument
18660 (a @samp{struct rusage *}), which @acronym{HP-UX} does not do, define
18661 @code{HAVE_WAIT3}.
18663 These days portable programs should use @code{waitpid}, not
18664 @code{wait3}, as @code{wait3} has been removed from Posix.
18665 @end defmac
18667 @defmac AC_GCC_TRADITIONAL
18668 @acindex{GCC_TRADITIONAL}
18669 Replaced by @code{AC_PROG_GCC_TRADITIONAL} (@pxref{AC_PROG_GCC_TRADITIONAL}).
18670 @end defmac
18672 @defmac AC_GETGROUPS_T
18673 @acindex{GETGROUPS_T}
18674 Replaced by @code{AC_TYPE_GETGROUPS} (@pxref{AC_TYPE_GETGROUPS}).
18675 @end defmac
18677 @defmac AC_GETLOADAVG
18678 @acindex{GETLOADAVG}
18679 Replaced by @code{AC_FUNC_GETLOADAVG} (@pxref{AC_FUNC_GETLOADAVG}).
18680 @end defmac
18682 @defmac AC_GNU_SOURCE
18683 @acindex{GNU_SOURCE}
18684 @cvindex _GNU_SOURCE
18685 This macro is a platform-specific subset of
18686 @code{AC_USE_SYSTEM_EXTENSIONS} (@pxref{AC_USE_SYSTEM_EXTENSIONS}).
18687 @end defmac
18689 @defmac AC_HAVE_FUNCS
18690 @acindex{HAVE_FUNCS}
18691 Replaced by @code{AC_CHECK_FUNCS} (@pxref{AC_CHECK_FUNCS}).
18692 @end defmac
18694 @defmac AC_HAVE_HEADERS
18695 @acindex{HAVE_HEADERS}
18696 Replaced by @code{AC_CHECK_HEADERS} (@pxref{AC_CHECK_HEADERS}).
18697 @end defmac
18699 @defmac AC_HAVE_LIBRARY (@var{library}, @ovar{action-if-found}, @
18700   @ovar{action-if-not-found}, @ovar{other-libraries})
18701 @acindex{HAVE_LIBRARY}
18702 This macro is equivalent to calling @code{AC_CHECK_LIB} with a
18703 @var{function} argument of @code{main}.  In addition, @var{library} can
18704 be written as any of @samp{foo}, @option{-lfoo}, or @samp{libfoo.a}.  In
18705 all of those cases, the compiler is passed @option{-lfoo}.  However,
18706 @var{library} cannot be a shell variable; it must be a literal name.
18707 @xref{AC_CHECK_LIB}.
18708 @end defmac
18710 @defmac AC_HAVE_POUNDBANG
18711 @acindex{HAVE_POUNDBANG}
18712 Replaced by @code{AC_SYS_INTERPRETER} (@pxref{AC_SYS_INTERPRETER}).
18713 @end defmac
18715 @defmac AC_HEADER_CHECK
18716 @acindex{HEADER_CHECK}
18717 Replaced by @code{AC_CHECK_HEADER} (@pxref{AC_CHECK_HEADER}).
18718 @end defmac
18720 @defmac AC_HEADER_EGREP
18721 @acindex{HEADER_EGREP}
18722 Replaced by @code{AC_EGREP_HEADER} (@pxref{AC_EGREP_HEADER}).
18723 @end defmac
18725 @defmac AC_HELP_STRING
18726 @acindex{HELP_STRING}
18727 Replaced by @code{AS_HELP_STRING} (@pxref{AS_HELP_STRING}).
18728 @end defmac
18730 @defmac AC_INIT (@var{unique-file-in-source-dir})
18731 @acindex{INIT}
18732 Formerly @code{AC_INIT} used to have a single argument, and was
18733 equivalent to:
18735 @example
18736 AC_INIT
18737 AC_CONFIG_SRCDIR(@var{unique-file-in-source-dir})
18738 @end example
18739 See @ref{AC_INIT} and @ref{AC_CONFIG_SRCDIR}.
18740 @end defmac
18742 @defmac AC_INLINE
18743 @acindex{INLINE}
18744 Replaced by @code{AC_C_INLINE} (@pxref{AC_C_INLINE}).
18745 @end defmac
18747 @defmac AC_INT_16_BITS
18748 @acindex{INT_16_BITS}
18749 @cvindex INT_16_BITS
18750 If the C type @code{int} is 16 bits wide, define @code{INT_16_BITS}.
18751 Use @samp{AC_CHECK_SIZEOF(int)} instead (@pxref{AC_CHECK_SIZEOF}).
18752 @end defmac
18754 @defmac AC_IRIX_SUN
18755 @acindex{IRIX_SUN}
18756 If on @sc{irix} (Silicon Graphics Unix), add @option{-lsun} to output
18757 @code{LIBS}.  If you were using it to get @code{getmntent}, use
18758 @code{AC_FUNC_GETMNTENT} instead.  If you used it for the NIS versions
18759 of the password and group functions, use @samp{AC_CHECK_LIB(sun,
18760 getpwnam)}.  Up to Autoconf 2.13, it used to be
18762 @example
18763 AC_CHECK_LIB([sun], [getmntent], [LIBS="-lsun $LIBS"])
18764 @end example
18766 @noindent
18767 now it is defined as
18769 @example
18770 AC_FUNC_GETMNTENT
18771 AC_CHECK_LIB([sun], [getpwnam])
18772 @end example
18774 @noindent
18775 See @ref{AC_FUNC_GETMNTENT} and @ref{AC_CHECK_LIB}.
18776 @end defmac
18778 @defmac AC_ISC_POSIX
18779 @acindex{ISC_POSIX}
18780 @ovindex LIBS
18781 This macro adds @option{-lcposix} to output variable @code{LIBS} if
18782 necessary for Posix facilities.  Sun dropped support for the obsolete
18783 @sc{interactive} Systems Corporation Unix on 2006-07-23.  New programs
18784 need not use this macro.  It is implemented as
18785 @code{AC_SEARCH_LIBS([strerror], [cposix])} (@pxref{AC_SEARCH_LIBS}).
18786 @end defmac
18788 @defmac AC_LANG_C
18789 @acindex{LANG_C}
18790 Same as @samp{AC_LANG([C])} (@pxref{AC_LANG}).
18791 @end defmac
18793 @defmac AC_LANG_CPLUSPLUS
18794 @acindex{LANG_CPLUSPLUS}
18795 Same as @samp{AC_LANG([C++])} (@pxref{AC_LANG}).
18796 @end defmac
18798 @defmac AC_LANG_FORTRAN77
18799 @acindex{LANG_FORTRAN77}
18800 Same as @samp{AC_LANG([Fortran 77])} (@pxref{AC_LANG}).
18801 @end defmac
18803 @defmac AC_LANG_RESTORE
18804 @acindex{LANG_RESTORE}
18805 Select the @var{language} that is saved on the top of the stack, as set
18806 by @code{AC_LANG_SAVE}, remove it from the stack, and call
18807 @code{AC_LANG(@var{language})}.  @xref{Language Choice}, for the
18808 preferred way to change languages.
18809 @end defmac
18811 @defmac AC_LANG_SAVE
18812 @acindex{LANG_SAVE}
18813 Remember the current language (as set by @code{AC_LANG}) on a stack.
18814 The current language does not change.  @code{AC_LANG_PUSH} is preferred
18815 (@pxref{AC_LANG_PUSH}).
18816 @end defmac
18818 @defmac AC_LINK_FILES (@var{source}@dots{}, @var{dest}@dots{})
18819 @acindex{LINK_FILES}
18820 This is an obsolete version of @code{AC_CONFIG_LINKS}
18821 (@pxref{AC_CONFIG_LINKS}.  An updated version of:
18823 @example
18824 AC_LINK_FILES(config/$machine.h config/$obj_format.h,
18825               host.h            object.h)
18826 @end example
18828 @noindent
18831 @example
18832 AC_CONFIG_LINKS([host.h:config/$machine.h
18833                 object.h:config/$obj_format.h])
18834 @end example
18835 @end defmac
18837 @defmac AC_LN_S
18838 @acindex{LN_S}
18839 Replaced by @code{AC_PROG_LN_S} (@pxref{AC_PROG_LN_S}).
18840 @end defmac
18842 @defmac AC_LONG_64_BITS
18843 @acindex{LONG_64_BITS}
18844 @cvindex LONG_64_BITS
18845 Define @code{LONG_64_BITS} if the C type @code{long int} is 64 bits wide.
18846 Use the generic macro @samp{AC_CHECK_SIZEOF([long int])} instead
18847 (@pxref{AC_CHECK_SIZEOF}).
18848 @end defmac
18850 @defmac AC_LONG_DOUBLE
18851 @acindex{LONG_DOUBLE}
18852 If the C compiler supports a working @code{long double} type with more
18853 range or precision than the @code{double} type, define
18854 @code{HAVE_LONG_DOUBLE}.
18856 You should use @code{AC_TYPE_LONG_DOUBLE} or
18857 @code{AC_TYPE_LONG_DOUBLE_WIDER} instead.  @xref{Particular Types}.
18858 @end defmac
18860 @defmac AC_LONG_FILE_NAMES
18861 @acindex{LONG_FILE_NAMES}
18862 Replaced by
18863 @example
18864 AC_SYS_LONG_FILE_NAMES
18865 @end example
18866 @noindent
18867 @xref{AC_SYS_LONG_FILE_NAMES}.
18868 @end defmac
18870 @defmac AC_MAJOR_HEADER
18871 @acindex{MAJOR_HEADER}
18872 Replaced by @code{AC_HEADER_MAJOR} (@pxref{AC_HEADER_MAJOR}).
18873 @end defmac
18875 @defmac AC_MEMORY_H
18876 @acindex{MEMORY_H}
18877 @cvindex NEED_MEMORY_H
18878 Used to define @code{NEED_MEMORY_H} if the @code{mem} functions were
18879 defined in @file{memory.h}.  Today it is equivalent to
18880 @samp{AC_CHECK_HEADERS([memory.h])} (@pxref{AC_CHECK_HEADERS}).  Adjust
18881 your code to depend upon
18882 @code{HAVE_MEMORY_H}, not @code{NEED_MEMORY_H}; see @ref{Standard
18883 Symbols}.
18884 @end defmac
18886 @defmac AC_MINGW32
18887 @acindex{MINGW32}
18888 Similar to @code{AC_CYGWIN} but checks for the MinGW compiler
18889 environment and sets @code{MINGW32}.  Don't use this macro, the
18890 dignified means to check the nature of the host is using
18891 @code{AC_CANONICAL_HOST} (@pxref{Canonicalizing}).
18892 @end defmac
18894 @defmac AC_MINIX
18895 @acindex{MINIX}
18896 @cvindex _MINIX
18897 @cvindex _POSIX_SOURCE
18898 @cvindex _POSIX_1_SOURCE
18899 This macro is a platform-specific subset of
18900 @code{AC_USE_SYSTEM_EXTENSIONS} (@pxref{AC_USE_SYSTEM_EXTENSIONS}).
18901 @end defmac
18903 @defmac AC_MINUS_C_MINUS_O
18904 @acindex{MINUS_C_MINUS_O}
18905 Replaced by @code{AC_PROG_CC_C_O} (@pxref{AC_PROG_CC_C_O}).
18906 @end defmac
18908 @defmac AC_MMAP
18909 @acindex{MMAP}
18910 Replaced by @code{AC_FUNC_MMAP} (@pxref{AC_FUNC_MMAP}).
18911 @end defmac
18913 @defmac AC_MODE_T
18914 @acindex{MODE_T}
18915 Replaced by @code{AC_TYPE_MODE_T} (@pxref{AC_TYPE_MODE_T}).
18916 @end defmac
18918 @defmac AC_OBJEXT
18919 @acindex{OBJEXT}
18920 @ovindex OBJEXT
18921 Defined the output variable @code{OBJEXT} based on the output of the
18922 compiler, after .c files have been excluded.  Typically set to @samp{o}
18923 if Posix, @samp{obj} if a @acronym{DOS} variant.
18924 Now the compiler checking macros handle
18925 this automatically.
18926 @end defmac
18928 @defmac AC_OBSOLETE (@var{this-macro-name}, @ovar{suggestion})
18929 @acindex{OBSOLETE}
18930 Make M4 print a message to the standard error output warning that
18931 @var{this-macro-name} is obsolete, and giving the file and line number
18932 where it was called.  @var{this-macro-name} should be the name of the
18933 macro that is calling @code{AC_OBSOLETE}.  If @var{suggestion} is given,
18934 it is printed at the end of the warning message; for example, it can be
18935 a suggestion for what to use instead of @var{this-macro-name}.
18937 For instance
18939 @example
18940 AC_OBSOLETE([$0], [; use AC_CHECK_HEADERS(unistd.h) instead])dnl
18941 @end example
18943 @noindent
18944 You are encouraged to use @code{AU_DEFUN} instead, since it gives better
18945 services to the user (@pxref{AU_DEFUN}).
18946 @end defmac
18948 @defmac AC_OFF_T
18949 @acindex{OFF_T}
18950 Replaced by @code{AC_TYPE_OFF_T} (@pxref{AC_TYPE_OFF_T}).
18951 @end defmac
18953 @defmac AC_OUTPUT (@ovar{file}@dots{}, @ovar{extra-cmds}, @ovar{init-cmds})
18954 @acindex{OUTPUT}
18955 The use of @code{AC_OUTPUT} with arguments is deprecated.  This obsoleted
18956 interface is equivalent to:
18958 @example
18959 @group
18960 AC_CONFIG_FILES(@var{file}@dots{})
18961 AC_CONFIG_COMMANDS([default],
18962                    @var{extra-cmds}, @var{init-cmds})
18963 AC_OUTPUT
18964 @end group
18965 @end example
18967 @noindent
18968 See @ref{AC_CONFIG_FILES}, @ref{AC_CONFIG_COMMANDS}, and @ref{AC_OUTPUT}.
18969 @end defmac
18971 @defmac AC_OUTPUT_COMMANDS (@var{extra-cmds}, @ovar{init-cmds})
18972 @acindex{OUTPUT_COMMANDS}
18973 Specify additional shell commands to run at the end of
18974 @file{config.status}, and shell commands to initialize any variables
18975 from @command{configure}.  This macro may be called multiple times.  It is
18976 obsolete, replaced by @code{AC_CONFIG_COMMANDS} (@pxref{AC_CONFIG_COMMANDS}).
18978 Here is an unrealistic example:
18980 @example
18981 fubar=27
18982 AC_OUTPUT_COMMANDS([echo this is extra $fubar, and so on.],
18983                    [fubar=$fubar])
18984 AC_OUTPUT_COMMANDS([echo this is another, extra, bit],
18985                    [echo init bit])
18986 @end example
18988 Aside from the fact that @code{AC_CONFIG_COMMANDS} requires an
18989 additional key, an important difference is that
18990 @code{AC_OUTPUT_COMMANDS} is quoting its arguments twice, unlike
18991 @code{AC_CONFIG_COMMANDS}.  This means that @code{AC_CONFIG_COMMANDS}
18992 can safely be given macro calls as arguments:
18994 @example
18995 AC_CONFIG_COMMANDS(foo, [my_FOO()])
18996 @end example
18998 @noindent
18999 Conversely, where one level of quoting was enough for literal strings
19000 with @code{AC_OUTPUT_COMMANDS}, you need two with
19001 @code{AC_CONFIG_COMMANDS}.  The following lines are equivalent:
19003 @example
19004 @group
19005 AC_OUTPUT_COMMANDS([echo "Square brackets: []"])
19006 AC_CONFIG_COMMANDS([default], [[echo "Square brackets: []"]])
19007 @end group
19008 @end example
19009 @end defmac
19011 @defmac AC_PID_T
19012 @acindex{PID_T}
19013 Replaced by @code{AC_TYPE_PID_T} (@pxref{AC_TYPE_PID_T}).
19014 @end defmac
19016 @defmac AC_PREFIX
19017 @acindex{PREFIX}
19018 Replaced by @code{AC_PREFIX_PROGRAM} (@pxref{AC_PREFIX_PROGRAM}).
19019 @end defmac
19021 @defmac AC_PROGRAMS_CHECK
19022 @acindex{PROGRAMS_CHECK}
19023 Replaced by @code{AC_CHECK_PROGS} (@pxref{AC_CHECK_PROGS}).
19024 @end defmac
19026 @defmac AC_PROGRAMS_PATH
19027 @acindex{PROGRAMS_PATH}
19028 Replaced by @code{AC_PATH_PROGS} (@pxref{AC_PATH_PROGS}).
19029 @end defmac
19031 @defmac AC_PROGRAM_CHECK
19032 @acindex{PROGRAM_CHECK}
19033 Replaced by @code{AC_CHECK_PROG} (@pxref{AC_CHECK_PROG}).
19034 @end defmac
19036 @defmac AC_PROGRAM_EGREP
19037 @acindex{PROGRAM_EGREP}
19038 Replaced by @code{AC_EGREP_CPP} (@pxref{AC_EGREP_CPP}).
19039 @end defmac
19041 @defmac AC_PROGRAM_PATH
19042 @acindex{PROGRAM_PATH}
19043 Replaced by @code{AC_PATH_PROG} (@pxref{AC_PATH_PROG}).
19044 @end defmac
19046 @defmac AC_REMOTE_TAPE
19047 @acindex{REMOTE_TAPE}
19048 Removed because of limited usefulness.
19049 @end defmac
19051 @defmac AC_RESTARTABLE_SYSCALLS
19052 @acindex{RESTARTABLE_SYSCALLS}
19053 This macro was renamed @code{AC_SYS_RESTARTABLE_SYSCALLS}.  However,
19054 these days portable programs should use @code{sigaction} with
19055 @code{SA_RESTART} if they want restartable system calls.  They should
19056 not rely on @code{HAVE_RESTARTABLE_SYSCALLS}, since nowadays whether a
19057 system call is restartable is a dynamic issue, not a configuration-time
19058 issue.
19059 @end defmac
19061 @defmac AC_RETSIGTYPE
19062 @acindex{RETSIGTYPE}
19063 Replaced by @code{AC_TYPE_SIGNAL} (@pxref{AC_TYPE_SIGNAL}).
19064 @end defmac
19066 @defmac AC_RSH
19067 @acindex{RSH}
19068 Removed because of limited usefulness.
19069 @end defmac
19071 @defmac AC_SCO_INTL
19072 @acindex{SCO_INTL}
19073 @ovindex LIBS
19074 If on SCO Unix, add @option{-lintl} to output variable @code{LIBS}.  This
19075 macro used to do this:
19077 @example
19078 AC_CHECK_LIB([intl], [strftime], [LIBS="-lintl $LIBS"])
19079 @end example
19081 @noindent
19082 Now it just calls @code{AC_FUNC_STRFTIME} instead (@pxref{AC_FUNC_STRFTIME}).
19083 @end defmac
19085 @defmac AC_SETVBUF_REVERSED
19086 @acindex{SETVBUF_REVERSED}
19087 Replaced by
19088 @example
19089 AC_FUNC_SETVBUF_REVERSED
19090 @end example
19091 @noindent
19092 @xref{AC_FUNC_SETVBUF_REVERSED}.
19093 @end defmac
19095 @defmac AC_SET_MAKE
19096 @acindex{SET_MAKE}
19097 Replaced by @code{AC_PROG_MAKE_SET} (@pxref{AC_PROG_MAKE_SET}).
19098 @end defmac
19100 @defmac AC_SIZEOF_TYPE
19101 @acindex{SIZEOF_TYPE}
19102 Replaced by @code{AC_CHECK_SIZEOF} (@pxref{AC_CHECK_SIZEOF}).
19103 @end defmac
19105 @defmac AC_SIZE_T
19106 @acindex{SIZE_T}
19107 Replaced by @code{AC_TYPE_SIZE_T} (@pxref{AC_TYPE_SIZE_T}).
19108 @end defmac
19110 @defmac AC_STAT_MACROS_BROKEN
19111 @acindex{STAT_MACROS_BROKEN}
19112 Replaced by @code{AC_HEADER_STAT} (@pxref{AC_HEADER_STAT}).
19113 @end defmac
19115 @defmac AC_STDC_HEADERS
19116 @acindex{STDC_HEADERS}
19117 Replaced by @code{AC_HEADER_STDC} (@pxref{AC_HEADER_STDC}).
19118 @end defmac
19120 @defmac AC_STRCOLL
19121 @acindex{STRCOLL}
19122 Replaced by @code{AC_FUNC_STRCOLL} (@pxref{AC_FUNC_STRCOLL}).
19123 @end defmac
19125 @defmac AC_STRUCT_ST_BLKSIZE
19126 @acindex{STRUCT_ST_BLKSIZE}
19127 @cvindex HAVE_STRUCT_STAT_ST_BLKSIZE
19128 @cvindex HAVE_ST_BLKSIZE
19129 If @code{struct stat} contains an @code{st_blksize} member, define
19130 @code{HAVE_STRUCT_STAT_ST_BLKSIZE}.  The former name,
19131 @code{HAVE_ST_BLKSIZE} is to be avoided, as its support will cease in
19132 the future.  This macro is obsoleted, and should be replaced by
19134 @example
19135 AC_CHECK_MEMBERS([struct stat.st_blksize])
19136 @end example
19137 @noindent
19138 @xref{AC_CHECK_MEMBERS}.
19139 @end defmac
19141 @defmac AC_STRUCT_ST_RDEV
19142 @acindex{STRUCT_ST_RDEV}
19143 @cvindex HAVE_ST_RDEV
19144 @cvindex HAVE_STRUCT_STAT_ST_RDEV
19145 If @code{struct stat} contains an @code{st_rdev} member, define
19146 @code{HAVE_STRUCT_STAT_ST_RDEV}.  The former name for this macro,
19147 @code{HAVE_ST_RDEV}, is to be avoided as it will cease to be supported
19148 in the future.  Actually, even the new macro is obsolete and should be
19149 replaced by:
19150 @example
19151 AC_CHECK_MEMBERS([struct stat.st_rdev])
19152 @end example
19153 @noindent
19154 @xref{AC_CHECK_MEMBERS}.
19155 @end defmac
19157 @defmac AC_ST_BLKSIZE
19158 @acindex{ST_BLKSIZE}
19159 Replaced by @code{AC_CHECK_MEMBERS} (@pxref{AC_CHECK_MEMBERS}).
19160 @end defmac
19162 @defmac AC_ST_BLOCKS
19163 @acindex{ST_BLOCKS}
19164 Replaced by @code{AC_STRUCT_ST_BLOCKS} (@pxref{AC_STRUCT_ST_BLOCKS}).
19165 @end defmac
19167 @defmac AC_ST_RDEV
19168 @acindex{ST_RDEV}
19169 Replaced by @code{AC_CHECK_MEMBERS} (@pxref{AC_CHECK_MEMBERS}).
19170 @end defmac
19172 @defmac AC_SYS_RESTARTABLE_SYSCALLS
19173 @acindex{SYS_RESTARTABLE_SYSCALLS}
19174 @cvindex HAVE_RESTARTABLE_SYSCALLS
19175 If the system automatically restarts a system call that is interrupted
19176 by a signal, define @code{HAVE_RESTARTABLE_SYSCALLS}.  This macro does
19177 not check whether system calls are restarted in general---it checks whether a
19178 signal handler installed with @code{signal} (but not @code{sigaction})
19179 causes system calls to be restarted.  It does not check whether system calls
19180 can be restarted when interrupted by signals that have no handler.
19182 These days portable programs should use @code{sigaction} with
19183 @code{SA_RESTART} if they want restartable system calls.  They should
19184 not rely on @code{HAVE_RESTARTABLE_SYSCALLS}, since nowadays whether a
19185 system call is restartable is a dynamic issue, not a configuration-time
19186 issue.
19187 @end defmac
19189 @defmac AC_SYS_SIGLIST_DECLARED
19190 @acindex{SYS_SIGLIST_DECLARED}
19191 This macro was renamed @code{AC_DECL_SYS_SIGLIST}.  However, even that
19192 name is obsolete, as the same functionality is now acheived via
19193 @code{AC_CHECK_DECLS} (@pxref{AC_CHECK_DECLS}).
19194 @end defmac
19196 @defmac AC_TEST_CPP
19197 @acindex{TEST_CPP}
19198 This macro was renamed @code{AC_TRY_CPP}, which in turn was replaced by
19199 @code{AC_PREPROC_IFELSE} (@pxref{AC_PREPROC_IFELSE}).
19200 @end defmac
19202 @defmac AC_TEST_PROGRAM
19203 @acindex{TEST_PROGRAM}
19204 This macro was renamed @code{AC_TRY_RUN}, which in turn was replaced by
19205 @code{AC_RUN_IFELSE} (@pxref{AC_RUN_IFELSE}).
19206 @end defmac
19208 @defmac AC_TIMEZONE
19209 @acindex{TIMEZONE}
19210 Replaced by @code{AC_STRUCT_TIMEZONE} (@pxref{AC_STRUCT_TIMEZONE}).
19211 @end defmac
19213 @defmac AC_TIME_WITH_SYS_TIME
19214 @acindex{TIME_WITH_SYS_TIME}
19215 Replaced by @code{AC_HEADER_TIME} (@pxref{AC_HEADER_TIME}).
19216 @end defmac
19218 @defmac AC_TRY_COMPILE (@var{includes}, @var{function-body}, @
19219   @ovar{action-if-true}, @ovar{action-if-false})
19220 @acindex{TRY_COMPILE}
19221 Same as:
19223 @example
19224 AC_COMPILE_IFELSE(
19225   [AC_LANG_PROGRAM([[@var{includes}]],
19226      [[@var{function-body}]])],
19227   [@var{action-if-true}],
19228   [@var{action-if-false}])
19229 @end example
19231 @noindent
19232 @xref{Running the Compiler}.
19234 This macro double quotes both @var{includes} and @var{function-body}.
19236 For C and C++, @var{includes} is any @code{#include} statements needed
19237 by the code in @var{function-body} (@var{includes} is ignored if
19238 the currently selected language is Fortran or Fortran 77).  The compiler
19239 and compilation flags are determined by the current language
19240 (@pxref{Language Choice}).
19241 @end defmac
19243 @defmac AC_TRY_CPP (@var{input}, @ovar{action-if-true}, @ovar{action-if-false})
19244 @acindex{TRY_CPP}
19245 Same as:
19247 @example
19248 AC_PREPROC_IFELSE(
19249   [AC_LANG_SOURCE([[@var{input}]])],
19250   [@var{action-if-true}],
19251   [@var{action-if-false}])
19252 @end example
19254 @noindent
19255 @xref{Running the Preprocessor}.
19257 This macro double quotes the @var{input}.
19258 @end defmac
19260 @defmac AC_TRY_LINK (@var{includes}, @var{function-body}, @
19261   @ovar{action-if-true}, @ovar{action-if-false})
19262 @acindex{TRY_LINK}
19263 Same as:
19265 @example
19266 AC_LINK_IFELSE(
19267   [AC_LANG_PROGRAM([[@var{includes}]],
19268      [[@var{function-body}]])],
19269   [@var{action-if-true}],
19270   [@var{action-if-false}])
19271 @end example
19273 @noindent
19274 @xref{Running the Compiler}.
19276 This macro double quotes both @var{includes} and @var{function-body}.
19278 Depending on the current language (@pxref{Language Choice}), create a
19279 test program to see whether a function whose body consists of
19280 @var{function-body} can be compiled and linked.  If the file compiles
19281 and links successfully, run shell commands @var{action-if-found},
19282 otherwise run @var{action-if-not-found}.
19284 This macro double quotes both @var{includes} and @var{function-body}.
19286 For C and C++, @var{includes} is any @code{#include} statements needed
19287 by the code in @var{function-body} (@var{includes} is ignored if
19288 the currently selected language is Fortran or Fortran 77).  The compiler
19289 and compilation flags are determined by the current language
19290 (@pxref{Language Choice}), and in addition @code{LDFLAGS} and
19291 @code{LIBS} are used for linking.
19292 @end defmac
19294 @defmac AC_TRY_LINK_FUNC (@var{function}, @ovar{action-if-found}, @
19295   @ovar{action-if-not-found})
19296 @acindex{TRY_LINK_FUNC}
19297 This macro is equivalent to
19298 @example
19299 AC_LINK_IFELSE([AC_LANG_CALL([], [@var{function}])],
19300   [@var{action-if-found}], [@var{action-if-not-found}])
19301 @end example
19302 @noindent
19303 @xref{AC_LINK_IFELSE}.
19304 @end defmac
19306 @defmac AC_TRY_RUN (@var{program}, @ovar{action-if-true}, @
19307   @ovar{action-if-false}, @ovar{action-if-cross-compiling})
19308 @acindex{TRY_RUN}
19309 Same as:
19311 @example
19312 AC_RUN_IFELSE(
19313   [AC_LANG_SOURCE([[@var{program}]])],
19314   [@var{action-if-true}],
19315   [@var{action-if-false}],
19316   [@var{action-if-cross-compiling}])
19317 @end example
19319 @noindent
19320 @xref{Runtime}.
19321 @end defmac
19323 @defmac AC_UID_T
19324 @acindex{UID_T}
19325 Replaced by @code{AC_TYPE_UID_T} (@pxref{AC_TYPE_UID_T}).
19326 @end defmac
19328 @defmac AC_UNISTD_H
19329 @acindex{UNISTD_H}
19330 Same as @samp{AC_CHECK_HEADERS([unistd.h])} (@pxref{AC_CHECK_HEADERS}).
19331 @end defmac
19333 @defmac AC_USG
19334 @acindex{USG}
19335 @cvindex USG
19336 Define @code{USG} if the @acronym{BSD} string functions are defined in
19337 @file{strings.h}.  You should no longer depend upon @code{USG}, but on
19338 @code{HAVE_STRING_H}; see @ref{Standard Symbols}.
19339 @end defmac
19341 @defmac AC_UTIME_NULL
19342 @acindex{UTIME_NULL}
19343 Replaced by @code{AC_FUNC_UTIME_NULL} (@pxref{AC_FUNC_UTIME_NULL}).
19344 @end defmac
19346 @defmac AC_VALIDATE_CACHED_SYSTEM_TUPLE (@ovar{cmd})
19347 @acindex{VALIDATE_CACHED_SYSTEM_TUPLE}
19348 If the cache file is inconsistent with the current host, target and
19349 build system types, it used to execute @var{cmd} or print a default
19350 error message.  This is now handled by default.
19351 @end defmac
19353 @defmac AC_VERBOSE (@var{result-description})
19354 @acindex{VERBOSE}
19355 Replaced by @code{AC_MSG_RESULT} (@pxref{AC_MSG_RESULT}).
19356 @end defmac
19358 @defmac AC_VFORK
19359 @acindex{VFORK}
19360 Replaced by @code{AC_FUNC_FORK} (@pxref{AC_FUNC_FORK}).
19361 @end defmac
19363 @defmac AC_VPRINTF
19364 @acindex{VPRINTF}
19365 Replaced by @code{AC_FUNC_VPRINTF} (@pxref{AC_FUNC_VPRINTF}).
19366 @end defmac
19368 @defmac AC_WAIT3
19369 @acindex{WAIT3}
19370 This macro was renamed @code{AC_FUNC_WAIT3}.  However, these days
19371 portable programs should use @code{waitpid}, not @code{wait3}, as
19372 @code{wait3} has been removed from Posix.
19373 @end defmac
19375 @defmac AC_WARN
19376 @acindex{WARN}
19377 Replaced by @code{AC_MSG_WARN} (@pxref{AC_MSG_WARN}).
19378 @end defmac
19380 @defmac AC_WITH (@var{package}, @var{action-if-given}, @
19381   @ovar{action-if-not-given})
19382 @acindex{WITH}
19383 This is an obsolete version of @code{AC_ARG_WITH} that does not
19384 support providing a help string (@pxref{AC_ARG_WITH}).
19385 @end defmac
19387 @defmac AC_WORDS_BIGENDIAN
19388 @acindex{WORDS_BIGENDIAN}
19389 Replaced by @code{AC_C_BIGENDIAN} (@pxref{AC_C_BIGENDIAN}).
19390 @end defmac
19392 @defmac AC_XENIX_DIR
19393 @acindex{XENIX_DIR}
19394 @ovindex LIBS
19395 This macro used to add @option{-lx} to output variable @code{LIBS} if on
19396 Xenix.  Also, if @file{dirent.h} is being checked for, added
19397 @option{-ldir} to @code{LIBS}.  Now it is merely an alias of
19398 @code{AC_HEADER_DIRENT} instead, plus some code to detect whether
19399 running @sc{xenix} on which you should not depend:
19401 @example
19402 AC_MSG_CHECKING([for Xenix])
19403 AC_EGREP_CPP([yes],
19404 [#if defined M_XENIX && !defined M_UNIX
19405   yes
19406 #endif],
19407              [AC_MSG_RESULT([yes]); XENIX=yes],
19408              [AC_MSG_RESULT([no]); XENIX=])
19409 @end example
19410 @noindent
19411 Don't use this macro, the dignified means to check the nature of the
19412 host is using @code{AC_CANONICAL_HOST} (@pxref{Canonicalizing}).
19413 @end defmac
19415 @defmac AC_YYTEXT_POINTER
19416 @acindex{YYTEXT_POINTER}
19417 This macro was renamed @code{AC_DECL_YYTEXT}, which in turn was
19418 integrated into @code{AC_PROG_LEX} (@pxref{AC_PROG_LEX}).
19419 @end defmac
19421 @node Autoconf 1
19422 @section Upgrading From Version 1
19423 @cindex Upgrading autoconf
19424 @cindex Autoconf upgrading
19426 Autoconf version 2 is mostly backward compatible with version 1.
19427 However, it introduces better ways to do some things, and doesn't
19428 support some of the ugly things in version 1.  So, depending on how
19429 sophisticated your @file{configure.ac} files are, you might have to do
19430 some manual work in order to upgrade to version 2.  This chapter points
19431 out some problems to watch for when upgrading.  Also, perhaps your
19432 @command{configure} scripts could benefit from some of the new features in
19433 version 2; the changes are summarized in the file @file{NEWS} in the
19434 Autoconf distribution.
19436 @menu
19437 * Changed File Names::          Files you might rename
19438 * Changed Makefiles::           New things to put in @file{Makefile.in}
19439 * Changed Macros::              Macro calls you might replace
19440 * Changed Results::             Changes in how to check test results
19441 * Changed Macro Writing::       Better ways to write your own macros
19442 @end menu
19444 @node Changed File Names
19445 @subsection Changed File Names
19447 If you have an @file{aclocal.m4} installed with Autoconf (as opposed to
19448 in a particular package's source directory), you must rename it to
19449 @file{acsite.m4}.  @xref{autoconf Invocation}.
19451 If you distribute @file{install.sh} with your package, rename it to
19452 @file{install-sh} so @code{make} builtin rules don't inadvertently
19453 create a file called @file{install} from it.  @code{AC_PROG_INSTALL}
19454 looks for the script under both names, but it is best to use the new name.
19456 If you were using @file{config.h.top}, @file{config.h.bot}, or
19457 @file{acconfig.h}, you still can, but you have less clutter if you
19458 use the @code{AH_} macros.  @xref{Autoheader Macros}.
19460 @node Changed Makefiles
19461 @subsection Changed Makefiles
19463 Add @samp{@@CFLAGS@@}, @samp{@@CPPFLAGS@@}, and @samp{@@LDFLAGS@@} in
19464 your @file{Makefile.in} files, so they can take advantage of the values
19465 of those variables in the environment when @command{configure} is run.
19466 Doing this isn't necessary, but it's a convenience for users.
19468 Also add @samp{@@configure_input@@} in a comment to each input file for
19469 @code{AC_OUTPUT}, so that the output files contain a comment saying
19470 they were produced by @command{configure}.  Automatically selecting the
19471 right comment syntax for all the kinds of files that people call
19472 @code{AC_OUTPUT} on became too much work.
19474 Add @file{config.log} and @file{config.cache} to the list of files you
19475 remove in @code{distclean} targets.
19477 If you have the following in @file{Makefile.in}:
19479 @example
19480 prefix = /usr/local
19481 exec_prefix = $(prefix)
19482 @end example
19484 @noindent
19485 you must change it to:
19487 @example
19488 prefix = @@prefix@@
19489 exec_prefix = @@exec_prefix@@
19490 @end example
19492 @noindent
19493 The old behavior of replacing those variables without @samp{@@}
19494 characters around them has been removed.
19496 @node Changed Macros
19497 @subsection Changed Macros
19499 Many of the macros were renamed in Autoconf version 2.  You can still
19500 use the old names, but the new ones are clearer, and it's easier to find
19501 the documentation for them.  @xref{Obsolete Macros}, for a table showing the
19502 new names for the old macros.  Use the @command{autoupdate} program to
19503 convert your @file{configure.ac} to using the new macro names.
19504 @xref{autoupdate Invocation}.
19506 Some macros have been superseded by similar ones that do the job better,
19507 but are not call-compatible.  If you get warnings about calling obsolete
19508 macros while running @command{autoconf}, you may safely ignore them, but
19509 your @command{configure} script generally works better if you follow
19510 the advice that is printed about what to replace the obsolete macros with.  In
19511 particular, the mechanism for reporting the results of tests has
19512 changed.  If you were using @command{echo} or @code{AC_VERBOSE} (perhaps
19513 via @code{AC_COMPILE_CHECK}), your @command{configure} script's output
19514 looks better if you switch to @code{AC_MSG_CHECKING} and
19515 @code{AC_MSG_RESULT}.  @xref{Printing Messages}.  Those macros work best
19516 in conjunction with cache variables.  @xref{Caching Results}.
19520 @node Changed Results
19521 @subsection Changed Results
19523 If you were checking the results of previous tests by examining the
19524 shell variable @code{DEFS}, you need to switch to checking the values of
19525 the cache variables for those tests.  @code{DEFS} no longer exists while
19526 @command{configure} is running; it is only created when generating output
19527 files.  This difference from version 1 is because properly quoting the
19528 contents of that variable turned out to be too cumbersome and
19529 inefficient to do every time @code{AC_DEFINE} is called.  @xref{Cache
19530 Variable Names}.
19532 For example, here is a @file{configure.ac} fragment written for Autoconf
19533 version 1:
19535 @example
19536 AC_HAVE_FUNCS(syslog)
19537 case "$DEFS" in
19538 *-DHAVE_SYSLOG*) ;;
19539 *) # syslog is not in the default libraries.  See if it's in some other.
19540   saved_LIBS="$LIBS"
19541   for lib in bsd socket inet; do
19542     AC_CHECKING(for syslog in -l$lib)
19543     LIBS="-l$lib $saved_LIBS"
19544     AC_HAVE_FUNCS(syslog)
19545     case "$DEFS" in
19546     *-DHAVE_SYSLOG*) break ;;
19547     *) ;;
19548     esac
19549     LIBS="$saved_LIBS"
19550   done ;;
19551 esac
19552 @end example
19554 Here is a way to write it for version 2:
19556 @example
19557 AC_CHECK_FUNCS([syslog])
19558 if test $ac_cv_func_syslog = no; then
19559   # syslog is not in the default libraries.  See if it's in some other.
19560   for lib in bsd socket inet; do
19561     AC_CHECK_LIB([$lib], [syslog], [AC_DEFINE([HAVE_SYSLOG])
19562       LIBS="-l$lib $LIBS"; break])
19563   done
19565 @end example
19567 If you were working around bugs in @code{AC_DEFINE_UNQUOTED} by adding
19568 backslashes before quotes, you need to remove them.  It now works
19569 predictably, and does not treat quotes (except back quotes) specially.
19570 @xref{Setting Output Variables}.
19572 All of the Boolean shell variables set by Autoconf macros now use
19573 @samp{yes} for the true value.  Most of them use @samp{no} for false,
19574 though for backward compatibility some use the empty string instead.  If
19575 you were relying on a shell variable being set to something like 1 or
19576 @samp{t} for true, you need to change your tests.
19578 @node Changed Macro Writing
19579 @subsection Changed Macro Writing
19581 When defining your own macros, you should now use @code{AC_DEFUN}
19582 instead of @code{define}.  @code{AC_DEFUN} automatically calls
19583 @code{AC_PROVIDE} and ensures that macros called via @code{AC_REQUIRE}
19584 do not interrupt other macros, to prevent nested @samp{checking@dots{}}
19585 messages on the screen.  There's no actual harm in continuing to use the
19586 older way, but it's less convenient and attractive.  @xref{Macro
19587 Definitions}.
19589 You probably looked at the macros that came with Autoconf as a guide for
19590 how to do things.  It would be a good idea to take a look at the new
19591 versions of them, as the style is somewhat improved and they take
19592 advantage of some new features.
19594 If you were doing tricky things with undocumented Autoconf internals
19595 (macros, variables, diversions), check whether you need to change
19596 anything to account for changes that have been made.  Perhaps you can
19597 even use an officially supported technique in version 2 instead of
19598 kludging.  Or perhaps not.
19600 To speed up your locally written feature tests, add caching to them.
19601 See whether any of your tests are of general enough usefulness to
19602 encapsulate them into macros that you can share.
19605 @node Autoconf 2.13
19606 @section Upgrading From Version 2.13
19607 @cindex Upgrading autoconf
19608 @cindex Autoconf upgrading
19610 The introduction of the previous section (@pxref{Autoconf 1}) perfectly
19611 suits this section@enddots{}
19613 @quotation
19614 Autoconf version 2.50 is mostly backward compatible with version 2.13.
19615 However, it introduces better ways to do some things, and doesn't
19616 support some of the ugly things in version 2.13.  So, depending on how
19617 sophisticated your @file{configure.ac} files are, you might have to do
19618 some manual work in order to upgrade to version 2.50.  This chapter
19619 points out some problems to watch for when upgrading.  Also, perhaps
19620 your @command{configure} scripts could benefit from some of the new
19621 features in version 2.50; the changes are summarized in the file
19622 @file{NEWS} in the Autoconf distribution.
19623 @end quotation
19625 @menu
19626 * Changed Quotation::           Broken code which used to work
19627 * New Macros::                  Interaction with foreign macros
19628 * Hosts and Cross-Compilation::  Bugward compatibility kludges
19629 * AC_LIBOBJ vs LIBOBJS::        LIBOBJS is a forbidden token
19630 * AC_FOO_IFELSE vs AC_TRY_FOO::  A more generic scheme for testing sources
19631 @end menu
19633 @node Changed Quotation
19634 @subsection Changed Quotation
19636 The most important changes are invisible to you: the implementation of
19637 most macros have completely changed.  This allowed more factorization of
19638 the code, better error messages, a higher uniformity of the user's
19639 interface etc.  Unfortunately, as a side effect, some construct which
19640 used to (miraculously) work might break starting with Autoconf 2.50.
19641 The most common culprit is bad quotation.
19643 For instance, in the following example, the message is not properly
19644 quoted:
19646 @example
19647 AC_INIT
19648 AC_CHECK_HEADERS(foo.h, ,
19649   AC_MSG_ERROR(cannot find foo.h, bailing out))
19650 AC_OUTPUT
19651 @end example
19653 @noindent
19654 Autoconf 2.13 simply ignores it:
19656 @example
19657 $ @kbd{autoconf-2.13; ./configure --silent}
19658 creating cache ./config.cache
19659 configure: error: cannot find foo.h
19661 @end example
19663 @noindent
19664 while Autoconf 2.50 produces a broken @file{configure}:
19666 @example
19667 $ @kbd{autoconf-2.50; ./configure --silent}
19668 configure: error: cannot find foo.h
19669 ./configure: exit: bad non-numeric arg `bailing'
19670 ./configure: exit: bad non-numeric arg `bailing'
19672 @end example
19674 The message needs to be quoted, and the @code{AC_MSG_ERROR} invocation
19675 too!
19677 @example
19678 AC_INIT([Example], [1.0], [bug-example@@example.org])
19679 AC_CHECK_HEADERS([foo.h], [],
19680   [AC_MSG_ERROR([cannot find foo.h, bailing out])])
19681 AC_OUTPUT
19682 @end example
19684 Many many (and many more) Autoconf macros were lacking proper quotation,
19685 including no less than@dots{} @code{AC_DEFUN} itself!
19687 @example
19688 $ @kbd{cat configure.in}
19689 AC_DEFUN([AC_PROG_INSTALL],
19690 [# My own much better version
19692 AC_INIT
19693 AC_PROG_INSTALL
19694 AC_OUTPUT
19695 $ @kbd{autoconf-2.13}
19696 autoconf: Undefined macros:
19697 ***BUG in Autoconf--please report*** AC_FD_MSG
19698 ***BUG in Autoconf--please report*** AC_EPI
19699 configure.in:1:AC_DEFUN([AC_PROG_INSTALL],
19700 configure.in:5:AC_PROG_INSTALL
19701 $ @kbd{autoconf-2.50}
19703 @end example
19706 @node New Macros
19707 @subsection New Macros
19709 @cindex undefined macro
19710 @cindex @code{_m4_divert_diversion}
19712 While Autoconf was relatively dormant in the late 1990s, Automake
19713 provided Autoconf-like macros for a while.  Starting with Autoconf 2.50
19714 in 2001, Autoconf provided
19715 versions of these macros, integrated in the @code{AC_} namespace,
19716 instead of @code{AM_}.  But in order to ease the upgrading via
19717 @command{autoupdate}, bindings to such @code{AM_} macros are provided.
19719 Unfortunately older versions of Automake (e.g., Automake 1.4)
19720 did not quote the names of these macros.
19721 Therefore, when @command{m4} finds something like
19722 @samp{AC_DEFUN(AM_TYPE_PTRDIFF_T, @dots{})} in @file{aclocal.m4},
19723 @code{AM_TYPE_PTRDIFF_T} is
19724 expanded, replaced with its Autoconf definition.
19726 Fortunately Autoconf catches pre-@code{AC_INIT} expansions, and
19727 complains, in its own words:
19729 @example
19730 $ @kbd{cat configure.ac}
19731 AC_INIT([Example], [1.0], [bug-example@@example.org])
19732 AM_TYPE_PTRDIFF_T
19733 $ @kbd{aclocal-1.4}
19734 $ @kbd{autoconf}
19735 aclocal.m4:17: error: m4_defn: undefined macro: _m4_divert_diversion
19736 aclocal.m4:17: the top level
19737 autom4te: m4 failed with exit status: 1
19739 @end example
19741 Modern versions of Automake no longer define most of these
19742 macros, and properly quote the names of the remaining macros.
19743 If you must use an old Automake, do not depend upon macros from Automake
19744 as it is simply not its job
19745 to provide macros (but the one it requires itself):
19747 @example
19748 $ @kbd{cat configure.ac}
19749 AC_INIT([Example], [1.0], [bug-example@@example.org])
19750 AM_TYPE_PTRDIFF_T
19751 $ @kbd{rm aclocal.m4}
19752 $ @kbd{autoupdate}
19753 autoupdate: `configure.ac' is updated
19754 $ @kbd{cat configure.ac}
19755 AC_INIT([Example], [1.0], [bug-example@@example.org])
19756 AC_CHECK_TYPES([ptrdiff_t])
19757 $ @kbd{aclocal-1.4}
19758 $ @kbd{autoconf}
19760 @end example
19763 @node Hosts and Cross-Compilation
19764 @subsection Hosts and Cross-Compilation
19765 @cindex Cross compilation
19767 Based on the experience of compiler writers, and after long public
19768 debates, many aspects of the cross-compilation chain have changed:
19770 @itemize @minus
19771 @item
19772 the relationship between the build, host, and target architecture types,
19774 @item
19775 the command line interface for specifying them to @command{configure},
19777 @item
19778 the variables defined in @command{configure},
19780 @item
19781 the enabling of cross-compilation mode.
19782 @end itemize
19784 @sp 1
19786 The relationship between build, host, and target have been cleaned up:
19787 the chain of default is now simply: target defaults to host, host to
19788 build, and build to the result of @command{config.guess}.  Nevertheless,
19789 in order to ease the transition from 2.13 to 2.50, the following
19790 transition scheme is implemented.  @emph{Do not rely on it}, as it will
19791 be completely disabled in a couple of releases (we cannot keep it, as it
19792 proves to cause more problems than it cures).
19794 They all default to the result of running @command{config.guess}, unless
19795 you specify either @option{--build} or @option{--host}.  In this case,
19796 the default becomes the system type you specified.  If you specify both,
19797 and they're different, @command{configure} enters cross compilation
19798 mode, so it doesn't run any tests that require execution.
19800 Hint: if you mean to override the result of @command{config.guess},
19801 prefer @option{--build} over @option{--host}.  In the future,
19802 @option{--host} will not override the name of the build system type.
19803 Whenever you specify @option{--host}, be sure to specify @option{--build}
19804 too.
19806 @sp 1
19808 For backward compatibility, @command{configure} accepts a system
19809 type as an option by itself.  Such an option overrides the
19810 defaults for build, host, and target system types.  The following
19811 configure statement configures a cross toolchain that runs on
19812 Net@acronym{BSD}/alpha but generates code for @acronym{GNU} Hurd/sparc,
19813 which is also the build platform.
19815 @example
19816 ./configure --host=alpha-netbsd sparc-gnu
19817 @end example
19819 @sp 1
19821 In Autoconf 2.13 and before, the variables @code{build}, @code{host},
19822 and @code{target} had a different semantics before and after the
19823 invocation of @code{AC_CANONICAL_BUILD} etc.  Now, the argument of
19824 @option{--build} is strictly copied into @code{build_alias}, and is left
19825 empty otherwise.  After the @code{AC_CANONICAL_BUILD}, @code{build} is
19826 set to the canonicalized build type.  To ease the transition, before,
19827 its contents is the same as that of @code{build_alias}.  Do @emph{not}
19828 rely on this broken feature.
19830 For consistency with the backward compatibility scheme exposed above,
19831 when @option{--host} is specified but @option{--build} isn't, the build
19832 system is assumed to be the same as @option{--host}, and
19833 @samp{build_alias} is set to that value.  Eventually, this
19834 historically incorrect behavior will go away.
19836 @sp 1
19838 The former scheme to enable cross-compilation proved to cause more harm
19839 than good, in particular, it used to be triggered too easily, leaving
19840 regular end users puzzled in front of cryptic error messages.
19841 @command{configure} could even enter cross-compilation mode only
19842 because the compiler was not functional.  This is mainly because
19843 @command{configure} used to try to detect cross-compilation, instead of
19844 waiting for an explicit flag from the user.
19846 Now, @command{configure} enters cross-compilation mode if and only if
19847 @option{--host} is passed.
19849 That's the short documentation.  To ease the transition between 2.13 and
19850 its successors, a more complicated scheme is implemented.  @emph{Do not
19851 rely on the following}, as it will be removed in the near future.
19853 If you specify @option{--host}, but not @option{--build}, when
19854 @command{configure} performs the first compiler test it tries to run
19855 an executable produced by the compiler.  If the execution fails, it
19856 enters cross-compilation mode.  This is fragile.  Moreover, by the time
19857 the compiler test is performed, it may be too late to modify the
19858 build-system type: other tests may have already been performed.
19859 Therefore, whenever you specify @option{--host}, be sure to specify
19860 @option{--build} too.
19862 @example
19863 ./configure --build=i686-pc-linux-gnu --host=m68k-coff
19864 @end example
19866 @noindent
19867 enters cross-compilation mode.  The former interface, which
19868 consisted in setting the compiler to a cross-compiler without informing
19869 @command{configure} is obsolete.  For instance, @command{configure}
19870 fails if it can't run the code generated by the specified compiler if you
19871 configure as follows:
19873 @example
19874 ./configure CC=m68k-coff-gcc
19875 @end example
19878 @node AC_LIBOBJ vs LIBOBJS
19879 @subsection @code{AC_LIBOBJ} vs.@: @code{LIBOBJS}
19881 Up to Autoconf 2.13, the replacement of functions was triggered via the
19882 variable @code{LIBOBJS}.  Since Autoconf 2.50, the macro
19883 @code{AC_LIBOBJ} should be used instead (@pxref{Generic Functions}).
19884 Starting at Autoconf 2.53, the use of @code{LIBOBJS} is an error.
19886 This change is mandated by the unification of the @acronym{GNU} Build System
19887 components.  In particular, the various fragile techniques used to parse
19888 a @file{configure.ac} are all replaced with the use of traces.  As a
19889 consequence, any action must be traceable, which obsoletes critical
19890 variable assignments.  Fortunately, @code{LIBOBJS} was the only problem,
19891 and it can even be handled gracefully (read, ``without your having to
19892 change something'').
19894 There were two typical uses of @code{LIBOBJS}: asking for a replacement
19895 function, and adjusting @code{LIBOBJS} for Automake and/or Libtool.
19897 @sp 1
19899 As for function replacement, the fix is immediate: use
19900 @code{AC_LIBOBJ}.  For instance:
19902 @example
19903 LIBOBJS="$LIBOBJS fnmatch.o"
19904 LIBOBJS="$LIBOBJS malloc.$ac_objext"
19905 @end example
19907 @noindent
19908 should be replaced with:
19910 @example
19911 AC_LIBOBJ([fnmatch])
19912 AC_LIBOBJ([malloc])
19913 @end example
19915 @sp 1
19917 @ovindex LIBOBJDIR
19918 When used with Automake 1.10 or newer, a suitable value for
19919 @code{LIBOBJDIR} is set so that the @code{LIBOBJS} and @code{LTLIBOBJS}
19920 can be referenced from any @file{Makefile.am}.  Even without Automake,
19921 arranging for @code{LIBOBJDIR} to be set correctly enables
19922 referencing @code{LIBOBJS} and @code{LTLIBOBJS} in another directory.
19923 The @code{LIBOBJDIR} feature is experimental.
19926 @node AC_FOO_IFELSE vs AC_TRY_FOO
19927 @subsection @code{AC_FOO_IFELSE} vs.@: @code{AC_TRY_FOO}
19929 Since Autoconf 2.50, internal codes uses @code{AC_PREPROC_IFELSE},
19930 @code{AC_COMPILE_IFELSE}, @code{AC_LINK_IFELSE}, and
19931 @code{AC_RUN_IFELSE} on one hand and @code{AC_LANG_SOURCES},
19932 and @code{AC_LANG_PROGRAM} on the other hand instead of the deprecated
19933 @code{AC_TRY_CPP}, @code{AC_TRY_COMPILE}, @code{AC_TRY_LINK}, and
19934 @code{AC_TRY_RUN}.  The motivations where:
19935 @itemize @minus
19936 @item
19937 a more consistent interface: @code{AC_TRY_COMPILE} etc.@: were double
19938 quoting their arguments;
19940 @item
19941 the combinatoric explosion is solved by decomposing on the one hand the
19942 generation of sources, and on the other hand executing the program;
19944 @item
19945 this scheme helps supporting more languages than plain C and C++.
19946 @end itemize
19948 In addition to the change of syntax, the philosophy has changed too:
19949 while emphasis was put on speed at the expense of accuracy, today's
19950 Autoconf promotes accuracy of the testing framework at, ahem@dots{}, the
19951 expense of speed.
19954 As a perfect example of what is @emph{not} to be done, here is how to
19955 find out whether a header file contains a particular declaration, such
19956 as a typedef, a structure, a structure member, or a function.  Use
19957 @code{AC_EGREP_HEADER} instead of running @code{grep} directly on the
19958 header file; on some systems the symbol might be defined in another
19959 header file that the file you are checking includes.
19961 As a (bad) example, here is how you should not check for C preprocessor
19962 symbols, either defined by header files or predefined by the C
19963 preprocessor: using @code{AC_EGREP_CPP}:
19965 @example
19966 @group
19967 AC_EGREP_CPP(yes,
19968 [#ifdef _AIX
19969   yes
19970 #endif
19971 ], is_aix=yes, is_aix=no)
19972 @end group
19973 @end example
19975 The above example, properly written would (i) use
19976 @code{AC_LANG_PROGRAM}, and (ii) run the compiler:
19978 @example
19979 @group
19980 AC_COMPILE_IFELSE([AC_LANG_PROGRAM(
19981 [[#ifndef _AIX
19982  error: This isn't AIX!
19983 #endif
19984 ]])],
19985                    [is_aix=yes],
19986                    [is_aix=no])
19987 @end group
19988 @end example
19991 @c ============================= Generating Test Suites with Autotest
19993 @node Using Autotest
19994 @chapter Generating Test Suites with Autotest
19996 @cindex Autotest
19998 @display
19999 @strong{N.B.: This section describes an experimental feature which will
20000 be part of Autoconf in a forthcoming release.  Although we believe
20001 Autotest is stabilizing, this documentation describes an interface which
20002 might change in the future: do not depend upon Autotest without
20003 subscribing to the Autoconf mailing lists.}
20004 @end display
20006 It is paradoxical that portable projects depend on nonportable tools
20007 to run their test suite.  Autoconf by itself is the paragon of this
20008 problem: although it aims at perfectly portability, up to 2.13 its
20009 test suite was using Deja@acronym{GNU}, a rich and complex testing
20010 framework, but which is far from being standard on Posix systems.
20011 Worse yet, it was likely to be missing on the most fragile platforms,
20012 the very platforms that are most likely to torture Autoconf and
20013 exhibit deficiencies.
20015 To circumvent this problem, many package maintainers have developed their
20016 own testing framework, based on simple shell scripts whose sole outputs
20017 are exit status values describing whether the test succeeded.  Most of
20018 these tests share common patterns, and this can result in lots of
20019 duplicated code and tedious maintenance.
20021 Following exactly the same reasoning that yielded to the inception of
20022 Autoconf, Autotest provides a test suite generation framework, based on
20023 M4 macros building a portable shell script.  The suite itself is
20024 equipped with automatic logging and tracing facilities which greatly
20025 diminish the interaction with bug reporters, and simple timing reports.
20027 Autoconf itself has been using Autotest for years, and we do attest that
20028 it has considerably improved the strength of the test suite and the
20029 quality of bug reports.  Other projects are known to use some generation
20030 of Autotest, such as Bison, Free Recode, Free Wdiff, @acronym{GNU} Tar, each of
20031 them with different needs, and this usage has validated Autotest as a general
20032 testing framework.
20034 Nonetheless, compared to Deja@acronym{GNU}, Autotest is inadequate for
20035 interactive tool testing, which is probably its main limitation.
20037 @menu
20038 * Using an Autotest Test Suite::  Autotest and the user
20039 * Writing Testsuites::          Autotest macros
20040 * testsuite Invocation::        Running @command{testsuite} scripts
20041 * Making testsuite Scripts::    Using autom4te to create @command{testsuite}
20042 @end menu
20044 @node Using an Autotest Test Suite
20045 @section Using an Autotest Test Suite
20047 @menu
20048 * testsuite Scripts::           The concepts of Autotest
20049 * Autotest Logs::               Their contents
20050 @end menu
20052 @node testsuite Scripts
20053 @subsection @command{testsuite} Scripts
20055 @cindex @command{testsuite}
20057 Generating testing or validation suites using Autotest is rather easy.
20058 The whole validation suite is held in a file to be processed through
20059 @command{autom4te}, itself using @acronym{GNU} M4 under the scene, to
20060 produce a stand-alone Bourne shell script which then gets distributed.
20061 Neither @command{autom4te} nor @acronym{GNU} M4 are needed at
20062 the installer's end.
20064 @cindex test group
20065 Each test of the validation suite should be part of some test group.  A
20066 @dfn{test group} is a sequence of interwoven tests that ought to be
20067 executed together, usually because one test in the group creates data
20068 files than a later test in the same group needs to read.  Complex test
20069 groups make later debugging more tedious.  It is much better to
20070 keep only a few tests per test group.  Ideally there is only one test
20071 per test group.
20073 For all but the simplest packages, some file such as @file{testsuite.at}
20074 does not fully hold all test sources, as these are often easier to
20075 maintain in separate files.  Each of these separate files holds a single
20076 test group, or a sequence of test groups all addressing some common
20077 functionality in the package.  In such cases, @file{testsuite.at}
20078 merely initializes the validation suite, and sometimes does elementary
20079 health checking, before listing include statements for all other test
20080 files.  The special file @file{package.m4}, containing the
20081 identification of the package, is automatically included if found.
20083 A convenient alternative consists in moving all the global issues
20084 (local Autotest macros, elementary health checking, and @code{AT_INIT}
20085 invocation) into the file @code{local.at}, and making
20086 @file{testsuite.at} be a simple list of @code{m4_include} of sub test
20087 suites.  In such case, generating the whole test suite or pieces of it
20088 is only a matter of choosing the @command{autom4te} command line
20089 arguments.
20091 The validation scripts that Autotest produces are by convention called
20092 @command{testsuite}.  When run, @command{testsuite} executes each test
20093 group in turn, producing only one summary line per test to say if that
20094 particular test succeeded or failed.  At end of all tests, summarizing
20095 counters get printed.  One debugging directory is left for each test
20096 group which failed, if any: such directories are named
20097 @file{testsuite.dir/@var{nn}}, where @var{nn} is the sequence number of
20098 the test group, and they include:
20100 @itemize @bullet
20101 @item a debugging script named @file{run} which reruns the test in
20102 @dfn{debug mode} (@pxref{testsuite Invocation}).  The automatic generation
20103 of debugging scripts has the purpose of easing the chase for bugs.
20105 @item all the files created with @code{AT_DATA}
20107 @item a log of the run, named @file{testsuite.log}
20108 @end itemize
20110 In the ideal situation, none of the tests fail, and consequently no
20111 debugging directory is left behind for validation.
20113 It often happens in practice that individual tests in the validation
20114 suite need to get information coming out of the configuration process.
20115 Some of this information, common for all validation suites, is provided
20116 through the file @file{atconfig}, automatically created by
20117 @code{AC_CONFIG_TESTDIR}.  For configuration informations which your
20118 testing environment specifically needs, you might prepare an optional
20119 file named @file{atlocal.in}, instantiated by @code{AC_CONFIG_FILES}.
20120 The configuration process produces @file{atconfig} and @file{atlocal}
20121 out of these two input files, and these two produced files are
20122 automatically read by the @file{testsuite} script.
20124 Here is a diagram showing the relationship between files.
20126 @noindent
20127 Files used in preparing a software package for distribution:
20129 @example
20130                 [package.m4] -->.
20131                                  \
20132 subfile-1.at ->.  [local.at] ---->+
20133     ...         \                  \
20134 subfile-i.at ---->-- testsuite.at -->-- autom4te* -->testsuite
20135     ...         /
20136 subfile-n.at ->'
20137 @end example
20139 @noindent
20140 Files used in configuring a software package:
20142 @example
20143                                      .--> atconfig
20144                                     /
20145 [atlocal.in] -->  config.status* --<
20146                                     \
20147                                      `--> [atlocal]
20148 @end example
20150 @noindent
20151 Files created during the test suite execution:
20153 @example
20154 atconfig -->.                    .--> testsuite.log
20155              \                  /
20156               >-- testsuite* --<
20157              /                  \
20158 [atlocal] ->'                    `--> [testsuite.dir]
20159 @end example
20162 @node Autotest Logs
20163 @subsection Autotest Logs
20165 When run, the test suite creates a log file named after itself, e.g., a
20166 test suite named @command{testsuite} creates @file{testsuite.log}.  It
20167 contains a lot of information, usually more than maintainers actually
20168 need, but therefore most of the time it contains all that is needed:
20170 @table @asis
20171 @item command line arguments
20172 @c akim s/to consist in/to consist of/
20173 A bad but unfortunately widespread habit consists of
20174 setting environment variables before the command, such as in
20175 @samp{CC=my-home-grown-cc ./testsuite}.  The test suite does not
20176 know this change, hence (i) it cannot report it to you, and (ii)
20177 it cannot preserve the value of @code{CC} for subsequent runs.
20178 Autoconf faced exactly the same problem, and solved it by asking
20179 users to pass the variable definitions as command line arguments.
20180 Autotest requires this rule, too, but has no means to enforce it; the log
20181 then contains a trace of the variables that were changed by the user.
20183 @item @file{ChangeLog} excerpts
20184 The topmost lines of all the @file{ChangeLog} files found in the source
20185 hierarchy.  This is especially useful when bugs are reported against
20186 development versions of the package, since the version string does not
20187 provide sufficient information to know the exact state of the sources
20188 the user compiled.  Of course, this relies on the use of a
20189 @file{ChangeLog}.
20191 @item build machine
20192 Running a test suite in a cross-compile environment is not an easy task,
20193 since it would mean having the test suite run on a machine @var{build},
20194 while running programs on a machine @var{host}.  It is much simpler to
20195 run both the test suite and the programs on @var{host}, but then, from
20196 the point of view of the test suite, there remains a single environment,
20197 @var{host} = @var{build}.  The log contains relevant information on the
20198 state of the build machine, including some important environment
20199 variables.
20200 @c FIXME: How about having an M4sh macro to say `hey, log the value
20201 @c of `@dots{}'?  This would help both Autoconf and Autotest.
20203 @item tested programs
20204 The absolute file name and answers to @option{--version} of the tested
20205 programs (see @ref{Writing Testsuites}, @code{AT_TESTED}).
20207 @item configuration log
20208 The contents of @file{config.log}, as created by @command{configure},
20209 are appended.  It contains the configuration flags and a detailed report
20210 on the configuration itself.
20211 @end table
20214 @node Writing Testsuites
20215 @section Writing @file{testsuite.at}
20217 The @file{testsuite.at} is a Bourne shell script making use of special
20218 Autotest M4 macros.  It often contains a call to @code{AT_INIT} near
20219 its beginning followed by one call to @code{m4_include} per source file
20220 for tests.  Each such included file, or the remainder of
20221 @file{testsuite.at} if include files are not used, contain a sequence of
20222 test groups.  Each test group begins with a call to @code{AT_SETUP},
20223 then an arbitrary number of shell commands or calls to @code{AT_CHECK},
20224 and then completes with a call to @code{AT_CLEANUP}.  Multiple test
20225 groups can be categorized by a call to @code{AT_BANNER}.
20227 @defmac AT_INIT (@ovar{name})
20228 @atindex{INIT}
20229 @c FIXME: Not clear, plus duplication of the information.
20230 Initialize Autotest.  Giving a @var{name} to the test suite is
20231 encouraged if your package includes several test suites.  In any case,
20232 the test suite always displays the package name and version.  It also
20233 inherits the package bug report address.
20234 @end defmac
20236 @defmac AT_COPYRIGHT (@var{copyright-notice})
20237 @atindex{COPYRIGHT}
20238 @cindex Copyright Notice
20239 State that, in addition to the Free Software Foundation's copyright on
20240 the Autotest macros, parts of your test suite are covered by
20241 @var{copyright-notice}.
20243 The @var{copyright-notice} shows up in both the head of
20244 @command{testsuite} and in @samp{testsuite --version}.
20245 @end defmac
20247 @defmac AT_TESTED (@var{executables})
20248 @atindex{TESTED}
20249 Log the file name and answer to @option{--version} of each program in
20250 space-separated list @var{executables}.  Several invocations register
20251 new executables, in other words, don't fear registering one program
20252 several times.
20253 @end defmac
20255 Autotest test suites rely on @env{PATH} to find the tested program.
20256 This avoids the need to generate absolute names of the various tools, and
20257 makes it possible to test installed programs.  Therefore, knowing which
20258 programs are being exercised is crucial to understanding problems in
20259 the test suite itself, or its occasional misuses.  It is a good idea to
20260 also subscribe foreign programs you depend upon, to avoid incompatible
20261 diagnostics.
20263 @sp 1
20265 @defmac AT_BANNER (@var{test-category-name})
20266 @atindex{BANNER}
20267 This macro identifies the start of a category of related test groups.
20268 When the resulting @file{testsuite} is invoked with more than one test
20269 group to run, its output will include a banner containing
20270 @var{test-category-name} prior to any tests run from that category.  The
20271 banner should be no more than about 40 or 50 characters.  A blank banner
20272 will not print, effectively ending a category and letting subsequent
20273 test groups behave as though they are uncategorized when run in
20274 isolation.
20275 @end defmac
20277 @defmac AT_SETUP (@var{test-group-name})
20278 @atindex{SETUP}
20279 This macro starts a group of related tests, all to be executed in the
20280 same subshell.  It accepts a single argument, which holds a few words
20281 (no more than about 30 or 40 characters) quickly describing the purpose
20282 of the test group being started.  @var{test-group-name} must not contain
20283 unbalanced quotes or parentheses.
20284 @end defmac
20286 @defmac AT_KEYWORDS (@var{keywords})
20287 @atindex{KEYWORDS}
20288 Associate the space-separated list of @var{keywords} to the enclosing
20289 test group.  This makes it possible to run ``slices'' of the test suite.
20290 For instance, if some of your test groups exercise some @samp{foo}
20291 feature, then using @samp{AT_KEYWORDS(foo)} lets you run
20292 @samp{./testsuite -k foo} to run exclusively these test groups.  The
20293 @var{title} of the test group is automatically recorded to
20294 @code{AT_KEYWORDS}.
20296 Several invocations within a test group accumulate new keywords.  In
20297 other words, don't fear registering the same keyword several times in a
20298 test group.
20299 @end defmac
20301 @defmac AT_CAPTURE_FILE (@var{file})
20302 @atindex{CAPTURE_FILE}
20303 If the current test group fails, log the contents of @var{file}.
20304 Several identical calls within one test group have no additional effect.
20305 @end defmac
20307 @defmac AT_XFAIL_IF (@var{shell-condition})
20308 @atindex{XFAIL_IF}
20309 Determine whether the test is expected to fail because it is a known
20310 bug (for unsupported features, you should skip the test).
20311 @var{shell-condition} is a shell expression such as a @code{test}
20312 command; you can instantiate this macro many times from within the
20313 same test group, and one of the conditions is enough to turn
20314 the test into an expected failure.
20315 @end defmac
20317 @defmac AT_CLEANUP
20318 @atindex{CLEANUP}
20319 End the current test group.
20320 @end defmac
20322 @sp 1
20324 @defmac AT_DATA (@var{file}, @var{contents})
20325 @atindex{DATA}
20326 Initialize an input data @var{file} with given @var{contents}.  Of
20327 course, the @var{contents} have to be properly quoted between square
20328 brackets to protect against included commas or spurious M4
20329 expansion.  The contents must end with an end of line.  @var{file} must
20330 be a single shell word that expands into a single file name.
20331 @end defmac
20333 @defmac AT_CHECK (@var{commands}, @dvar{status, 0}, @dvar{stdout, }, @
20334   @dvar{stderr, }, @ovar{run-if-fail}, @ovar{run-if-pass})
20335 @atindex{CHECK}
20336 Execute a test by performing given shell @var{commands}.  These commands
20337 should normally exit with @var{status}, while producing expected
20338 @var{stdout} and @var{stderr} contents.  If @var{commands} exit with
20339 status 77, then the whole test group is skipped.  Otherwise, if this test
20340 fails, run shell commands @var{run-if-fail} or, if this test passes, run shell
20341 commands @var{run-if-pass}.
20343 This macro must be invoked in between @code{AT_SETUP} and @code{AT_CLEANUP}.
20345 @c Previously, we had this:
20346 @c  The @var{commands} @emph{must not} redirect the standard output, nor the
20347 @c  standard error.
20348 @c to prevent trigerring the double redirect bug on Ultrix, see
20349 @c `File Descriptors'.  This was too restricting, and Ultrix is pretty
20350 @c much dead, so we dropped the limitation; the obvious workaround on
20351 @c Ultrix is to use a working shell there.
20353 If @var{status}, or @var{stdout}, or @var{stderr} is @samp{ignore}, then
20354 the corresponding value is not checked.
20356 The special value @samp{expout} for @var{stdout} means the expected
20357 output of the @var{commands} is the content of the file @file{expout}.
20358 If @var{stdout} is @samp{stdout}, then the standard output of the
20359 @var{commands} is available for further tests in the file @file{stdout}.
20360 Similarly for @var{stderr} with @samp{experr} and @samp{stderr}.
20361 @end defmac
20364 @node testsuite Invocation
20365 @section Running @command{testsuite} Scripts
20366 @cindex @command{testsuite}
20368 Autotest test suites support the following arguments:
20370 @table @option
20371 @item --help
20372 @itemx -h
20373 Display the list of options and exit successfully.
20375 @item --version
20376 @itemx -V
20377 Display the version of the test suite and exit successfully.
20379 @item --directory=@var{dir}
20380 @itemx -C @var{dir}
20381 Change the current directory to @var{dir} before creating any files.
20382 Useful for running the testsuite in a subdirectory from a top-level
20383 Makefile.
20385 @item --clean
20386 @itemx -c
20387 Remove all the files the test suite might have created and exit.  Meant
20388 for @code{clean} Make targets.
20390 @item --list
20391 @itemx -l
20392 List all the tests (or only the selection), including their possible
20393 keywords.
20394 @end table
20396 @sp 1
20398 By default all tests are performed (or described with
20399 @option{--list}) in the default environment first silently, then
20400 verbosely, but the environment, set of tests, and verbosity level can be
20401 tuned:
20403 @table @samp
20404 @item @var{variable}=@var{value}
20405 Set the environment @var{variable} to @var{value}.  Use this rather
20406 than @samp{FOO=foo ./testsuite} as debugging scripts would then run in a
20407 different environment.
20409 @cindex @code{AUTOTEST_PATH}
20410 The variable @code{AUTOTEST_PATH} specifies the testing path to prepend
20411 to @env{PATH}.  Relative directory names (not starting with
20412 @samp{/}) are considered to be relative to the top level of the
20413 package being built.  All directories are made absolute, first
20414 starting from the top level @emph{build} tree, then from the
20415 @emph{source} tree.  For instance @samp{./testsuite
20416 AUTOTEST_PATH=tests:bin} for a @file{/src/foo-1.0} source package built
20417 in @file{/tmp/foo} results in @samp{/tmp/foo/tests:/tmp/foo/bin} and
20418 then @samp{/src/foo-1.0/tests:/src/foo-1.0/bin} being prepended to
20419 @env{PATH}.
20421 @item @var{number}
20422 @itemx @var{number}-@var{number}
20423 @itemx @var{number}-
20424 @itemx -@var{number}
20425 Add the corresponding test groups, with obvious semantics, to the
20426 selection.
20428 @item --keywords=@var{keywords}
20429 @itemx -k @var{keywords}
20430 Add to the selection the test groups with title or keywords (arguments
20431 to @code{AT_SETUP} or @code{AT_KEYWORDS}) that match @emph{all} keywords
20432 of the comma separated list @var{keywords}, case-insensitively.  Use
20433 @samp{!} immediately before the keyword to invert the selection for this
20434 keyword.  By default, the keywords match whole words; enclose them in
20435 @samp{.*} to also match parts of words.
20437 For example, running
20439 @example
20440 @kbd{./testsuite -k 'autoupdate,.*FUNC.*'}
20441 @end example
20443 @noindent
20444 selects all tests tagged @samp{autoupdate} @emph{and} with tags
20445 containing @samp{FUNC} (as in @samp{AC_CHECK_FUNC}, @samp{AC_FUNC_ALLOCA},
20446 etc.), while
20448 @example
20449 @kbd{./testsuite -k '!autoupdate' -k '.*FUNC.*'}
20450 @end example
20452 @noindent
20453 selects all tests not tagged @samp{autoupdate} @emph{or} with tags
20454 containing @samp{FUNC}.
20456 @item --errexit
20457 @itemx -e
20458 If any test fails, immediately abort testing.  It implies
20459 @option{--debug}: post test group clean up, and top-level logging
20460 are inhibited.  This option is meant for the full test
20461 suite, it is not really useful for generated debugging scripts.
20463 @item --verbose
20464 @itemx -v
20465 Force more verbosity in the detailed output of what is being done.  This
20466 is the default for debugging scripts.
20468 @item --debug
20469 @itemx -d
20470 Do not remove the files after a test group was performed ---but they are
20471 still removed @emph{before}, therefore using this option is sane when
20472 running several test groups.  Create debugging scripts.  Do not
20473 overwrite the top-level
20474 log (in order to preserve supposedly existing full log file).  This is
20475 the default for debugging scripts, but it can also be useful to debug
20476 the testsuite itself.
20478 @item --trace
20479 @itemx -x
20480 Trigger shell tracing of the test groups.
20481 @end table
20484 @node Making testsuite Scripts
20485 @section Making @command{testsuite} Scripts
20487 For putting Autotest into movement, you need some configuration and
20488 makefile machinery.  We recommend, at least if your package uses deep or
20489 shallow hierarchies, that you use @file{tests/} as the name of the
20490 directory holding all your tests and their makefile.  Here is a
20491 check list of things to do.
20493 @itemize @minus
20495 @item
20496 @cindex @file{package.m4}
20497 Make sure to create the file @file{package.m4}, which defines the
20498 identity of the package.  It must define @code{AT_PACKAGE_STRING}, the
20499 full signature of the package, and @code{AT_PACKAGE_BUGREPORT}, the
20500 address to which bug reports should be sent.  For sake of completeness,
20501 we suggest that you also define @code{AT_PACKAGE_NAME},
20502 @code{AT_PACKAGE_TARNAME}, and @code{AT_PACKAGE_VERSION}.
20503 @xref{Initializing configure}, for a description of these variables.  We
20504 suggest the following makefile excerpt:
20506 @smallexample
20507 # The `:;' works around a Bash 3.2 bug when the output is not writeable.
20508 $(srcdir)/package.m4: $(top_srcdir)/configure.ac
20509         :;@{ \
20510           echo '# Signature of the current package.' && \
20511           echo 'm4_define([AT_PACKAGE_NAME],      [@@PACKAGE_NAME@@])' && \
20512           echo 'm4_define([AT_PACKAGE_TARNAME],   [@@PACKAGE_TARNAME@@])' && \
20513           echo 'm4_define([AT_PACKAGE_VERSION],   [@@PACKAGE_VERSION@@])' && \
20514           echo 'm4_define([AT_PACKAGE_STRING],    [@@PACKAGE_STRING@@])' && \
20515           echo 'm4_define([AT_PACKAGE_BUGREPORT], [@@PACKAGE_BUGREPORT@@])'; \
20516         @} >'$(srcdir)/package.m4'
20517 @end smallexample
20519 @noindent
20520 Be sure to distribute @file{package.m4} and to put it into the source
20521 hierarchy: the test suite ought to be shipped!
20523 @item
20524 Invoke @code{AC_CONFIG_TESTDIR}.
20526 @defmac AC_CONFIG_TESTDIR (@var{directory}, @dvar{test-path, directory})
20527 @acindex{CONFIG_TESTDIR}
20528 An Autotest test suite is to be configured in @var{directory}.  This
20529 macro requires the instantiation of @file{@var{directory}/atconfig} from
20530 @file{@var{directory}/atconfig.in}, and sets the default
20531 @code{AUTOTEST_PATH} to @var{test-path} (@pxref{testsuite Invocation}).
20532 @end defmac
20534 @item
20535 Still within @file{configure.ac}, as appropriate, ensure that some
20536 @code{AC_CONFIG_FILES} command includes substitution for
20537 @file{tests/atlocal}.
20539 @item
20540 The @file{tests/Makefile.in} should be modified so the validation in
20541 your package is triggered by @samp{make check}.  An example is provided
20542 below.
20543 @end itemize
20545 With Automake, here is a minimal example about how to link @samp{make
20546 check} with a validation suite.
20548 @example
20549 EXTRA_DIST = testsuite.at $(TESTSUITE) atlocal.in
20550 TESTSUITE = $(srcdir)/testsuite
20552 check-local: atconfig atlocal $(TESTSUITE)
20553         $(SHELL) '$(TESTSUITE)' $(TESTSUITEFLAGS)
20555 installcheck-local: atconfig atlocal $(TESTSUITE)
20556         $(SHELL) '$(TESTSUITE)' AUTOTEST_PATH='$(bindir)' \
20557           $(TESTSUITEFLAGS)
20559 clean-local:
20560         test ! -f '$(TESTSUITE)' || \
20561          $(SHELL) '$(TESTSUITE)' --clean
20563 AUTOTEST = $(AUTOM4TE) --language=autotest
20564 $(TESTSUITE): $(srcdir)/testsuite.at
20565         $(AUTOTEST) -I '$(srcdir)' -o $@@.tmp $@@.at
20566         mv $@@.tmp $@@
20567 @end example
20569 You might want to list explicitly the dependencies, i.e., the list of
20570 the files @file{testsuite.at} includes.
20572 If you don't use Automake, you might need to add lines inspired from the
20573 following:
20575 @example
20576 subdir = tests
20578 atconfig: $(top_builddir)/config.status
20579         cd $(top_builddir) && \
20580            $(SHELL) ./config.status $(subdir)/$@@
20582 atlocal: $(srcdir)/atlocal.in $(top_builddir)/config.status
20583         cd $(top_builddir) && \
20584            $(SHELL) ./config.status $(subdir)/$@@
20585 @end example
20587 @noindent
20588 and manage to have @code{$(EXTRA_DIST)} distributed.
20590 If you use Automake, however, you don't need to add a rule to generate
20591 @file{atlocal}.
20593 With all this in place, and if you have not initialized @samp{TESTSUITEFLAGS}
20594 within your makefile, you can fine-tune test suite execution with this
20595 variable, for example:
20597 @example
20598 make check TESTSUITEFLAGS='-v -d -x 75 -k AC_PROG_CC CFLAGS=-g'
20599 @end example
20603 @c =============================== Frequent Autoconf Questions, with answers
20605 @node FAQ
20606 @chapter Frequent Autoconf Questions, with answers
20608 Several questions about Autoconf come up occasionally.  Here some of them
20609 are addressed.
20611 @menu
20612 * Distributing::                Distributing @command{configure} scripts
20613 * Why GNU M4::                  Why not use the standard M4?
20614 * Bootstrapping::               Autoconf and @acronym{GNU} M4 require each other?
20615 * Why Not Imake::               Why @acronym{GNU} uses @command{configure} instead of Imake
20616 * Defining Directories::        Passing @code{datadir} to program
20617 * Autom4te Cache::              What is it?  Can I remove it?
20618 * Present But Cannot Be Compiled::  Compiler and Preprocessor Disagree
20619 @end menu
20621 @node Distributing
20622 @section Distributing @command{configure} Scripts
20623 @cindex License
20625 @display
20626 What are the restrictions on distributing @command{configure}
20627 scripts that Autoconf generates?  How does that affect my
20628 programs that use them?
20629 @end display
20631 There are no restrictions on how the configuration scripts that Autoconf
20632 produces may be distributed or used.  In Autoconf version 1, they were
20633 covered by the @acronym{GNU} General Public License.  We still encourage
20634 software authors to distribute their work under terms like those of the
20635 @acronym{GPL}, but doing so is not required to use Autoconf.
20637 Of the other files that might be used with @command{configure},
20638 @file{config.h.in} is under whatever copyright you use for your
20639 @file{configure.ac}.  @file{config.sub} and @file{config.guess} have an
20640 exception to the @acronym{GPL} when they are used with an Autoconf-generated
20641 @command{configure} script, which permits you to distribute them under the
20642 same terms as the rest of your package.  @file{install-sh} is from the X
20643 Consortium and is not copyrighted.
20645 @node Why GNU M4
20646 @section Why Require @acronym{GNU} M4?
20648 @display
20649 Why does Autoconf require @acronym{GNU} M4?
20650 @end display
20652 Many M4 implementations have hard-coded limitations on the size and
20653 number of macros that Autoconf exceeds.  They also lack several
20654 builtin macros that it would be difficult to get along without in a
20655 sophisticated application like Autoconf, including:
20657 @example
20658 m4_builtin
20659 m4_indir
20660 m4_bpatsubst
20661 __file__
20662 __line__
20663 @end example
20665 Autoconf requires version 1.4.5 or later of @acronym{GNU} M4.
20667 Since only software maintainers need to use Autoconf, and since @acronym{GNU}
20668 M4 is simple to configure and install, it seems reasonable to require
20669 @acronym{GNU} M4 to be installed also.  Many maintainers of @acronym{GNU} and
20670 other free software already have most of the @acronym{GNU} utilities
20671 installed, since they prefer them.
20673 @node Bootstrapping
20674 @section How Can I Bootstrap?
20675 @cindex Bootstrap
20677 @display
20678 If Autoconf requires @acronym{GNU} M4 and @acronym{GNU} M4 has an Autoconf
20679 @command{configure} script, how do I bootstrap?  It seems like a chicken
20680 and egg problem!
20681 @end display
20683 This is a misunderstanding.  Although @acronym{GNU} M4 does come with a
20684 @command{configure} script produced by Autoconf, Autoconf is not required
20685 in order to run the script and install @acronym{GNU} M4.  Autoconf is only
20686 required if you want to change the M4 @command{configure} script, which few
20687 people have to do (mainly its maintainer).
20689 @node Why Not Imake
20690 @section Why Not Imake?
20691 @cindex Imake
20693 @display
20694 Why not use Imake instead of @command{configure} scripts?
20695 @end display
20697 Several people have written addressing this question, so I include
20698 adaptations of their explanations here.
20700 The following answer is based on one written by Richard Pixley:
20702 @quotation
20703 Autoconf generated scripts frequently work on machines that it has
20704 never been set up to handle before.  That is, it does a good job of
20705 inferring a configuration for a new system.  Imake cannot do this.
20707 Imake uses a common database of host specific data.  For X11, this makes
20708 sense because the distribution is made as a collection of tools, by one
20709 central authority who has control over the database.
20711 @acronym{GNU} tools are not released this way.  Each @acronym{GNU} tool has a
20712 maintainer; these maintainers are scattered across the world.  Using a
20713 common database would be a maintenance nightmare.  Autoconf may appear
20714 to be this kind of database, but in fact it is not.  Instead of listing
20715 host dependencies, it lists program requirements.
20717 If you view the @acronym{GNU} suite as a collection of native tools, then the
20718 problems are similar.  But the @acronym{GNU} development tools can be
20719 configured as cross tools in almost any host+target permutation.  All of
20720 these configurations can be installed concurrently.  They can even be
20721 configured to share host independent files across hosts.  Imake doesn't
20722 address these issues.
20724 Imake templates are a form of standardization.  The @acronym{GNU} coding
20725 standards address the same issues without necessarily imposing the same
20726 restrictions.
20727 @end quotation
20730 Here is some further explanation, written by Per Bothner:
20732 @quotation
20733 One of the advantages of Imake is that it easy to generate large
20734 makefiles using the @samp{#include} and macro mechanisms of @command{cpp}.
20735 However, @code{cpp} is not programmable: it has limited conditional
20736 facilities, and no looping.  And @code{cpp} cannot inspect its
20737 environment.
20739 All of these problems are solved by using @code{sh} instead of
20740 @code{cpp}.  The shell is fully programmable, has macro substitution,
20741 can execute (or source) other shell scripts, and can inspect its
20742 environment.
20743 @end quotation
20746 Paul Eggert elaborates more:
20748 @quotation
20749 With Autoconf, installers need not assume that Imake itself is already
20750 installed and working well.  This may not seem like much of an advantage
20751 to people who are accustomed to Imake.  But on many hosts Imake is not
20752 installed or the default installation is not working well, and requiring
20753 Imake to install a package hinders the acceptance of that package on
20754 those hosts.  For example, the Imake template and configuration files
20755 might not be installed properly on a host, or the Imake build procedure
20756 might wrongly assume that all source files are in one big directory
20757 tree, or the Imake configuration might assume one compiler whereas the
20758 package or the installer needs to use another, or there might be a
20759 version mismatch between the Imake expected by the package and the Imake
20760 supported by the host.  These problems are much rarer with Autoconf,
20761 where each package comes with its own independent configuration
20762 processor.
20764 Also, Imake often suffers from unexpected interactions between
20765 @command{make} and the installer's C preprocessor.  The fundamental problem
20766 here is that the C preprocessor was designed to preprocess C programs,
20767 not makefiles.  This is much less of a problem with Autoconf,
20768 which uses the general-purpose preprocessor M4, and where the
20769 package's author (rather than the installer) does the preprocessing in a
20770 standard way.
20771 @end quotation
20774 Finally, Mark Eichin notes:
20776 @quotation
20777 Imake isn't all that extensible, either.  In order to add new features to
20778 Imake, you need to provide your own project template, and duplicate most
20779 of the features of the existing one.  This means that for a sophisticated
20780 project, using the vendor-provided Imake templates fails to provide any
20781 leverage---since they don't cover anything that your own project needs
20782 (unless it is an X11 program).
20784 On the other side, though:
20786 The one advantage that Imake has over @command{configure}:
20787 @file{Imakefile} files tend to be much shorter (likewise, less redundant)
20788 than @file{Makefile.in} files.  There is a fix to this, however---at least
20789 for the Kerberos V5 tree, we've modified things to call in common
20790 @file{post.in} and @file{pre.in} makefile fragments for the
20791 entire tree.  This means that a lot of common things don't have to be
20792 duplicated, even though they normally are in @command{configure} setups.
20793 @end quotation
20796 @node Defining Directories
20797 @section How Do I @code{#define} Installation Directories?
20799 @display
20800 My program needs library files, installed in @code{datadir} and
20801 similar.  If I use
20803 @example
20804 AC_DEFINE_UNQUOTED([DATADIR], [$datadir],
20805   [Define to the read-only architecture-independent
20806    data directory.])
20807 @end example
20809 @noindent
20810 I get
20812 @example
20813 #define DATADIR "$@{prefix@}/share"
20814 @end example
20815 @end display
20817 As already explained, this behavior is on purpose, mandated by the
20818 @acronym{GNU} Coding Standards, see @ref{Installation Directory
20819 Variables}.  There are several means to achieve a similar goal:
20821 @itemize @minus
20822 @item
20823 Do not use @code{AC_DEFINE} but use your makefile to pass the
20824 actual value of @code{datadir} via compilation flags.
20825 @xref{Installation Directory Variables}, for the details.
20827 @item
20828 This solution can be simplified when compiling a program: you may either
20829 extend the @code{CPPFLAGS}:
20831 @example
20832 CPPFLAGS = -DDATADIR='"$(datadir)"' @@CPPFLAGS@@
20833 @end example
20835 @noindent
20836 If you are using Automake, you should use @code{AM_CPPFLAGS} instead:
20838 @example
20839 AM_CPPFLAGS = -DDATADIR='"$(datadir)"'
20840 @end example
20842 @noindent
20843 Alternatively, create a dedicated header file:
20845 @example
20846 DISTCLEANFILES = myprog-paths.h
20847 myprog-paths.h: Makefile
20848         echo '#define DATADIR "$(datadir)"' >$@@
20849 @end example
20851 @item
20852 Use @code{AC_DEFINE} but have @command{configure} compute the literal
20853 value of @code{datadir} and others.  Many people have wrapped macros to
20854 automate this task.  For instance, the macro @code{AC_DEFINE_DIR} from
20855 the @uref{http://autoconf-archive.cryp.to/, Autoconf Macro
20856 Archive}.
20858 This solution does not conform to the @acronym{GNU} Coding Standards.
20860 @item
20861 Note that all the previous solutions hard wire the absolute name of
20862 these directories in the executables, which is not a good property.  You
20863 may try to compute the names relative to @code{prefix}, and try to
20864 find @code{prefix} at runtime, this way your package is relocatable.
20865 @end itemize
20868 @node Autom4te Cache
20869 @section What is @file{autom4te.cache}?
20871 @display
20872 What is this directory @file{autom4te.cache}?  Can I safely remove it?
20873 @end display
20875 In the @acronym{GNU} Build System, @file{configure.ac} plays a central
20876 role and is read by many tools: @command{autoconf} to create
20877 @file{configure}, @command{autoheader} to create @file{config.h.in},
20878 @command{automake} to create @file{Makefile.in}, @command{autoscan} to
20879 check the completeness of @file{configure.ac}, @command{autoreconf} to
20880 check the @acronym{GNU} Build System components that are used.  To
20881 ``read @file{configure.ac}'' actually means to compile it with M4,
20882 which can be a long process for complex @file{configure.ac}.
20884 This is why all these tools, instead of running directly M4, invoke
20885 @command{autom4te} (@pxref{autom4te Invocation}) which, while answering to
20886 a specific demand, stores additional information in
20887 @file{autom4te.cache} for future runs.  For instance, if you run
20888 @command{autoconf}, behind the scenes, @command{autom4te} also
20889 stores information for the other tools, so that when you invoke
20890 @command{autoheader} or @command{automake} etc., reprocessing
20891 @file{configure.ac} is not needed.  The speed up is frequently 30%,
20892 and is increasing with the size of @file{configure.ac}.
20894 But it is and remains being simply a cache: you can safely remove it.
20896 @sp 1
20898 @display
20899 Can I permanently get rid of it?
20900 @end display
20902 The creation of this cache can be disabled from
20903 @file{~/.autom4te.cfg}, see @ref{Customizing autom4te}, for more
20904 details.  You should be aware that disabling the cache slows down the
20905 Autoconf test suite by 40%.  The more @acronym{GNU} Build System
20906 components are used, the more the cache is useful; for instance
20907 running @samp{autoreconf -f} on the Core Utilities is twice slower without
20908 the cache @emph{although @option{--force} implies that the cache is
20909 not fully exploited}, and eight times slower than without
20910 @option{--force}.
20913 @node Present But Cannot Be Compiled
20914 @section Header Present But Cannot Be Compiled
20916 The most important guideline to bear in mind when checking for
20917 features is to mimic as much as possible the intended use.
20918 Unfortunately, old versions of @code{AC_CHECK_HEADER} and
20919 @code{AC_CHECK_HEADERS} failed to follow this idea, and called
20920 the preprocessor, instead of the compiler, to check for headers.  As a
20921 result, incompatibilities between headers went unnoticed during
20922 configuration, and maintainers finally had to deal with this issue
20923 elsewhere.
20925 As of Autoconf 2.56 both checks are performed, and @code{configure}
20926 complains loudly if the compiler and the preprocessor do not agree.
20927 For the time being the result used is that of the preprocessor, to give
20928 maintainers time to adjust their @file{configure.ac}, but in the
20929 future, only the compiler will be considered.
20931 Consider the following example:
20933 @smallexample
20934 $ @kbd{cat number.h}
20935 typedef int number;
20936 $ @kbd{cat pi.h}
20937 const number pi = 3;
20938 $ @kbd{cat configure.ac}
20939 AC_INIT([Example], [1.0], [bug-example@@example.org])
20940 AC_CHECK_HEADERS([pi.h])
20941 $ @kbd{autoconf -Wall}
20942 $ @kbd{./configure}
20943 checking for gcc... gcc
20944 checking for C compiler default output file name... a.out
20945 checking whether the C compiler works... yes
20946 checking whether we are cross compiling... no
20947 checking for suffix of executables...
20948 checking for suffix of object files... o
20949 checking whether we are using the GNU C compiler... yes
20950 checking whether gcc accepts -g... yes
20951 checking for gcc option to accept ISO C89... none needed
20952 checking how to run the C preprocessor... gcc -E
20953 checking for grep that handles long lines and -e... grep
20954 checking for egrep... grep -E
20955 checking for ANSI C header files... yes
20956 checking for sys/types.h... yes
20957 checking for sys/stat.h... yes
20958 checking for stdlib.h... yes
20959 checking for string.h... yes
20960 checking for memory.h... yes
20961 checking for strings.h... yes
20962 checking for inttypes.h... yes
20963 checking for stdint.h... yes
20964 checking for unistd.h... yes
20965 checking pi.h usability... no
20966 checking pi.h presence... yes
20967 configure: WARNING: pi.h: present but cannot be compiled
20968 configure: WARNING: pi.h:     check for missing prerequisite headers?
20969 configure: WARNING: pi.h: see the Autoconf documentation
20970 configure: WARNING: pi.h:     section "Present But Cannot Be Compiled"
20971 configure: WARNING: pi.h: proceeding with the preprocessor's result
20972 configure: WARNING: pi.h: in the future, the compiler will take precedence
20973 configure: WARNING:     ## -------------------------------------- ##
20974 configure: WARNING:     ## Report this to bug-example@@example.org ##
20975 configure: WARNING:     ## -------------------------------------- ##
20976 checking for pi.h... yes
20977 @end smallexample
20979 @noindent
20980 The proper way the handle this case is using the fourth argument
20981 (@pxref{Generic Headers}):
20983 @example
20984 $ @kbd{cat configure.ac}
20985 AC_INIT([Example], [1.0], [bug-example@@example.org])
20986 AC_CHECK_HEADERS([number.h pi.h], [], [],
20987 [[#ifdef HAVE_NUMBER_H
20988 # include <number.h>
20989 #endif
20991 $ @kbd{autoconf -Wall}
20992 $ @kbd{./configure}
20993 checking for gcc... gcc
20994 checking for C compiler default output... a.out
20995 checking whether the C compiler works... yes
20996 checking whether we are cross compiling... no
20997 checking for suffix of executables...
20998 checking for suffix of object files... o
20999 checking whether we are using the GNU C compiler... yes
21000 checking whether gcc accepts -g... yes
21001 checking for gcc option to accept ANSI C... none needed
21002 checking for number.h... yes
21003 checking for pi.h... yes
21004 @end example
21006 See @ref{Particular Headers}, for a list of headers with their
21007 prerequisite.
21009 @c ===================================================== History of Autoconf.
21011 @node History
21012 @chapter History of Autoconf
21013 @cindex History of autoconf
21015 You may be wondering, Why was Autoconf originally written?  How did it
21016 get into its present form?  (Why does it look like gorilla spit?)  If
21017 you're not wondering, then this chapter contains no information useful
21018 to you, and you might as well skip it.  If you @emph{are} wondering,
21019 then let there be light@enddots{}
21021 @menu
21022 * Genesis::                     Prehistory and naming of @command{configure}
21023 * Exodus::                      The plagues of M4 and Perl
21024 * Leviticus::                   The priestly code of portability arrives
21025 * Numbers::                     Growth and contributors
21026 * Deuteronomy::                 Approaching the promises of easy configuration
21027 @end menu
21029 @node Genesis
21030 @section Genesis
21032 In June 1991 I was maintaining many of the @acronym{GNU} utilities for the
21033 Free Software Foundation.  As they were ported to more platforms and
21034 more programs were added, the number of @option{-D} options that users
21035 had to select in the makefile (around 20) became burdensome.
21036 Especially for me---I had to test each new release on a bunch of
21037 different systems.  So I wrote a little shell script to guess some of
21038 the correct settings for the fileutils package, and released it as part
21039 of fileutils 2.0.  That @command{configure} script worked well enough that
21040 the next month I adapted it (by hand) to create similar @command{configure}
21041 scripts for several other @acronym{GNU} utilities packages.  Brian Berliner
21042 also adapted one of my scripts for his @acronym{CVS} revision control system.
21044 Later that summer, I learned that Richard Stallman and Richard Pixley
21045 were developing similar scripts to use in the @acronym{GNU} compiler tools;
21046 so I adapted my @command{configure} scripts to support their evolving
21047 interface: using the file name @file{Makefile.in} as the templates;
21048 adding @samp{+srcdir}, the first option (of many); and creating
21049 @file{config.status} files.
21051 @node Exodus
21052 @section Exodus
21054 As I got feedback from users, I incorporated many improvements, using
21055 Emacs to search and replace, cut and paste, similar changes in each of
21056 the scripts.  As I adapted more @acronym{GNU} utilities packages to use
21057 @command{configure} scripts, updating them all by hand became impractical.
21058 Rich Murphey, the maintainer of the @acronym{GNU} graphics utilities, sent me
21059 mail saying that the @command{configure} scripts were great, and asking if
21060 I had a tool for generating them that I could send him.  No, I thought,
21061 but I should!  So I started to work out how to generate them.  And the
21062 journey from the slavery of hand-written @command{configure} scripts to the
21063 abundance and ease of Autoconf began.
21065 Cygnus @command{configure}, which was being developed at around that time,
21066 is table driven; it is meant to deal mainly with a discrete number of
21067 system types with a small number of mainly unguessable features (such as
21068 details of the object file format).  The automatic configuration system
21069 that Brian Fox had developed for Bash takes a similar approach.  For
21070 general use, it seems to me a hopeless cause to try to maintain an
21071 up-to-date database of which features each variant of each operating
21072 system has.  It's easier and more reliable to check for most features on
21073 the fly---especially on hybrid systems that people have hacked on
21074 locally or that have patches from vendors installed.
21076 I considered using an architecture similar to that of Cygnus
21077 @command{configure}, where there is a single @command{configure} script that
21078 reads pieces of @file{configure.in} when run.  But I didn't want to have
21079 to distribute all of the feature tests with every package, so I settled
21080 on having a different @command{configure} made from each
21081 @file{configure.in} by a preprocessor.  That approach also offered more
21082 control and flexibility.
21084 I looked briefly into using the Metaconfig package, by Larry Wall,
21085 Harlan Stenn, and Raphael Manfredi, but I decided not to for several
21086 reasons.  The @command{Configure} scripts it produces are interactive,
21087 which I find quite inconvenient; I didn't like the ways it checked for
21088 some features (such as library functions); I didn't know that it was
21089 still being maintained, and the @command{Configure} scripts I had
21090 seen didn't work on many modern systems (such as System V R4 and NeXT);
21091 it wasn't flexible in what it could do in response to a feature's
21092 presence or absence; I found it confusing to learn; and it was too big
21093 and complex for my needs (I didn't realize then how much Autoconf would
21094 eventually have to grow).
21096 I considered using Perl to generate my style of @command{configure}
21097 scripts, but decided that M4 was better suited to the job of simple
21098 textual substitutions: it gets in the way less, because output is
21099 implicit.  Plus, everyone already has it.  (Initially I didn't rely on
21100 the @acronym{GNU} extensions to M4.)  Also, some of my friends at the
21101 University of Maryland had recently been putting M4 front ends on
21102 several programs, including @code{tvtwm}, and I was interested in trying
21103 out a new language.
21105 @node Leviticus
21106 @section Leviticus
21108 Since my @command{configure} scripts determine the system's capabilities
21109 automatically, with no interactive user intervention, I decided to call
21110 the program that generates them Autoconfig.  But with a version number
21111 tacked on, that name would be too long for old Unix file systems,
21112 so I shortened it to Autoconf.
21114 In the fall of 1991 I called together a group of fellow questers after
21115 the Holy Grail of portability (er, that is, alpha testers) to give me
21116 feedback as I encapsulated pieces of my handwritten scripts in M4 macros
21117 and continued to add features and improve the techniques used in the
21118 checks.  Prominent among the testers were Fran@,{c}ois Pinard, who came up
21119 with the idea of making an Autoconf shell script to run M4
21120 and check for unresolved macro calls; Richard Pixley, who suggested
21121 running the compiler instead of searching the file system to find
21122 include files and symbols, for more accurate results; Karl Berry, who
21123 got Autoconf to configure @TeX{} and added the macro index to the
21124 documentation; and Ian Lance Taylor, who added support for creating a C
21125 header file as an alternative to putting @option{-D} options in a
21126 makefile, so he could use Autoconf for his @acronym{UUCP} package.
21127 The alpha testers cheerfully adjusted their files again and again as the
21128 names and calling conventions of the Autoconf macros changed from
21129 release to release.  They all contributed many specific checks, great
21130 ideas, and bug fixes.
21132 @node Numbers
21133 @section Numbers
21135 In July 1992, after months of alpha testing, I released Autoconf 1.0,
21136 and converted many @acronym{GNU} packages to use it.  I was surprised by how
21137 positive the reaction to it was.  More people started using it than I
21138 could keep track of, including people working on software that wasn't
21139 part of the @acronym{GNU} Project (such as TCL, FSP, and Kerberos V5).
21140 Autoconf continued to improve rapidly, as many people using the
21141 @command{configure} scripts reported problems they encountered.
21143 Autoconf turned out to be a good torture test for M4 implementations.
21144 Unix M4 started to dump core because of the length of the
21145 macros that Autoconf defined, and several bugs showed up in @acronym{GNU}
21146 M4 as well.  Eventually, we realized that we needed to use some
21147 features that only @acronym{GNU} M4 has.  4.3@acronym{BSD} M4, in
21148 particular, has an impoverished set of builtin macros; the System V
21149 version is better, but still doesn't provide everything we need.
21151 More development occurred as people put Autoconf under more stresses
21152 (and to uses I hadn't anticipated).  Karl Berry added checks for X11.
21153 david zuhn contributed C++ support.  Fran@,{c}ois Pinard made it diagnose
21154 invalid arguments.  Jim Blandy bravely coerced it into configuring
21155 @acronym{GNU} Emacs, laying the groundwork for several later improvements.
21156 Roland McGrath got it to configure the @acronym{GNU} C Library, wrote the
21157 @command{autoheader} script to automate the creation of C header file
21158 templates, and added a @option{--verbose} option to @command{configure}.
21159 Noah Friedman added the @option{--autoconf-dir} option and
21160 @code{AC_MACRODIR} environment variable.  (He also coined the term
21161 @dfn{autoconfiscate} to mean ``adapt a software package to use
21162 Autoconf''.)  Roland and Noah improved the quoting protection in
21163 @code{AC_DEFINE} and fixed many bugs, especially when I got sick of
21164 dealing with portability problems from February through June, 1993.
21166 @node Deuteronomy
21167 @section Deuteronomy
21169 A long wish list for major features had accumulated, and the effect of
21170 several years of patching by various people had left some residual
21171 cruft.  In April 1994, while working for Cygnus Support, I began a major
21172 revision of Autoconf.  I added most of the features of the Cygnus
21173 @command{configure} that Autoconf had lacked, largely by adapting the
21174 relevant parts of Cygnus @command{configure} with the help of david zuhn
21175 and Ken Raeburn.  These features include support for using
21176 @file{config.sub}, @file{config.guess}, @option{--host}, and
21177 @option{--target}; making links to files; and running @command{configure}
21178 scripts in subdirectories.  Adding these features enabled Ken to convert
21179 @acronym{GNU} @code{as}, and Rob Savoye to convert Deja@acronym{GNU}, to using
21180 Autoconf.
21182 I added more features in response to other peoples' requests.  Many
21183 people had asked for @command{configure} scripts to share the results of
21184 the checks between runs, because (particularly when configuring a large
21185 source tree, like Cygnus does) they were frustratingly slow.  Mike
21186 Haertel suggested adding site-specific initialization scripts.  People
21187 distributing software that had to unpack on MS-DOS asked for a way to
21188 override the @file{.in} extension on the file names, which produced file
21189 names like @file{config.h.in} containing two dots.  Jim Avera did an
21190 extensive examination of the problems with quoting in @code{AC_DEFINE}
21191 and @code{AC_SUBST}; his insights led to significant improvements.
21192 Richard Stallman asked that compiler output be sent to @file{config.log}
21193 instead of @file{/dev/null}, to help people debug the Emacs
21194 @command{configure} script.
21196 I made some other changes because of my dissatisfaction with the quality
21197 of the program.  I made the messages showing results of the checks less
21198 ambiguous, always printing a result.  I regularized the names of the
21199 macros and cleaned up coding style inconsistencies.  I added some
21200 auxiliary utilities that I had developed to help convert source code
21201 packages to use Autoconf.  With the help of Fran@,{c}ois Pinard, I made
21202 the macros not interrupt each others' messages.  (That feature revealed
21203 some performance bottlenecks in @acronym{GNU} M4, which he hastily
21204 corrected!)  I reorganized the documentation around problems people want
21205 to solve.  And I began a test suite, because experience had shown that
21206 Autoconf has a pronounced tendency to regress when we change it.
21208 Again, several alpha testers gave invaluable feedback, especially
21209 Fran@,{c}ois Pinard, Jim Meyering, Karl Berry, Rob Savoye, Ken Raeburn,
21210 and Mark Eichin.
21212 Finally, version 2.0 was ready.  And there was much rejoicing.  (And I
21213 have free time again.  I think.  Yeah, right.)
21216 @c ========================================================== Appendices
21219 @node GNU Free Documentation License
21220 @appendix GNU Free Documentation License
21222 @include fdl.texi
21224 @node Indices
21225 @appendix Indices
21227 @menu
21228 * Environment Variable Index::  Index of environment variables used
21229 * Output Variable Index::       Index of variables set in output files
21230 * Preprocessor Symbol Index::   Index of C preprocessor symbols defined
21231 * Autoconf Macro Index::        Index of Autoconf macros
21232 * M4 Macro Index::              Index of M4, M4sugar, and M4sh macros
21233 * Autotest Macro Index::        Index of Autotest macros
21234 * Program & Function Index::    Index of those with portability problems
21235 * Concept Index::               General index
21236 @end menu
21238 @node Environment Variable Index
21239 @appendixsec Environment Variable Index
21241 This is an alphabetical list of the environment variables that Autoconf
21242 checks.
21244 @printindex ev
21246 @node Output Variable Index
21247 @appendixsec Output Variable Index
21249 This is an alphabetical list of the variables that Autoconf can
21250 substitute into files that it creates, typically one or more
21251 makefiles.  @xref{Setting Output Variables}, for more information
21252 on how this is done.
21254 @printindex ov
21256 @node Preprocessor Symbol Index
21257 @appendixsec Preprocessor Symbol Index
21259 This is an alphabetical list of the C preprocessor symbols that the
21260 Autoconf macros define.  To work with Autoconf, C source code needs to
21261 use these names in @code{#if} or @code{#ifdef} directives.
21263 @printindex cv
21265 @node Autoconf Macro Index
21266 @appendixsec Autoconf Macro Index
21268 This is an alphabetical list of the Autoconf macros.
21269 @ifset shortindexflag
21270 To make the list easier to use, the macros are listed without their
21271 preceding @samp{AC_}.
21272 @end ifset
21274 @printindex AC
21276 @node M4 Macro Index
21277 @appendixsec M4 Macro Index
21279 This is an alphabetical list of the M4, M4sugar, and M4sh macros.
21280 @ifset shortindexflag
21281 To make the list easier to use, the macros are listed without their
21282 preceding @samp{m4_} or @samp{AS_}.
21283 @end ifset
21285 @printindex MS
21287 @node Autotest Macro Index
21288 @appendixsec Autotest Macro Index
21290 This is an alphabetical list of the Autotest macros.
21291 @ifset shortindexflag
21292 To make the list easier to use, the macros are listed without their
21293 preceding @samp{AT_}.
21294 @end ifset
21296 @printindex AT
21298 @node Program & Function Index
21299 @appendixsec Program and Function Index
21301 This is an alphabetical list of the programs and functions whose
21302 portability is discussed in this document.
21304 @printindex pr
21306 @node Concept Index
21307 @appendixsec Concept Index
21309 This is an alphabetical list of the files, tools, and concepts
21310 introduced in this document.
21312 @printindex cp
21314 @bye
21316 @c  LocalWords:  texinfo setfilename autoconf texi settitle setchapternewpage
21317 @c  LocalWords:  setcontentsaftertitlepage finalout ARG ovar varname dvar acx
21318 @c  LocalWords:  makeinfo dvi defcodeindex ev ov CPP cv Autotest mv defindex fn
21319 @c  LocalWords:  shortindexflag iftex ifset acindex ACindex ifclear ahindex fu
21320 @c  LocalWords:  asindex MSindex atindex ATindex auindex hdrindex prindex FIXME
21321 @c  LocalWords:  msindex alloca fnindex Aaarg indices FSF's dircategory ifnames
21322 @c  LocalWords:  direntry autoscan autoreconf autoheader autoupdate config FDs
21323 @c  LocalWords:  testsuite titlepage Elliston Demaille vskip filll ifnottex hmm
21324 @c  LocalWords:  insertcopying Autoconf's detailmenu Automake Libtool Posix ois
21325 @c  LocalWords:  Systemology Checkpointing Changequote INTERCAL changequote dfn
21326 @c  LocalWords:  Quadrigraphs builtins Shellology acconfig Bugward LIBOBJ Imake
21327 @c  LocalWords:  LIBOBJS IFELSE cindex flushright Pinard Metaconfig uref Simons
21328 @c  LocalWords:  distclean uninstall noindent versioning Tromey dir
21329 @c  LocalWords:  SAMS samp aclocal acsite underquoted emph itemx prepend SUBST
21330 @c  LocalWords:  evindex automake Gettext autopoint gettext symlink libtoolize
21331 @c  LocalWords:  defmac INIT tarname ovindex cvindex BUGREPORT PREREQ asis PROG
21332 @c  LocalWords:  SRCDIR srcdir globbing afterwards cmds foos fooo foooo init cd
21333 @c  LocalWords:  builddir timestamp src Imakefile chmod defvar CFLAGS CPPFLAGS
21334 @c  LocalWords:  CXXFLAGS DEFS DHAVE defvarx FCFLAGS FFLAGS LDFLAGS bindir GCC
21335 @c  LocalWords:  datadir datarootdir docdir dvidir htmldir libdir ifnothtml kbd
21336 @c  LocalWords:  includedir infodir libexecdir localedir localstatedir mandir
21337 @c  LocalWords:  oldincludedir pdfdir PDF psdir PostScript sbindir sysconfdir
21338 @c  LocalWords:  sharedstatedir DDATADIR sed tmp pkgdatadir VPATH conf unistd
21339 @c  LocalWords:  undef endif builtin FUNCS ifndef STACKSEG getb GETB YMP fubar
21340 @c  LocalWords:  PRE dest SUBDIRS subdirs fi struct STDC stdlib stddef INTTYPES
21341 @c  LocalWords:  inttypes STDINT stdint AWK AIX Solaris NeXT env EGREP FGREP yy
21342 @c  LocalWords:  LEXLIB YYTEXT lfl nonportable Automake's LN RANLIB byacc INETD
21343 @c  LocalWords:  inetd prog PROGS progs ranlib lmp lXt lX nsl gethostbyname UX
21344 @c  LocalWords:  NextStep isinf isnan glibc IRIX sunmath lm lsunmath pre sizeof
21345 @c  LocalWords:  ld inline malloc putenv setenv FreeBSD realloc SunOS MinGW
21346 @c  LocalWords:  snprintf vsnprintf sprintf vsprintf sscanf gcc strerror ifdef
21347 @c  LocalWords:  strnlen sysconf PAGESIZE unsetenv va fallback memcpy dst FUNC
21348 @c  LocalWords:  PowerPC GNUC libPW pragma Olibcalls CHOWN chown CLOSEDIR VFORK
21349 @c  LocalWords:  closedir FNMATCH fnmatch vfork FSEEKO LARGEFILE fseeko SVR sc
21350 @c  LocalWords:  largefile GETGROUPS getgroups GETLOADAVG DGUX UMAX NLIST KMEM
21351 @c  LocalWords:  SETGID getloadavg nlist GETMNTENT irix
21352 @c  LocalWords:  getmntent UnixWare GETPGRP getpgid getpgrp Posix's pid LSTAT
21353 @c  LocalWords:  lstat rpl MEMCMP memcmp OpenStep MBRTOWC mbrtowc MKTIME mktime
21354 @c  LocalWords:  localtime MMAP mmap OBSTACK obstack obstacks ARGTYPES timeval
21355 @c  LocalWords:  SETPGRP setpgrp defmacx Hurd SETVBUF setvbuf STRCOLL strcoll
21356 @c  LocalWords:  STRTOD strtod DECL STRFTIME strftime SCO UTIME utime VPRINTF
21357 @c  LocalWords:  DOPRNT vprintf doprnt sp unfixable LIBSOURCE LIBSOURCES Eggert
21358 @c  LocalWords:  linux netinet ia Tru XFree DIRENT NDIR dirent ndir multitable
21359 @c  LocalWords:  NAMLEN strlen namlen MKDEV SYSMACROS makedev RESOLV resolv DNS
21360 @c  LocalWords:  inet structs NAMESER arpa NETDB netdb UTekV UTS GCC's kB
21361 @c  LocalWords:  STDBOOL BOOL stdbool conformant cplusplus bool Bool stdarg tm
21362 @c  LocalWords:  ctype strchr strrchr rindex bcopy memmove memchr WEXITSTATUS
21363 @c  LocalWords:  WIFEXITED TIOCGWINSZ GWINSZ termios preprocess preprocessable
21364 @c  LocalWords:  DECLS strdup calloc BLKSIZE blksize RDEV rdev TZNAME tzname pw
21365 @c  LocalWords:  passwd gecos pwd MBSTATE mbstate wchar RETSIGTYPE hup UID uid
21366 @c  LocalWords:  gid ptrdiff uintmax EXEEXT OBJEXT Ae conftest AXP str
21367 @c  LocalWords:  ALIGNOF WERROR Werror cpp HP's WorkShop egcs un fied stdc CXX
21368 @c  LocalWords:  varargs BIGENDIAN Endianness SPARC endianness grep'ed CONST FC
21369 @c  LocalWords:  const STRINGIZE stringizing PARAMS unprotoize protos KCC cxx
21370 @c  LocalWords:  xlC aCC CXXCPP FREEFORM xlf FLIBS FCLIBS ish SRCEXT XTRA LFS
21371 @c  LocalWords:  ISC lcposix MINIX Minix conditionalized inlines hw dD confdefs
21372 @c  LocalWords:  fputs stdout PREPROC ar UFS HFS QNX realtime fstype STATVFS se
21373 @c  LocalWords:  statvfs STATFS statfs func machfile hdr lelf raboof DEFUN GTK
21374 @c  LocalWords:  GTKMM Grmph ified ine defn baz EOF qar Ahhh changecom algol io
21375 @c  LocalWords:  changeword quadrigraphs quadrigraph dnl SGI atoi overquoting
21376 @c  LocalWords:  Aas Wcross sep args namespace undefine bpatsubst popdef dquote
21377 @c  LocalWords:  bregexp Overquote overquotation meisch maisch meische maische
21378 @c  LocalWords:  miscian DIRNAME dirname MKDIR CATFILE XMKMF TRAVOLTA celsius
21379 @c  LocalWords:  EMX emxos Emacsen Korn DYNIX subshell posix Ksh ksh Pdksh Zsh
21380 @c  LocalWords:  pdksh zsh Allbery Lipe Kubota UWS zorglub stderr eval esac lfn
21381 @c  LocalWords:  drivespec Posixy DJGPP doschk prettybird LPT pfew Zsh's yu yaa
21382 @c  LocalWords:  yM uM aM firebird IP subdir misparses ok Unpatched abc bc zA
21383 @c  LocalWords:  CDPATH DUALCASE LINENO prepass Subshells lineno NULLCMD cmp wc
21384 @c  LocalWords:  MAILPATH scanset arg NetBSD Almquist printf expr cp
21385 @c  LocalWords:  Oliva awk Aaaaarg cmd regex xfoo GNV OpenVMS VM
21386 @c  LocalWords:  sparc Proulx nbar nfoo maxdepth acdilrtu TWG mc
21387 @c  LocalWords:  mkdir exe uname OpenBSD Fileutils mktemp umask TMPDIR guid os
21388 @c  LocalWords:  fooXXXXXX Unicos utimes hpux hppa unescaped
21389 @c  LocalWords:  pmake DOS's gmake ifoo DESTDIR autoconfiscated pc coff mips gg
21390 @c  LocalWords:  dec ultrix cpu wildcards rpcc rdtsc powerpc readline
21391 @c  LocalWords:  withval vxworks gless localcache usr LOFF loff CYGWIN Cygwin
21392 @c  LocalWords:  cygwin SIGLIST siglist SYSNDIR SYSDIR ptx lseq rusage elif MSC
21393 @c  LocalWords:  lfoo POUNDBANG lsun NIS getpwnam SYSCALLS RSH INTL lintl aix
21394 @c  LocalWords:  intl lx ldir syslog bsd EPI toolchain netbsd objext de KNR nn
21395 @c  LocalWords:  fication LTLIBOBJS Wdiff TESTDIR atconfig atlocal akim XFAIL
21396 @c  LocalWords:  ChangeLog prepended errexit smallexample TESTSUITEFLAGS GPL er
21397 @c  LocalWords:  installcheck autotest indir Pixley Bothner Eichin Kerberos adl
21398 @c  LocalWords:  DISTCLEANFILES preprocessor's fileutils Stallman Murphey Stenn
21399 @c  LocalWords:  Manfredi Autoconfig TCL FSP david zuhn Blandy MACRODIR Raeburn
21400 @c  LocalWords:  autoconfiscate Savoye Haertel Avera Meyering fdl appendixsec
21401 @c  LocalWords:  printindex american LIBOBJDIR LibdirTest ERLCFLAGS OBJCFLAGS
21402 @c  LocalWords:  VER Gnulib online xyes strcpy TYPEOF typeof OBJC objcc objc ln
21403 @c  LocalWords:  GOBJC OTP ERLC erl valloc decr dumpdef errprint incr
21404 @c  LocalWords:  esyscmd len maketemp pushdef substr syscmd sysval translit txt
21405 @c  LocalWords:  sinclude foreach myvar tolower toupper uniq BASENAME STDIN
21406 @c  LocalWords:  Dynix descrips basename aname cname macroexpands xno xcheck
21407 @c  LocalWords:  LIBREADLINE lreadline lncurses libreadline
21409 @c Local Variables:
21410 @c fill-column: 72
21411 @c ispell-local-dictionary: "american"
21412 @c indent-tabs-mode: nil
21413 @c whitespace-check-buffer-indent: nil
21414 @c End: