Avoid extra side effects in m4sugar list expansion.
[autoconf.git] / doc / autoconf.texi
blob75c110e559dc3515f1782ad1ea70c561617154c4
1 \input texinfo @c -*-texinfo-*-
2 @comment ========================================================
3 @comment %**start of header
4 @setfilename autoconf.info
5 @include version.texi
6 @settitle Autoconf
7 @setchapternewpage odd
8 @ifnothtml
9 @setcontentsaftertitlepage
10 @end ifnothtml
11 @finalout
13 @c @ovar(ARG)
14 @c ----------
15 @c The ARG is an optional argument.  To be used for macro arguments in
16 @c their documentation (@defmac).
17 @macro ovar{varname}
18 @r{[}@var{\varname\}@r{]}@c
19 @end macro
21 @c @dvar(ARG, DEFAULT)
22 @c -------------------
23 @c The ARG is an optional argument, defaulting to DEFAULT.  To be used
24 @c for macro arguments in their documentation (@defmac).
25 @macro dvar{varname, default}
26 @r{[}@var{\varname\} = @samp{\default\}@r{]}@c
27 @end macro
29 @c Handling the indexes with Texinfo yields several different problems.
31 @c Because we want to drop out the AC_ part of the macro names in the
32 @c printed manual, but not in the other outputs, we need a layer above
33 @c the usual @acindex{} etc.  That's why we first define indexes such as
34 @c acx meant to become the macro @acindex.  First of all, using ``ac_''
35 @c does not work with makeinfo, and using ``ac1'' doesn't work with TeX.
36 @c So use something more regular ``acx''.  Then you finish with a printed
37 @c index saying ``index is not existent''.  Of course: you ought to use
38 @c two letters :(  So you use capitals.
40 @c Second, when defining a macro in the TeX world, following spaces are
41 @c eaten.  But then, since we embed @acxindex commands that use the end
42 @c of line as an end marker, the whole things wrecks itself.  So make
43 @c sure you do *force* an additional end of line, add a ``@c''.
45 @c Finally, you might want to get rid of TeX expansion, using --expand
46 @c with texi2dvi.  But then you wake up an old problem: we use macros
47 @c in @defmac etc. where TeX does perform the expansion, but not makeinfo.
49 @c Define an environment variable index.
50 @defcodeindex ev
51 @c Define an output variable index.
52 @defcodeindex ov
53 @c Define a CPP variable index.
54 @defcodeindex cv
55 @c Define an Autoconf macro index that @defmac doesn't write to.
56 @defcodeindex AC
57 @c Define an Autotest macro index that @defmac doesn't write to.
58 @defcodeindex AT
59 @c Define an M4sugar macro index that @defmac doesn't write to.
60 @defcodeindex MS
61 @c Define an index for *foreign* programs: `mv' etc.  Used for the
62 @c portability sections and so on.
63 @defindex pr
65 @c shortindexflag
66 @c --------------
67 @c Shall we factor AC_ out of the Autoconf macro index etc.?
68 @iftex
69 @set shortindexflag
70 @end iftex
72 @c @acindex{MACRO}
73 @c ---------------
74 @c Registering an AC_\MACRO\.
75 @ifset shortindexflag
76 @macro acindex{macro}
77 @ACindex \macro\
79 @end macro
80 @end ifset
81 @ifclear shortindexflag
82 @macro acindex{macro}
83 @ACindex AC_\macro\
84 @end macro
85 @end ifclear
87 @c @ahindex{MACRO}
88 @c ---------------
89 @c Registering an AH_\MACRO\.
90 @macro ahindex{macro}
91 @ACindex AH_\macro\
93 @end macro
95 @c @asindex{MACRO}
96 @c ---------------
97 @c Registering an AS_\MACRO\.
98 @ifset shortindexflag
99 @macro asindex{macro}
100 @MSindex \macro\
102 @end macro
103 @end ifset
104 @ifclear shortindexflag
105 @macro asindex{macro}
106 @MSindex AS_\macro\
107 @end macro
108 @end ifclear
110 @c @atindex{MACRO}
111 @c ---------------
112 @c Registering an AT_\MACRO\.
113 @ifset shortindexflag
114 @macro atindex{macro}
115 @ATindex \macro\
117 @end macro
118 @end ifset
119 @ifclear shortindexflag
120 @macro atindex{macro}
121 @ATindex AT_\macro\
122 @end macro
123 @end ifclear
125 @c @auindex{MACRO}
126 @c ---------------
127 @c Registering an AU_\MACRO\.
128 @macro auindex{macro}
129 @ACindex AU_\macro\
131 @end macro
133 @c @hdrindex{MACRO}
134 @c ----------------
135 @c Indexing a header.
136 @macro hdrindex{macro}
137 @prindex @file{\macro\}
139 @end macro
141 @c @msindex{MACRO}
142 @c ---------------
143 @c Registering an m4_\MACRO\.
144 @ifset shortindexflag
145 @macro msindex{macro}
146 @MSindex \macro\
148 @end macro
149 @end ifset
150 @ifclear shortindexflag
151 @macro msindex{macro}
152 @MSindex m4_\macro\
153 @end macro
154 @end ifclear
157 @c Define an index for functions: `alloca' etc.  Used for the
158 @c portability sections and so on.  We can't use `fn' (aka `fnindex),
159 @c since `@defmac' goes into it => we'd get all the macros too.
161 @c   FIXME: Aaarg!  It seems there are too many indices for TeX :(
163 @c   ! No room for a new @write .
164 @c   l.112 @defcodeindex fu
166 @c   so don't define yet another one :(  Just put some tags before each
167 @c   @prindex which is actually a @funindex.
169 @c   @defcodeindex fu
172 @c   @c Put the programs and functions into their own index.
173 @c   @syncodeindex fu pr
175 @comment %**end of header
176 @comment ========================================================
178 @copying
180 This manual 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 * Set manipulation Macros::     Set manipulation in M4
460 * Forbidden Patterns::          Catching unexpanded macros
462 Writing Autoconf Macros
464 * Macro Definitions::           Basic format of an Autoconf macro
465 * Macro Names::                 What to call your new macros
466 * Reporting Messages::          Notifying @command{autoconf} users
467 * Dependencies Between Macros::  What to do when macros depend on other macros
468 * Obsoleting Macros::           Warning about old ways of doing things
469 * Coding Style::                Writing Autoconf macros @`a la Autoconf
471 Dependencies Between Macros
473 * Prerequisite Macros::         Ensuring required information
474 * Suggested Ordering::          Warning about possible ordering problems
475 * One-Shot Macros::             Ensuring a macro is called only once
477 Portable Shell Programming
479 * Shellology::                  A zoology of shells
480 * Here-Documents::              Quirks and tricks
481 * File Descriptors::            FDs and redirections
482 * File System Conventions::     File names
483 * Shell Pattern Matching::      Pattern matching
484 * Shell Substitutions::         Variable and command expansions
485 * Assignments::                 Varying side effects of assignments
486 * Parentheses::                 Parentheses in shell scripts
487 * Slashes::                     Slashes in shell scripts
488 * Special Shell Variables::     Variables you should not change
489 * Shell Functions::             What to look out for if you use them
490 * Limitations of Builtins::     Portable use of not so portable /bin/sh
491 * Limitations of Usual Tools::  Portable use of portable tools
493 Portable Make Programming
495 * $< in Ordinary Make Rules::   $< in ordinary rules
496 * Failure in Make Rules::       Failing portably in rules
497 * Special Chars in Names::      Special Characters in Macro Names
498 * Backslash-Newline-Newline::   Empty last lines in macro definitions
499 * Backslash-Newline Comments::  Spanning comments across line boundaries
500 * Long Lines in Makefiles::     Line length limitations
501 * Macros and Submakes::         @code{make macro=value} and submakes
502 * The Make Macro MAKEFLAGS::    @code{$(MAKEFLAGS)} portability issues
503 * The Make Macro SHELL::        @code{$(SHELL)} portability issues
504 * Comments in Make Rules::      Other problems with Make comments
505 * obj/ and Make::               Don't name a subdirectory @file{obj}
506 * make -k Status::              Exit status of @samp{make -k}
507 * VPATH and Make::              @code{VPATH} woes
508 * Single Suffix Rules::         Single suffix rules and separated dependencies
509 * Timestamps and Make::         Subsecond timestamp resolution
511 @code{VPATH} and Make
513 * VPATH and Double-colon::      Problems with @samp{::} on ancient hosts
514 * $< in Explicit Rules::        @code{$<} does not work in ordinary rules
515 * Automatic Rule Rewriting::    @code{VPATH} goes wild on Solaris
516 * Tru64 Directory Magic::       @command{mkdir} goes wild on Tru64
517 * Make Target Lookup::          More details about @code{VPATH} lookup
519 Portable C and C++ Programming
521 * Varieties of Unportability::  How to make your programs unportable
522 * Integer Overflow::            When integers get too large
523 * Preprocessor Arithmetic::     @code{#if} expression problems
524 * Null Pointers::               Properties of null pointers
525 * Buffer Overruns::             Subscript errors and the like
526 * Volatile Objects::            @code{volatile} and signals
527 * Floating Point Portability::  Portable floating-point arithmetic
528 * Exiting Portably::            Exiting and the exit status
530 Manual Configuration
532 * Specifying Names::            Specifying the system type
533 * Canonicalizing::              Getting the canonical system type
534 * Using System Type::           What to do with the system type
536 Site Configuration
538 * Help Formatting::             Customizing @samp{configure --help}
539 * External Software::           Working with other optional software
540 * Package Options::             Selecting optional features
541 * Pretty Help Strings::         Formatting help string
542 * Option Checking::             Controlling checking of @command{configure} options
543 * Site Details::                Configuring site details
544 * Transforming Names::          Changing program names when installing
545 * Site Defaults::               Giving @command{configure} local defaults
547 Transforming Program Names When Installing
549 * Transformation Options::      @command{configure} options to transform names
550 * Transformation Examples::     Sample uses of transforming names
551 * Transformation Rules::        Makefile uses of transforming names
553 Running @command{configure} Scripts
555 * Basic Installation::          Instructions for typical cases
556 * Compilers and Options::       Selecting compilers and optimization
557 * Multiple Architectures::      Compiling for multiple architectures at once
558 * Installation Names::          Installing in different directories
559 * Optional Features::           Selecting optional features
560 * Particular Systems::          Particular systems
561 * System Type::                 Specifying the system type
562 * Sharing Defaults::            Setting site-wide defaults for @command{configure}
563 * Defining Variables::          Specifying the compiler etc.
564 * configure Invocation::        Changing how @command{configure} runs
566 Obsolete Constructs
568 * Obsolete config.status Use::  Obsolete convention for @command{config.status}
569 * acconfig Header::             Additional entries in @file{config.h.in}
570 * autoupdate Invocation::       Automatic update of @file{configure.ac}
571 * Obsolete Macros::             Backward compatibility macros
572 * Autoconf 1::                  Tips for upgrading your files
573 * Autoconf 2.13::               Some fresher tips
575 Upgrading From Version 1
577 * Changed File Names::          Files you might rename
578 * Changed Makefiles::           New things to put in @file{Makefile.in}
579 * Changed Macros::              Macro calls you might replace
580 * Changed Results::             Changes in how to check test results
581 * Changed Macro Writing::       Better ways to write your own macros
583 Upgrading From Version 2.13
585 * Changed Quotation::           Broken code which used to work
586 * New Macros::                  Interaction with foreign macros
587 * Hosts and Cross-Compilation::  Bugward compatibility kludges
588 * AC_LIBOBJ vs LIBOBJS::        LIBOBJS is a forbidden token
589 * AC_FOO_IFELSE vs AC_TRY_FOO::  A more generic scheme for testing sources
591 Generating Test Suites with Autotest
593 * Using an Autotest Test Suite::  Autotest and the user
594 * Writing Testsuites::          Autotest macros
595 * testsuite Invocation::        Running @command{testsuite} scripts
596 * Making testsuite Scripts::    Using autom4te to create @command{testsuite}
598 Using an Autotest Test Suite
600 * testsuite Scripts::           The concepts of Autotest
601 * Autotest Logs::               Their contents
603 Frequent Autoconf Questions, with answers
605 * Distributing::                Distributing @command{configure} scripts
606 * Why GNU M4::                  Why not use the standard M4?
607 * Bootstrapping::               Autoconf and @acronym{GNU} M4 require each other?
608 * Why Not Imake::               Why @acronym{GNU} uses @command{configure} instead of Imake
609 * Defining Directories::        Passing @code{datadir} to program
610 * Autom4te Cache::              What is it?  Can I remove it?
611 * Present But Cannot Be Compiled::  Compiler and Preprocessor Disagree
613 History of Autoconf
615 * Genesis::                     Prehistory and naming of @command{configure}
616 * Exodus::                      The plagues of M4 and Perl
617 * Leviticus::                   The priestly code of portability arrives
618 * Numbers::                     Growth and contributors
619 * Deuteronomy::                 Approaching the promises of easy configuration
621 Indices
623 * Environment Variable Index::  Index of environment variables used
624 * Output Variable Index::       Index of variables set in output files
625 * Preprocessor Symbol Index::   Index of C preprocessor symbols defined
626 * Autoconf Macro Index::        Index of Autoconf macros
627 * M4 Macro Index::              Index of M4, M4sugar, and M4sh macros
628 * Autotest Macro Index::        Index of Autotest macros
629 * Program & Function Index::    Index of those with portability problems
630 * Concept Index::               General index
632 @end detailmenu
633 @end menu
635 @c ============================================================= Introduction.
637 @node Introduction
638 @chapter Introduction
639 @cindex Introduction
641 @flushright
642 A physicist, an engineer, and a computer scientist were discussing the
643 nature of God.  ``Surely a Physicist,'' said the physicist, ``because
644 early in the Creation, God made Light; and you know, Maxwell's
645 equations, the dual nature of electromagnetic waves, the relativistic
646 consequences@dots{}'' ``An Engineer!,'' said the engineer, ``because
647 before making Light, God split the Chaos into Land and Water; it takes a
648 hell of an engineer to handle that big amount of mud, and orderly
649 separation of solids from liquids@dots{}'' The computer scientist
650 shouted: ``And the Chaos, where do you think it was coming from, hmm?''
652 ---Anonymous
653 @end flushright
654 @c (via Franc,ois Pinard)
656 Autoconf is a tool for producing shell scripts that automatically
657 configure software source code packages to adapt to many kinds of
658 Posix-like systems.  The configuration scripts produced by Autoconf
659 are independent of Autoconf when they are run, so their users do not
660 need to have Autoconf.
662 The configuration scripts produced by Autoconf require no manual user
663 intervention when run; they do not normally even need an argument
664 specifying the system type.  Instead, they individually test for the
665 presence of each feature that the software package they are for might need.
666 (Before each check, they print a one-line message stating what they are
667 checking for, so the user doesn't get too bored while waiting for the
668 script to finish.)  As a result, they deal well with systems that are
669 hybrids or customized from the more common Posix variants.  There is
670 no need to maintain files that list the features supported by each
671 release of each variant of Posix.
673 For each software package that Autoconf is used with, it creates a
674 configuration script from a template file that lists the system features
675 that the package needs or can use.  After the shell code to recognize
676 and respond to a system feature has been written, Autoconf allows it to
677 be shared by many software packages that can use (or need) that feature.
678 If it later turns out that the shell code needs adjustment for some
679 reason, it needs to be changed in only one place; all of the
680 configuration scripts can be regenerated automatically to take advantage
681 of the updated code.
683 @c "Those who do not understand Unix are condemned to reinvent it, poorly."
684 @c --Henry Spencer, 1987 (see http://en.wikipedia.org/wiki/Unix_philosophy)
685 Those who do not understand Autoconf are condemned to reinvent it, poorly.
686 The primary goal of Autoconf is making the @emph{user's} life easier;
687 making the @emph{maintainer's} life easier is only a secondary goal.
688 Put another way, the primary goal is not to make the generation of
689 @file{configure} automatic for package maintainers (although patches
690 along that front are welcome, since package maintainers form the user
691 base of Autoconf); rather, the goal is to make @file{configure}
692 painless, portable, and predictable for the end user of each
693 @dfn{autoconfiscated} package.  And to this degree, Autoconf is highly
694 successful at its goal --- most complaints to the Autoconf list are
695 about difficulties in writing Autoconf input, and not in the behavior of
696 the resulting @file{configure}.  Even packages that don't use Autoconf
697 will generally provide a @file{configure} script, and the most common
698 complaint about these alternative home-grown scripts is that they fail
699 to meet one or more of the @acronym{GNU} Coding Standards that users
700 have come to expect from Autoconf-generated @file{configure} scripts.
702 The Metaconfig package is similar in purpose to Autoconf, but the
703 scripts it produces require manual user intervention, which is quite
704 inconvenient when configuring large source trees.  Unlike Metaconfig
705 scripts, Autoconf scripts can support cross-compiling, if some care is
706 taken in writing them.
708 Autoconf does not solve all problems related to making portable
709 software packages---for a more complete solution, it should be used in
710 concert with other @acronym{GNU} build tools like Automake and
711 Libtool.  These other tools take on jobs like the creation of a
712 portable, recursive makefile with all of the standard targets,
713 linking of shared libraries, and so on.  @xref{The GNU Build System},
714 for more information.
716 Autoconf imposes some restrictions on the names of macros used with
717 @code{#if} in C programs (@pxref{Preprocessor Symbol Index}).
719 Autoconf requires @acronym{GNU} M4 version 1.4.5 or later in order to
720 generate the scripts.  It uses features that some versions of M4,
721 including @acronym{GNU} M4 1.3, do not have.  Autoconf works better
722 with @acronym{GNU} M4 version 1.4.11 or later, though this is not
723 required.
725 @xref{Autoconf 1}, for information about upgrading from version 1.
726 @xref{History}, for the story of Autoconf's development.  @xref{FAQ},
727 for answers to some common questions about Autoconf.
729 See the @uref{http://www.gnu.org/software/autoconf/,
730 Autoconf web page} for up-to-date information, details on the mailing
731 lists, pointers to a list of known bugs, etc.
733 Mail suggestions to @email{autoconf@@gnu.org, the Autoconf mailing
734 list}.  Past suggestions are
735 @uref{http://lists.gnu.org/archive/html/autoconf/, archived}.
737 Mail bug reports to @email{bug-autoconf@@gnu.org, the
738 Autoconf Bugs mailing list}.  Past bug reports are
739 @uref{http://lists.gnu.org/archive/html/bug-autoconf/, archived}.
741 If possible, first check that your bug is
742 not already solved in current development versions, and that it has not
743 been reported yet.  Be sure to include all the needed information and a
744 short @file{configure.ac} that demonstrates the problem.
746 Autoconf's development tree is accessible via @command{git}; see the
747 @uref{http://savannah.gnu.org/projects/autoconf/, Autoconf
748 Summary} for details, or view
749 @uref{http://git.sv.gnu.org/gitweb/?p=autoconf.git, the actual
750 repository}.  Anonymous @acronym{CVS} access is also available, see
751 @file{README} for more details.  Patches relative to the
752 current @command{git} version can be sent for review to the
753 @email{autoconf-patches@@gnu.org, Autoconf Patches mailing list}.
754 Discussions on past patches are
755 @uref{http://lists.gnu.org/@/archive/@/html/@/autoconf-patches/,
756 archived}, and all commits are archived in the read-only
757 @email{autoconf-commit@@gnu.org, Autoconf Commit mailing list}, which is
758 also @uref{http://lists.gnu.org/@/archive/@/html/@/autoconf-commit/,
759 archived}.
761 Because of its mission, the Autoconf package itself
762 includes only a set of often-used
763 macros that have already demonstrated their usefulness.  Nevertheless,
764 if you wish to share your macros, or find existing ones, see the
765 @uref{http://autoconf-archive.cryp.to/, Autoconf Macro
766 Archive}, which is kindly run by @email{simons@@cryp.to,
767 Peter Simons}.
770 @c ================================================= The GNU Build System
772 @node The GNU Build System
773 @chapter The @acronym{GNU} Build System
774 @cindex @acronym{GNU} build system
776 Autoconf solves an important problem---reliable discovery of
777 system-specific build and runtime information---but this is only one
778 piece of the puzzle for the development of portable software.  To this
779 end, the @acronym{GNU} project has developed a suite of integrated
780 utilities to finish the job Autoconf started: the @acronym{GNU} build
781 system, whose most important components are Autoconf, Automake, and
782 Libtool.  In this chapter, we introduce you to those tools, point you
783 to sources of more information, and try to convince you to use the
784 entire @acronym{GNU} build system for your software.
786 @menu
787 * Automake::                    Escaping makefile hell
788 * Gnulib::                      The @acronym{GNU} portability library
789 * Libtool::                     Building libraries portably
790 * Pointers::                    More info on the @acronym{GNU} build system
791 @end menu
793 @node Automake
794 @section Automake
796 The ubiquity of @command{make} means that a makefile is almost the
797 only viable way to distribute automatic build rules for software, but
798 one quickly runs into its numerous limitations.  Its lack of
799 support for automatic dependency tracking, recursive builds in
800 subdirectories, reliable timestamps (e.g., for network file systems), and
801 so on, mean that developers must painfully (and often incorrectly)
802 reinvent the wheel for each project.  Portability is non-trivial, thanks
803 to the quirks of @command{make} on many systems.  On top of all this is the
804 manual labor required to implement the many standard targets that users
805 have come to expect (@code{make install}, @code{make distclean},
806 @code{make uninstall}, etc.).  Since you are, of course, using Autoconf,
807 you also have to insert repetitive code in your @file{Makefile.in} to
808 recognize @code{@@CC@@}, @code{@@CFLAGS@@}, and other substitutions
809 provided by @command{configure}.  Into this mess steps @dfn{Automake}.
810 @cindex Automake
812 Automake allows you to specify your build needs in a @file{Makefile.am}
813 file with a vastly simpler and more powerful syntax than that of a plain
814 makefile, and then generates a portable @file{Makefile.in} for
815 use with Autoconf.  For example, the @file{Makefile.am} to build and
816 install a simple ``Hello world'' program might look like:
818 @example
819 bin_PROGRAMS = hello
820 hello_SOURCES = hello.c
821 @end example
823 @noindent
824 The resulting @file{Makefile.in} (~400 lines) automatically supports all
825 the standard targets, the substitutions provided by Autoconf, automatic
826 dependency tracking, @code{VPATH} building, and so on.  @command{make}
827 builds the @code{hello} program, and @code{make install} installs it
828 in @file{/usr/local/bin} (or whatever prefix was given to
829 @command{configure}, if not @file{/usr/local}).
831 The benefits of Automake increase for larger packages (especially ones
832 with subdirectories), but even for small programs the added convenience
833 and portability can be substantial.  And that's not all@enddots{}
835 @node Gnulib
836 @section Gnulib
838 @acronym{GNU} software has a well-deserved reputation for running on
839 many different types of systems.  While our primary goal is to write
840 software for the @acronym{GNU} system, many users and developers have
841 been introduced to us through the systems that they were already using.
843 @cindex Gnulib
844 Gnulib is a central location for common @acronym{GNU} code, intended to
845 be shared among free software packages.  Its components are typically
846 shared at the source level, rather than being a library that gets built,
847 installed, and linked against.  The idea is to copy files from Gnulib
848 into your own source tree.  There is no distribution tarball; developers
849 should just grab source modules from the repository.  The source files
850 are available online, under various licenses, mostly @acronym{GNU}
851 @acronym{GPL} or @acronym{GNU} @acronym{LGPL}.
853 Gnulib modules typically contain C source code along with Autoconf
854 macros used to configure the source code.  For example, the Gnulib
855 @code{stdbool} module implements a @file{stdbool.h} header that nearly
856 conforms to C99, even on old-fashioned hosts that lack @file{stdbool.h}.
857 This module contains a source file for the replacement header, along
858 with an Autoconf macro that arranges to use the replacement header on
859 old-fashioned systems.
861 @node Libtool
862 @section Libtool
864 Often, one wants to build not only programs, but libraries, so that
865 other programs can benefit from the fruits of your labor.  Ideally, one
866 would like to produce @emph{shared} (dynamically linked) libraries,
867 which can be used by multiple programs without duplication on disk or in
868 memory and can be updated independently of the linked programs.
869 Producing shared libraries portably, however, is the stuff of
870 nightmares---each system has its own incompatible tools, compiler flags,
871 and magic incantations.  Fortunately, @acronym{GNU} provides a solution:
872 @dfn{Libtool}.
873 @cindex Libtool
875 Libtool handles all the requirements of building shared libraries for
876 you, and at this time seems to be the @emph{only} way to do so with any
877 portability.  It also handles many other headaches, such as: the
878 interaction of Make rules with the variable suffixes of
879 shared libraries, linking reliably with shared libraries before they are
880 installed by the superuser, and supplying a consistent versioning system
881 (so that different versions of a library can be installed or upgraded
882 without breaking binary compatibility).  Although Libtool, like
883 Autoconf, can be used without Automake, it is most simply utilized in
884 conjunction with Automake---there, Libtool is used automatically
885 whenever shared libraries are needed, and you need not know its syntax.
887 @node Pointers
888 @section Pointers
890 Developers who are used to the simplicity of @command{make} for small
891 projects on a single system might be daunted at the prospect of
892 learning to use Automake and Autoconf.  As your software is
893 distributed to more and more users, however, you otherwise
894 quickly find yourself putting lots of effort into reinventing the
895 services that the @acronym{GNU} build tools provide, and making the
896 same mistakes that they once made and overcame.  (Besides, since
897 you're already learning Autoconf, Automake is a piece of cake.)
899 There are a number of places that you can go to for more information on
900 the @acronym{GNU} build tools.
902 @itemize @minus
904 @item Web
906 The home pages for
907 @uref{http://www.gnu.org/@/software/@/autoconf/, Autoconf},
908 @uref{http://www.gnu.org/@/software/@/automake/, Automake},
909 @uref{http://www.gnu.org/@/software/@/gnulib/, Gnulib}, and
910 @uref{http://www.gnu.org/@/software/@/libtool/, Libtool}.
912 @item Automake Manual
914 @xref{Top, , Automake, automake, @acronym{GNU} Automake}, for more
915 information on Automake.
917 @item Books
919 The book @cite{@acronym{GNU} Autoconf, Automake and
920 Libtool}@footnote{@cite{@acronym{GNU} Autoconf, Automake and Libtool},
921 by G. V. Vaughan, B. Elliston, T. Tromey, and I. L. Taylor.  SAMS (originally
922 New Riders), 2000, ISBN 1578701902.} describes the complete @acronym{GNU}
923 build environment.  You can also find
924 @uref{http://sources.redhat.com/@/autobook/, the entire book on-line}.
926 @end itemize
928 @c ================================================= Making configure Scripts.
930 @node Making configure Scripts
931 @chapter Making @command{configure} Scripts
932 @cindex @file{aclocal.m4}
933 @cindex @command{configure}
935 The configuration scripts that Autoconf produces are by convention
936 called @command{configure}.  When run, @command{configure} creates several
937 files, replacing configuration parameters in them with appropriate
938 values.  The files that @command{configure} creates are:
940 @itemize @minus
941 @item
942 one or more @file{Makefile} files, usually one in each subdirectory of the
943 package (@pxref{Makefile Substitutions});
945 @item
946 optionally, a C header file, the name of which is configurable,
947 containing @code{#define} directives (@pxref{Configuration Headers});
949 @item
950 a shell script called @file{config.status} that, when run, recreates
951 the files listed above (@pxref{config.status Invocation});
953 @item
954 an optional shell script normally called @file{config.cache}
955 (created when using @samp{configure --config-cache}) that
956 saves the results of running many of the tests (@pxref{Cache Files});
958 @item
959 a file called @file{config.log} containing any messages produced by
960 compilers, to help debugging if @command{configure} makes a mistake.
961 @end itemize
963 @cindex @file{configure.in}
964 @cindex @file{configure.ac}
965 To create a @command{configure} script with Autoconf, you need to write an
966 Autoconf input file @file{configure.ac} (or @file{configure.in}) and run
967 @command{autoconf} on it.  If you write your own feature tests to
968 supplement those that come with Autoconf, you might also write files
969 called @file{aclocal.m4} and @file{acsite.m4}.  If you use a C header
970 file to contain @code{#define} directives, you might also run
971 @command{autoheader}, and you can distribute the generated file
972 @file{config.h.in} with the package.
974 Here is a diagram showing how the files that can be used in
975 configuration are produced.  Programs that are executed are suffixed by
976 @samp{*}.  Optional files are enclosed in square brackets (@samp{[]}).
977 @command{autoconf} and @command{autoheader} also read the installed Autoconf
978 macro files (by reading @file{autoconf.m4}).
980 @noindent
981 Files used in preparing a software package for distribution:
982 @example
983 your source files --> [autoscan*] --> [configure.scan] --> configure.ac
985 @group
986 configure.ac --.
987                |   .------> autoconf* -----> configure
988 [aclocal.m4] --+---+
989                |   `-----> [autoheader*] --> [config.h.in]
990 [acsite.m4] ---'
991 @end group
993 Makefile.in -------------------------------> Makefile.in
994 @end example
996 @noindent
997 Files used in configuring a software package:
998 @example
999 @group
1000                        .-------------> [config.cache]
1001 configure* ------------+-------------> config.log
1002                        |
1003 [config.h.in] -.       v            .-> [config.h] -.
1004                +--> config.status* -+               +--> make*
1005 Makefile.in ---'                    `-> Makefile ---'
1006 @end group
1007 @end example
1009 @menu
1010 * Writing Autoconf Input::      What to put in an Autoconf input file
1011 * autoscan Invocation::         Semi-automatic @file{configure.ac} writing
1012 * ifnames Invocation::          Listing the conditionals in source code
1013 * autoconf Invocation::         How to create configuration scripts
1014 * autoreconf Invocation::       Remaking multiple @command{configure} scripts
1015 @end menu
1017 @node Writing Autoconf Input
1018 @section Writing @file{configure.ac}
1020 To produce a @command{configure} script for a software package, create a
1021 file called @file{configure.ac} that contains invocations of the
1022 Autoconf macros that test the system features your package needs or can
1023 use.  Autoconf macros already exist to check for many features; see
1024 @ref{Existing Tests}, for their descriptions.  For most other features,
1025 you can use Autoconf template macros to produce custom checks; see
1026 @ref{Writing Tests}, for information about them.  For especially tricky
1027 or specialized features, @file{configure.ac} might need to contain some
1028 hand-crafted shell commands; see @ref{Portable Shell}.  The
1029 @command{autoscan} program can give you a good start in writing
1030 @file{configure.ac} (@pxref{autoscan Invocation}, for more information).
1032 Previous versions of Autoconf promoted the name @file{configure.in},
1033 which is somewhat ambiguous (the tool needed to process this file is not
1034 described by its extension), and introduces a slight confusion with
1035 @file{config.h.in} and so on (for which @samp{.in} means ``to be
1036 processed by @command{configure}'').  Using @file{configure.ac} is now
1037 preferred.
1039 @menu
1040 * Shell Script Compiler::       Autoconf as solution of a problem
1041 * Autoconf Language::           Programming in Autoconf
1042 * Autoconf Input Layout::       Standard organization of @file{configure.ac}
1043 @end menu
1045 @node Shell Script Compiler
1046 @subsection A Shell Script Compiler
1048 Just as for any other computer language, in order to properly program
1049 @file{configure.ac} in Autoconf you must understand @emph{what} problem
1050 the language tries to address and @emph{how} it does so.
1052 The problem Autoconf addresses is that the world is a mess.  After all,
1053 you are using Autoconf in order to have your package compile easily on
1054 all sorts of different systems, some of them being extremely hostile.
1055 Autoconf itself bears the price for these differences: @command{configure}
1056 must run on all those systems, and thus @command{configure} must limit itself
1057 to their lowest common denominator of features.
1059 Naturally, you might then think of shell scripts; who needs
1060 @command{autoconf}?  A set of properly written shell functions is enough to
1061 make it easy to write @command{configure} scripts by hand.  Sigh!
1062 Unfortunately, shell functions do not belong to the least common
1063 denominator; therefore, where you would like to define a function and
1064 use it ten times, you would instead need to copy its body ten times.
1065 Even in 2007, where shells without any function support are far and
1066 few between, there are pitfalls to avoid when making use of them.
1068 So, what is really needed is some kind of compiler, @command{autoconf},
1069 that takes an Autoconf program, @file{configure.ac}, and transforms it
1070 into a portable shell script, @command{configure}.
1072 How does @command{autoconf} perform this task?
1074 There are two obvious possibilities: creating a brand new language or
1075 extending an existing one.  The former option is attractive: all
1076 sorts of optimizations could easily be implemented in the compiler and
1077 many rigorous checks could be performed on the Autoconf program
1078 (e.g., rejecting any non-portable construct).  Alternatively, you can
1079 extend an existing language, such as the @code{sh} (Bourne shell)
1080 language.
1082 Autoconf does the latter: it is a layer on top of @code{sh}.  It was
1083 therefore most convenient to implement @command{autoconf} as a macro
1084 expander: a program that repeatedly performs @dfn{macro expansions} on
1085 text input, replacing macro calls with macro bodies and producing a pure
1086 @code{sh} script in the end.  Instead of implementing a dedicated
1087 Autoconf macro expander, it is natural to use an existing
1088 general-purpose macro language, such as M4, and implement the extensions
1089 as a set of M4 macros.
1092 @node Autoconf Language
1093 @subsection The Autoconf Language
1094 @cindex quotation
1096 The Autoconf language differs from many other computer
1097 languages because it treats actual code the same as plain text.  Whereas
1098 in C, for instance, data and instructions have different syntactic
1099 status, in Autoconf their status is rigorously the same.  Therefore, we
1100 need a means to distinguish literal strings from text to be expanded:
1101 quotation.
1103 When calling macros that take arguments, there must not be any white
1104 space between the macro name and the open parenthesis.  Arguments should
1105 be enclosed within the M4 quote characters @samp{[} and @samp{]}, and be
1106 separated by commas.  Any leading blanks or newlines in arguments are ignored,
1107 unless they are quoted.  You should always quote an argument that
1108 might contain a macro name, comma, parenthesis, or a leading blank or
1109 newline.  This rule applies recursively for every macro
1110 call, including macros called from other macros.
1112 For instance:
1114 @example
1115 AC_CHECK_HEADER([stdio.h],
1116                 [AC_DEFINE([HAVE_STDIO_H], [1],
1117                    [Define to 1 if you have <stdio.h>.])],
1118                 [AC_MSG_ERROR([Sorry, can't do anything for you])])
1119 @end example
1121 @noindent
1122 is quoted properly.  You may safely simplify its quotation to:
1124 @example
1125 AC_CHECK_HEADER([stdio.h],
1126                 [AC_DEFINE([HAVE_STDIO_H], 1,
1127                    [Define to 1 if you have <stdio.h>.])],
1128                 [AC_MSG_ERROR([Sorry, can't do anything for you])])
1129 @end example
1131 @noindent
1132 because @samp{1} cannot contain a macro call.  Here, the argument of
1133 @code{AC_MSG_ERROR} must be quoted; otherwise, its comma would be
1134 interpreted as an argument separator.  Also, the second and third arguments
1135 of @samp{AC_CHECK_HEADER} must be quoted, since they contain
1136 macro calls.  The three arguments @samp{HAVE_STDIO_H}, @samp{stdio.h},
1137 and @samp{Define to 1 if you have <stdio.h>.} do not need quoting, but
1138 if you unwisely defined a macro with a name like @samp{Define} or
1139 @samp{stdio} then they would need quoting.  Cautious Autoconf users
1140 would keep the quotes, but many Autoconf users find such precautions
1141 annoying, and would rewrite the example as follows:
1143 @example
1144 AC_CHECK_HEADER(stdio.h,
1145                 [AC_DEFINE(HAVE_STDIO_H, 1,
1146                    [Define to 1 if you have <stdio.h>.])],
1147                 [AC_MSG_ERROR([Sorry, can't do anything for you])])
1148 @end example
1150 @noindent
1151 This is safe, so long as you adopt good naming conventions and do not
1152 define macros with names like @samp{HAVE_STDIO_H}, @samp{stdio}, or
1153 @samp{h}.  Though it is also safe here to omit the quotes around
1154 @samp{Define to 1 if you have <stdio.h>.} this is not recommended, as
1155 message strings are more likely to inadvertently contain commas.
1157 The following example is wrong and dangerous, as it is underquoted:
1159 @example
1160 AC_CHECK_HEADER(stdio.h,
1161                 AC_DEFINE(HAVE_STDIO_H, 1,
1162                    Define to 1 if you have <stdio.h>.),
1163                 AC_MSG_ERROR([Sorry, can't do anything for you]))
1164 @end example
1166 In other cases, you may have to use text that also resembles a macro
1167 call.  You must quote that text even when it is not passed as a macro
1168 argument:
1170 @example
1171 echo "Hard rock was here!  --[AC_DC]"
1172 @end example
1174 @noindent
1175 which results in:
1177 @example
1178 echo "Hard rock was here!  --AC_DC"
1179 @end example
1181 @noindent
1182 When you use the same text in a macro argument, you must therefore have
1183 an extra quotation level (since one is stripped away by the macro
1184 substitution).  In general, then, it is a good idea to @emph{use double
1185 quoting for all literal string arguments}:
1187 @example
1188 AC_MSG_WARN([[AC_DC stinks  --Iron Maiden]])
1189 @end example
1191 You are now able to understand one of the constructs of Autoconf that
1192 has been continually misunderstood@dots{}  The rule of thumb is that
1193 @emph{whenever you expect macro expansion, expect quote expansion};
1194 i.e., expect one level of quotes to be lost.  For instance:
1196 @example
1197 AC_COMPILE_IFELSE([char b[10];], [], [AC_MSG_ERROR([you lose])])
1198 @end example
1200 @noindent
1201 is incorrect: here, the first argument of @code{AC_COMPILE_IFELSE} is
1202 @samp{char b[10];} and is expanded once, which results in
1203 @samp{char b10;}.  (There was an idiom common in Autoconf's past to
1204 address this issue via the M4 @code{changequote} primitive, but do not
1205 use it!)  Let's take a closer look: the author meant the first argument
1206 to be understood as a literal, and therefore it must be quoted twice:
1208 @example
1209 AC_COMPILE_IFELSE([[char b[10];]], [], [AC_MSG_ERROR([you lose])])
1210 @end example
1212 @noindent
1213 Voil@`a, you actually produce @samp{char b[10];} this time!
1215 On the other hand, descriptions (e.g., the last parameter of
1216 @code{AC_DEFINE} or @code{AS_HELP_STRING}) are not literals---they
1217 are subject to line breaking, for example---and should not be double quoted.
1218 Even if these descriptions are short and are not actually broken, double
1219 quoting them yields weird results.
1221 Some macros take optional arguments, which this documentation represents
1222 as @ovar{arg} (not to be confused with the quote characters).  You may
1223 just leave them empty, or use @samp{[]} to make the emptiness of the
1224 argument explicit, or you may simply omit the trailing commas.  The
1225 three lines below are equivalent:
1227 @example
1228 AC_CHECK_HEADERS([stdio.h], [], [], [])
1229 AC_CHECK_HEADERS([stdio.h],,,)
1230 AC_CHECK_HEADERS([stdio.h])
1231 @end example
1233 It is best to put each macro call on its own line in
1234 @file{configure.ac}.  Most of the macros don't add extra newlines; they
1235 rely on the newline after the macro call to terminate the commands.
1236 This approach makes the generated @command{configure} script a little
1237 easier to read by not inserting lots of blank lines.  It is generally
1238 safe to set shell variables on the same line as a macro call, because
1239 the shell allows assignments without intervening newlines.
1241 You can include comments in @file{configure.ac} files by starting them
1242 with the @samp{#}.  For example, it is helpful to begin
1243 @file{configure.ac} files with a line like this:
1245 @example
1246 # Process this file with autoconf to produce a configure script.
1247 @end example
1249 @node Autoconf Input Layout
1250 @subsection Standard @file{configure.ac} Layout
1252 The order in which @file{configure.ac} calls the Autoconf macros is not
1253 important, with a few exceptions.  Every @file{configure.ac} must
1254 contain a call to @code{AC_INIT} before the checks, and a call to
1255 @code{AC_OUTPUT} at the end (@pxref{Output}).  Additionally, some macros
1256 rely on other macros having been called first, because they check
1257 previously set values of some variables to decide what to do.  These
1258 macros are noted in the individual descriptions (@pxref{Existing
1259 Tests}), and they also warn you when @command{configure} is created if they
1260 are called out of order.
1262 To encourage consistency, here is a suggested order for calling the
1263 Autoconf macros.  Generally speaking, the things near the end of this
1264 list are those that could depend on things earlier in it.  For example,
1265 library functions could be affected by types and libraries.
1267 @display
1268 @group
1269 Autoconf requirements
1270 @code{AC_INIT(@var{package}, @var{version}, @var{bug-report-address})}
1271 information on the package
1272 checks for programs
1273 checks for libraries
1274 checks for header files
1275 checks for types
1276 checks for structures
1277 checks for compiler characteristics
1278 checks for library functions
1279 checks for system services
1280 @code{AC_CONFIG_FILES(@r{[}@var{file@dots{}}@r{]})}
1281 @code{AC_OUTPUT}
1282 @end group
1283 @end display
1286 @node autoscan Invocation
1287 @section Using @command{autoscan} to Create @file{configure.ac}
1288 @cindex @command{autoscan}
1290 The @command{autoscan} program can help you create and/or maintain a
1291 @file{configure.ac} file for a software package.  @command{autoscan}
1292 examines source files in the directory tree rooted at a directory given
1293 as a command line argument, or the current directory if none is given.
1294 It searches the source files for common portability problems and creates
1295 a file @file{configure.scan} which is a preliminary @file{configure.ac}
1296 for that package, and checks a possibly existing @file{configure.ac} for
1297 completeness.
1299 When using @command{autoscan} to create a @file{configure.ac}, you
1300 should manually examine @file{configure.scan} before renaming it to
1301 @file{configure.ac}; it probably needs some adjustments.
1302 Occasionally, @command{autoscan} outputs a macro in the wrong order
1303 relative to another macro, so that @command{autoconf} produces a warning;
1304 you need to move such macros manually.  Also, if you want the package to
1305 use a configuration header file, you must add a call to
1306 @code{AC_CONFIG_HEADERS} (@pxref{Configuration Headers}).  You might
1307 also have to change or add some @code{#if} directives to your program in
1308 order to make it work with Autoconf (@pxref{ifnames Invocation}, for
1309 information about a program that can help with that job).
1311 When using @command{autoscan} to maintain a @file{configure.ac}, simply
1312 consider adding its suggestions.  The file @file{autoscan.log}
1313 contains detailed information on why a macro is requested.
1315 @command{autoscan} uses several data files (installed along with Autoconf)
1316 to determine which macros to output when it finds particular symbols in
1317 a package's source files.  These data files all have the same format:
1318 each line consists of a symbol, one or more blanks, and the Autoconf macro to
1319 output if that symbol is encountered.  Lines starting with @samp{#} are
1320 comments.
1322 @command{autoscan} accepts the following options:
1324 @table @option
1325 @item --help
1326 @itemx -h
1327 Print a summary of the command line options and exit.
1329 @item --version
1330 @itemx -V
1331 Print the version number of Autoconf and exit.
1333 @item --verbose
1334 @itemx -v
1335 Print the names of the files it examines and the potentially interesting
1336 symbols it finds in them.  This output can be voluminous.
1338 @item --include=@var{dir}
1339 @itemx -I @var{dir}
1340 Append @var{dir} to the include path.  Multiple invocations accumulate.
1342 @item --prepend-include=@var{dir}
1343 @itemx -B @var{dir}
1344 Prepend @var{dir} to the include path.  Multiple invocations accumulate.
1345 @end table
1347 @node ifnames Invocation
1348 @section Using @command{ifnames} to List Conditionals
1349 @cindex @command{ifnames}
1351 @command{ifnames} can help you write @file{configure.ac} for a software
1352 package.  It prints the identifiers that the package already uses in C
1353 preprocessor conditionals.  If a package has already been set up to have
1354 some portability, @command{ifnames} can thus help you figure out what its
1355 @command{configure} needs to check for.  It may help fill in some gaps in a
1356 @file{configure.ac} generated by @command{autoscan} (@pxref{autoscan
1357 Invocation}).
1359 @command{ifnames} scans all of the C source files named on the command line
1360 (or the standard input, if none are given) and writes to the standard
1361 output a sorted list of all the identifiers that appear in those files
1362 in @code{#if}, @code{#elif}, @code{#ifdef}, or @code{#ifndef}
1363 directives.  It prints each identifier on a line, followed by a
1364 space-separated list of the files in which that identifier occurs.
1366 @noindent
1367 @command{ifnames} accepts the following options:
1369 @table @option
1370 @item --help
1371 @itemx -h
1372 Print a summary of the command line options and exit.
1374 @item --version
1375 @itemx -V
1376 Print the version number of Autoconf and exit.
1377 @end table
1379 @node autoconf Invocation
1380 @section Using @command{autoconf} to Create @command{configure}
1381 @cindex @command{autoconf}
1383 To create @command{configure} from @file{configure.ac}, run the
1384 @command{autoconf} program with no arguments.  @command{autoconf} processes
1385 @file{configure.ac} with the M4 macro processor, using the
1386 Autoconf macros.  If you give @command{autoconf} an argument, it reads that
1387 file instead of @file{configure.ac} and writes the configuration script
1388 to the standard output instead of to @command{configure}.  If you give
1389 @command{autoconf} the argument @option{-}, it reads from the standard
1390 input instead of @file{configure.ac} and writes the configuration script
1391 to the standard output.
1393 The Autoconf macros are defined in several files.  Some of the files are
1394 distributed with Autoconf; @command{autoconf} reads them first.  Then it
1395 looks for the optional file @file{acsite.m4} in the directory that
1396 contains the distributed Autoconf macro files, and for the optional file
1397 @file{aclocal.m4} in the current directory.  Those files can contain
1398 your site's or the package's own Autoconf macro definitions
1399 (@pxref{Writing Autoconf Macros}, for more information).  If a macro is
1400 defined in more than one of the files that @command{autoconf} reads, the
1401 last definition it reads overrides the earlier ones.
1403 @command{autoconf} accepts the following options:
1405 @table @option
1406 @item --help
1407 @itemx -h
1408 Print a summary of the command line options and exit.
1410 @item --version
1411 @itemx -V
1412 Print the version number of Autoconf and exit.
1414 @item --verbose
1415 @itemx -v
1416 Report processing steps.
1418 @item --debug
1419 @itemx -d
1420 Don't remove the temporary files.
1422 @item --force
1423 @itemx -f
1424 Remake @file{configure} even if newer than its input files.
1426 @item --include=@var{dir}
1427 @itemx -I @var{dir}
1428 Append @var{dir} to the include path.  Multiple invocations accumulate.
1430 @item --prepend-include=@var{dir}
1431 @itemx -B @var{dir}
1432 Prepend @var{dir} to the include path.  Multiple invocations accumulate.
1434 @item --output=@var{file}
1435 @itemx -o @var{file}
1436 Save output (script or trace) to @var{file}.  The file @option{-} stands
1437 for the standard output.
1439 @item --warnings=@var{category}
1440 @itemx -W @var{category}
1441 @evindex WARNINGS
1442 Report the warnings related to @var{category} (which can actually be a
1443 comma separated list).  @xref{Reporting Messages}, macro
1444 @code{AC_DIAGNOSE}, for a comprehensive list of categories.  Special
1445 values include:
1447 @table @samp
1448 @item all
1449 report all the warnings
1451 @item none
1452 report none
1454 @item error
1455 treats warnings as errors
1457 @item no-@var{category}
1458 disable warnings falling into @var{category}
1459 @end table
1461 Warnings about @samp{syntax} are enabled by default, and the environment
1462 variable @env{WARNINGS}, a comma separated list of categories, is
1463 honored as well.  Passing @option{-W @var{category}} actually behaves as if
1464 you had passed @option{--warnings syntax,$WARNINGS,@var{category}}.  If
1465 you want to disable the defaults and @env{WARNINGS}, but (for example)
1466 enable the warnings about obsolete constructs, you would use @option{-W
1467 none,obsolete}.
1469 @cindex Back trace
1470 @cindex Macro invocation stack
1471 Because @command{autoconf} uses @command{autom4te} behind the scenes, it
1472 displays a back trace for errors, but not for warnings; if you want
1473 them, just pass @option{-W error}.  @xref{autom4te Invocation}, for some
1474 examples.
1476 @item --trace=@var{macro}[:@var{format}]
1477 @itemx -t @var{macro}[:@var{format}]
1478 Do not create the @command{configure} script, but list the calls to
1479 @var{macro} according to the @var{format}.  Multiple @option{--trace}
1480 arguments can be used to list several macros.  Multiple @option{--trace}
1481 arguments for a single macro are not cumulative; instead, you should
1482 just make @var{format} as long as needed.
1484 The @var{format} is a regular string, with newlines if desired, and
1485 several special escape codes.  It defaults to @samp{$f:$l:$n:$%}; see
1486 @ref{autom4te Invocation}, for details on the @var{format}.
1488 @item --initialization
1489 @itemx -i
1490 By default, @option{--trace} does not trace the initialization of the
1491 Autoconf macros (typically the @code{AC_DEFUN} definitions).  This
1492 results in a noticeable speedup, but can be disabled by this option.
1493 @end table
1496 It is often necessary to check the content of a @file{configure.ac}
1497 file, but parsing it yourself is extremely fragile and error-prone.  It
1498 is suggested that you rely upon @option{--trace} to scan
1499 @file{configure.ac}.  For instance, to find the list of variables that
1500 are substituted, use:
1502 @example
1503 @group
1504 $ @kbd{autoconf -t AC_SUBST}
1505 configure.ac:2:AC_SUBST:ECHO_C
1506 configure.ac:2:AC_SUBST:ECHO_N
1507 configure.ac:2:AC_SUBST:ECHO_T
1508 @i{More traces deleted}
1509 @end group
1510 @end example
1512 @noindent
1513 The example below highlights the difference between @samp{$@@},
1514 @samp{$*}, and @samp{$%}.
1516 @example
1517 @group
1518 $ @kbd{cat configure.ac}
1519 AC_DEFINE(This, is, [an
1520 [example]])
1521 $ @kbd{autoconf -t 'AC_DEFINE:@@: $@@}
1522 *: $*
1523 %: $%'
1524 @@: [This],[is],[an
1525 [example]]
1526 *: This,is,an
1527 [example]
1528 %: This:is:an [example]
1529 @end group
1530 @end example
1532 @noindent
1533 The @var{format} gives you a lot of freedom:
1535 @example
1536 @group
1537 $ @kbd{autoconf -t 'AC_SUBST:$$ac_subst@{"$1"@} = "$f:$l";'}
1538 $ac_subst@{"ECHO_C"@} = "configure.ac:2";
1539 $ac_subst@{"ECHO_N"@} = "configure.ac:2";
1540 $ac_subst@{"ECHO_T"@} = "configure.ac:2";
1541 @i{More traces deleted}
1542 @end group
1543 @end example
1545 @noindent
1546 A long @var{separator} can be used to improve the readability of complex
1547 structures, and to ease their parsing (for instance when no single
1548 character is suitable as a separator):
1550 @example
1551 @group
1552 $ @kbd{autoconf -t 'AM_MISSING_PROG:$@{|:::::|@}*'}
1553 ACLOCAL|:::::|aclocal|:::::|$missing_dir
1554 AUTOCONF|:::::|autoconf|:::::|$missing_dir
1555 AUTOMAKE|:::::|automake|:::::|$missing_dir
1556 @i{More traces deleted}
1557 @end group
1558 @end example
1560 @node autoreconf Invocation
1561 @section Using @command{autoreconf} to Update @command{configure} Scripts
1562 @cindex @command{autoreconf}
1564 Installing the various components of the @acronym{GNU} Build System can be
1565 tedious: running @command{autopoint} for Gettext, @command{automake} for
1566 @file{Makefile.in} etc.@: in each directory.  It may be needed either
1567 because some tools such as @command{automake} have been updated on your
1568 system, or because some of the sources such as @file{configure.ac} have
1569 been updated, or finally, simply in order to install the @acronym{GNU} Build
1570 System in a fresh tree.
1572 @command{autoreconf} runs @command{autoconf}, @command{autoheader},
1573 @command{aclocal}, @command{automake}, @command{libtoolize}, and
1574 @command{autopoint} (when appropriate) repeatedly to update the
1575 @acronym{GNU} Build System in the specified directories and their
1576 subdirectories (@pxref{Subdirectories}).  By default, it only remakes
1577 those files that are older than their sources.  The environment variables
1578 @env{AUTOCONF}, @env{AUTOHEADER}, @env{AUTOMAKE}, @env{ACLOCAL},
1579 @env{AUTOPOINT}, @env{LIBTOOLIZE}, @env{M4}, and @env{MAKE} may be used
1580 to override the invocation of the respective tools.
1582 If you install a new version of some tool, you can make
1583 @command{autoreconf} remake @emph{all} of the files by giving it the
1584 @option{--force} option.
1586 @xref{Automatic Remaking}, for Make rules to automatically
1587 rebuild @command{configure} scripts when their source files change.  That
1588 method handles the timestamps of configuration header templates
1589 properly, but does not pass @option{--autoconf-dir=@var{dir}} or
1590 @option{--localdir=@var{dir}}.
1592 @cindex Gettext
1593 @cindex @command{autopoint}
1594 Gettext supplies the @command{autopoint} command to add translation
1595 infrastructure to a source package.  If you use @command{autopoint},
1596 your @file{configure.ac} should invoke both @code{AM_GNU_GETTEXT} and
1597 @code{AM_GNU_GETTEXT_VERSION(@var{gettext-version})}.  @xref{autopoint
1598 Invocation, , Invoking the @code{autopoint} Program, gettext,
1599 @acronym{GNU} @code{gettext} utilities}, for further details.
1601 @noindent
1602 @command{autoreconf} accepts the following options:
1604 @table @option
1605 @item --help
1606 @itemx -h
1607 Print a summary of the command line options and exit.
1609 @item --version
1610 @itemx -V
1611 Print the version number of Autoconf and exit.
1613 @item --verbose
1614 Print the name of each directory @command{autoreconf} examines and the
1615 commands it runs.  If given two or more times, pass @option{--verbose}
1616 to subordinate tools that support it.
1618 @item --debug
1619 @itemx -d
1620 Don't remove the temporary files.
1622 @item --force
1623 @itemx -f
1624 Remake even @file{configure} scripts and configuration headers that are
1625 newer than their input files (@file{configure.ac} and, if present,
1626 @file{aclocal.m4}).
1628 @item --install
1629 @itemx -i
1630 Install the missing auxiliary files in the package.  By default, files
1631 are copied; this can be changed with @option{--symlink}.
1633 If deemed appropriate, this option triggers calls to
1634 @samp{automake --add-missing},
1635 @samp{libtoolize}, @samp{autopoint}, etc.
1637 @item --no-recursive
1638 Do not rebuild files in subdirectories to configure (see @ref{Subdirectories},
1639 macro @code{AC_CONFIG_SUBDIRS}).
1641 @item --symlink
1642 @itemx -s
1643 When used with @option{--install}, install symbolic links to the missing
1644 auxiliary files instead of copying them.
1646 @item --make
1647 @itemx -m
1648 When the directories were configured, update the configuration by
1649 running @samp{./config.status --recheck && ./config.status}, and then
1650 run @samp{make}.
1652 @item --include=@var{dir}
1653 @itemx -I @var{dir}
1654 Append @var{dir} to the include path.  Multiple invocations accumulate.
1655 Passed on to @command{autoconf} and @command{autoheader} internally.
1657 @item --prepend-include=@var{dir}
1658 @itemx -B @var{dir}
1659 Prepend @var{dir} to the include path.  Multiple invocations accumulate.
1660 Passed on to @command{autoconf} and @command{autoheader} internally.
1662 @item --warnings=@var{category}
1663 @itemx -W @var{category}
1664 @evindex WARNINGS
1665 Report the warnings related to @var{category} (which can actually be a
1666 comma separated list).
1668 @table @samp
1669 @item cross
1670 related to cross compilation issues.
1672 @item obsolete
1673 report the uses of obsolete constructs.
1675 @item portability
1676 portability issues
1678 @item syntax
1679 dubious syntactic constructs.
1681 @item all
1682 report all the warnings
1684 @item none
1685 report none
1687 @item error
1688 treats warnings as errors
1690 @item no-@var{category}
1691 disable warnings falling into @var{category}
1692 @end table
1694 Warnings about @samp{syntax} are enabled by default, and the environment
1695 variable @env{WARNINGS}, a comma separated list of categories, is
1696 honored as well.  Passing @option{-W @var{category}} actually behaves as if
1697 you had passed @option{--warnings syntax,$WARNINGS,@var{category}}.  If
1698 you want to disable the defaults and @env{WARNINGS}, but (for example)
1699 enable the warnings about obsolete constructs, you would use @option{-W
1700 none,obsolete}.
1701 @end table
1703 If you want @command{autoreconf} to pass flags that are not listed here
1704 on to @command{aclocal}, set @code{ACLOCAL_AMFLAGS} in your @file{Makefile.am}.
1705 Due to a limitation in the Autoconf implementation these flags currently
1706 must be set on a single line in @file{Makefile.am}, without any
1707 backslash-newlines.
1709 @c ========================================= Initialization and Output Files.
1711 @node Setup
1712 @chapter Initialization and Output Files
1714 Autoconf-generated @command{configure} scripts need some information about
1715 how to initialize, such as how to find the package's source files and
1716 about the output files to produce.  The following sections describe the
1717 initialization and the creation of output files.
1719 @menu
1720 * Initializing configure::      Option processing etc.
1721 * Versioning::                  Dealing with Autoconf versions
1722 * Notices::                     Copyright, version numbers in @command{configure}
1723 * Input::                       Where Autoconf should find files
1724 * Output::                      Outputting results from the configuration
1725 * Configuration Actions::       Preparing the output based on results
1726 * Configuration Files::         Creating output files
1727 * Makefile Substitutions::      Using output variables in makefiles
1728 * Configuration Headers::       Creating a configuration header file
1729 * Configuration Commands::      Running arbitrary instantiation commands
1730 * Configuration Links::         Links depending on the configuration
1731 * Subdirectories::              Configuring independent packages together
1732 * Default Prefix::              Changing the default installation prefix
1733 @end menu
1735 @node Initializing configure
1736 @section Initializing @command{configure}
1738 Every @command{configure} script must call @code{AC_INIT} before doing
1739 anything else.  The only other required macro is @code{AC_OUTPUT}
1740 (@pxref{Output}).
1742 @anchor{AC_INIT}
1743 @defmac AC_INIT (@var{package}, @var{version}, @ovar{bug-report}, @
1744   @ovar{tarname})
1745 @acindex{INIT}
1746 Process any command-line arguments and perform various initializations
1747 and verifications.
1749 Set the name of the @var{package} and its @var{version}.  These are
1750 typically used in @option{--version} support, including that of
1751 @command{configure}.  The optional argument @var{bug-report} should be
1752 the email to which users should send bug reports.  The package
1753 @var{tarname} differs from @var{package}: the latter designates the full
1754 package name (e.g., @samp{GNU Autoconf}), while the former is meant for
1755 distribution tar ball names (e.g., @samp{autoconf}).  It defaults to
1756 @var{package} with @samp{GNU } stripped, lower-cased, and all characters
1757 other than alphanumerics and underscores are changed to @samp{-}.
1759 It is preferable that the arguments of @code{AC_INIT} be static, i.e.,
1760 there should not be any shell computation, but they can be computed by
1763 The following M4 macros (e.g., @code{AC_PACKAGE_NAME}), output variables
1764 (e.g., @code{PACKAGE_NAME}), and preprocessor symbols (e.g.,
1765 @code{PACKAGE_NAME}), are defined by @code{AC_INIT}:
1767 @table @asis
1768 @item @code{AC_PACKAGE_NAME}, @code{PACKAGE_NAME}
1769 @acindex{PACKAGE_NAME}
1770 @ovindex PACKAGE_NAME
1771 @cvindex PACKAGE_NAME
1772 Exactly @var{package}.
1774 @item @code{AC_PACKAGE_TARNAME}, @code{PACKAGE_TARNAME}
1775 @acindex{PACKAGE_TARNAME}
1776 @ovindex PACKAGE_TARNAME
1777 @cvindex PACKAGE_TARNAME
1778 Exactly @var{tarname}.
1780 @item @code{AC_PACKAGE_VERSION}, @code{PACKAGE_VERSION}
1781 @acindex{PACKAGE_VERSION}
1782 @ovindex PACKAGE_VERSION
1783 @cvindex PACKAGE_VERSION
1784 Exactly @var{version}.
1786 @item @code{AC_PACKAGE_STRING}, @code{PACKAGE_STRING}
1787 @acindex{PACKAGE_STRING}
1788 @ovindex PACKAGE_STRING
1789 @cvindex PACKAGE_STRING
1790 Exactly @samp{@var{package} @var{version}}.
1792 @item @code{AC_PACKAGE_BUGREPORT}, @code{PACKAGE_BUGREPORT}
1793 @acindex{PACKAGE_BUGREPORT}
1794 @ovindex PACKAGE_BUGREPORT
1795 @cvindex PACKAGE_BUGREPORT
1796 Exactly @var{bug-report}.
1797 @end table
1798 @end defmac
1800 If your @command{configure} script does its own option processing, it
1801 should inspect @samp{$@@} or @samp{$*} immediately after calling
1802 @code{AC_INIT}, because other Autoconf macros liberally use the
1803 @command{set} command to process strings, and this has the side effect
1804 of updating @samp{$@@} and @samp{$*}.  However, we suggest that you use
1805 standard macros like @code{AC_ARG_ENABLE} instead of attempting to
1806 implement your own option processing.  @xref{Site Configuration}.
1808 @node Versioning
1809 @section Dealing with Autoconf versions
1810 @cindex Autoconf version
1811 @cindex version, Autoconf
1813 The following optional macros can be used to help choose the minimum
1814 version of Autoconf that can successfully compile a given
1815 @file{configure.ac}.
1817 @defmac AC_PREREQ (@var{version})
1818 @acindex{PREREQ}
1819 @cindex Version
1820 Ensure that a recent enough version of Autoconf is being used.  If the
1821 version of Autoconf being used to create @command{configure} is
1822 earlier than @var{version}, print an error message to the standard
1823 error output and exit with failure (exit status is 63).  For example:
1825 @example
1826 AC_PREREQ([@value{VERSION}])
1827 @end example
1829 This macro is the only macro that may be used before @code{AC_INIT}, but
1830 for consistency, you are invited not to do so.
1831 @end defmac
1833 @defmac AC_AUTOCONF_VERSION
1834 @acindex{AUTOCONF_VERSION}
1835 This macro was introduced in Autoconf 2.62.  It identifies the version
1836 of Autoconf that is currently parsing the input file, in a format
1837 suitable for @code{m4_version_compare} (@pxref{m4_version_compare}); in
1838 other words, for this release of Autoconf, its value is
1839 @samp{@value{VERSION}}.  One potential use of this macro is for writing
1840 conditional fallbacks based on when a feature was added to Autoconf,
1841 rather than using @code{AC_PREREQ} to require the newer version of
1842 Autoconf.  However, remember that the Autoconf philosophy favors feature
1843 checks over version checks.
1845 You should not expand this macro directly; use
1846 @samp{m4_defn([AC_AUTOCONF_VERSION])} instead.  This is because some
1847 users might
1848 have a beta version of Autoconf installed, with arbitrary letters
1849 included in its version string.  This means it is possible for the
1850 version string to contain the name of a defined macro, such that
1851 expanding @code{AC_AUTOCONF_VERSION} would trigger the expansion of that
1852 macro during rescanning, and change the version string to be different
1853 than what you intended to check.
1854 @end defmac
1856 @node Notices
1857 @section Notices in @command{configure}
1858 @cindex Notices in @command{configure}
1860 The following macros manage version numbers for @command{configure}
1861 scripts.  Using them is optional.
1863 @defmac AC_COPYRIGHT (@var{copyright-notice})
1864 @acindex{COPYRIGHT}
1865 @cindex Copyright Notice
1866 State that, in addition to the Free Software Foundation's copyright on
1867 the Autoconf macros, parts of your @command{configure} are covered by the
1868 @var{copyright-notice}.
1870 The @var{copyright-notice} shows up in both the head of
1871 @command{configure} and in @samp{configure --version}.
1872 @end defmac
1875 @defmac AC_REVISION (@var{revision-info})
1876 @acindex{REVISION}
1877 @cindex Revision
1878 Copy revision stamp @var{revision-info} into the @command{configure}
1879 script, with any dollar signs or double-quotes removed.  This macro lets
1880 you put a revision stamp from @file{configure.ac} into @command{configure}
1881 without @acronym{RCS} or @acronym{CVS} changing it when you check in
1882 @command{configure}.  That way, you can determine easily which revision of
1883 @file{configure.ac} a particular @command{configure} corresponds to.
1885 For example, this line in @file{configure.ac}:
1887 @c The @w prevents RCS from changing the example in the manual.
1888 @example
1889 AC_REVISION([@w{$}Revision: 1.30 $])
1890 @end example
1892 @noindent
1893 produces this in @command{configure}:
1895 @example
1896 #!/bin/sh
1897 # From configure.ac Revision: 1.30
1898 @end example
1899 @end defmac
1902 @node Input
1903 @section Finding @command{configure} Input
1905 @anchor{AC_CONFIG_SRCDIR}
1906 @defmac AC_CONFIG_SRCDIR (@var{unique-file-in-source-dir})
1907 @acindex{CONFIG_SRCDIR}
1908 @var{unique-file-in-source-dir} is some file that is in the package's
1909 source directory; @command{configure} checks for this file's existence to
1910 make sure that the directory that it is told contains the source code in
1911 fact does.  Occasionally people accidentally specify the wrong directory
1912 with @option{--srcdir}; this is a safety check.  @xref{configure
1913 Invocation}, for more information.
1914 @end defmac
1917 @c FIXME: Remove definitively once --install explained.
1919 @c Small packages may store all their macros in @code{aclocal.m4}.  As the
1920 @c set of macros grows, or for maintenance reasons, a maintainer may prefer
1921 @c to split the macros in several files.  In this case, Autoconf must be
1922 @c told which files to load, and in which order.
1924 @c @defmac AC_INCLUDE (@var{file}@dots{})
1925 @c @acindex{INCLUDE}
1926 @c @c FIXME: There is no longer shell globbing.
1927 @c Read the macro definitions that appear in the listed files.  A list of
1928 @c space-separated file names or shell globbing patterns is expected.  The
1929 @c files are read in the order they're listed.
1931 @c Because the order of definition of macros is important (only the last
1932 @c definition of a macro is used), beware that it is @code{AC_INIT} that
1933 @c loads @file{acsite.m4} and @file{aclocal.m4}.  Note that
1934 @c @code{AC_INCLUDE}ing a file before @code{AC_INIT} or within
1935 @c @file{aclocal.m4} is different from doing so after @code{AC_INIT}: in
1936 @c the latter case, non-macro lines from included files may end up in the
1937 @c @file{configure} script, whereas in the former case, they'd be discarded
1938 @c just like any text that appear before @code{AC_INIT}.
1939 @c @end defmac
1941 Packages that do manual configuration or use the @command{install} program
1942 might need to tell @command{configure} where to find some other shell
1943 scripts by calling @code{AC_CONFIG_AUX_DIR}, though the default places
1944 it looks are correct for most cases.
1946 @defmac AC_CONFIG_AUX_DIR (@var{dir})
1947 @acindex{CONFIG_AUX_DIR}
1948 Use the auxiliary build tools (e.g., @file{install-sh},
1949 @file{config.sub}, @file{config.guess}, Cygnus @command{configure},
1950 Automake and Libtool scripts, etc.)@: that are in directory @var{dir}.
1951 These are auxiliary files used in configuration.  @var{dir} can be
1952 either absolute or relative to @file{@var{srcdir}}.  The default is
1953 @file{@var{srcdir}} or @file{@var{srcdir}/..} or
1954 @file{@var{srcdir}/../..}, whichever is the first that contains
1955 @file{install-sh}.  The other files are not checked for, so that using
1956 @code{AC_PROG_INSTALL} does not automatically require distributing the
1957 other auxiliary files.  It checks for @file{install.sh} also, but that
1958 name is obsolete because some @command{make} have a rule that creates
1959 @file{install} from it if there is no makefile.
1961 The auxiliary directory is commonly named @file{build-aux}.
1962 If you need portability to @acronym{DOS} variants, do not name the
1963 auxiliary directory @file{aux}.  @xref{File System Conventions}.
1964 @end defmac
1966 @defmac AC_REQUIRE_AUX_FILE (@var{file})
1967 @acindex{REQUIRE_AUX_FILE}
1968 Declares that @var{file} is expected in the directory defined above.  In
1969 Autoconf proper, this macro does nothing: its sole purpose is to be
1970 traced by third-party tools to produce a list of expected auxiliary
1971 files.  For instance it is called by macros like @code{AC_PROG_INSTALL}
1972 (@pxref{Particular Programs}) or @code{AC_CANONICAL_BUILD}
1973 (@pxref{Canonicalizing}) to register the auxiliary files they need.
1974 @end defmac
1976 Similarly, packages that use @command{aclocal} should declare where
1977 local macros can be found using @code{AC_CONFIG_MACRO_DIR}.
1979 @defmac AC_CONFIG_MACRO_DIR (@var{dir})
1980 @acindex{CONFIG_MACRO_DIR}
1981 Specify @var{dir} as the location of additional local Autoconf macros.
1982 This macro is intended for use by future versions of commands like
1983 @command{autoreconf} that trace macro calls.  It should be called
1984 directly from @file{configure.ac} so that tools that install macros for
1985 @command{aclocal} can find the macros' declarations.
1987 Note that if you use @command{aclocal} from Automake to generate
1988 @file{aclocal.m4}, you must also set @code{ACLOCAL_AMFLAGS = -I
1989 @var{dir}} in your top-level @file{Makefile.am}.  Due to a limitation in
1990 the Autoconf implementation of @command{autoreconf}, these include
1991 directives currently must be set on a single line in @file{Makefile.am},
1992 without any backslash-newlines.
1993 @end defmac
1996 @node Output
1997 @section Outputting Files
1998 @cindex Outputting files
2000 Every Autoconf script, e.g., @file{configure.ac}, should finish by
2001 calling @code{AC_OUTPUT}.  That is the macro that generates and runs
2002 @file{config.status}, which in turn creates the makefiles and any
2003 other files resulting from configuration.  This is the only required
2004 macro besides @code{AC_INIT} (@pxref{Input}).
2006 @anchor{AC_OUTPUT}
2007 @defmac AC_OUTPUT
2008 @acindex{OUTPUT}
2009 @cindex Instantiation
2010 Generate @file{config.status} and launch it.  Call this macro once, at
2011 the end of @file{configure.ac}.
2013 @file{config.status} performs all the configuration actions: all the
2014 output files (see @ref{Configuration Files}, macro
2015 @code{AC_CONFIG_FILES}), header files (see @ref{Configuration Headers},
2016 macro @code{AC_CONFIG_HEADERS}), commands (see @ref{Configuration
2017 Commands}, macro @code{AC_CONFIG_COMMANDS}), links (see
2018 @ref{Configuration Links}, macro @code{AC_CONFIG_LINKS}), subdirectories
2019 to configure (see @ref{Subdirectories}, macro @code{AC_CONFIG_SUBDIRS})
2020 are honored.
2022 The location of your @code{AC_OUTPUT} invocation is the exact point
2023 where configuration actions are taken: any code afterwards is
2024 executed by @command{configure} once @command{config.status} was run.  If
2025 you want to bind actions to @command{config.status} itself
2026 (independently of whether @command{configure} is being run), see
2027 @ref{Configuration Commands, , Running Arbitrary Configuration
2028 Commands}.
2029 @end defmac
2031 Historically, the usage of @code{AC_OUTPUT} was somewhat different.
2032 @xref{Obsolete Macros}, for a description of the arguments that
2033 @code{AC_OUTPUT} used to support.
2036 If you run @command{make} in subdirectories, you should run it using the
2037 @command{make} variable @code{MAKE}.  Most versions of @command{make} set
2038 @code{MAKE} to the name of the @command{make} program plus any options it
2039 was given.  (But many do not include in it the values of any variables
2040 set on the command line, so those are not passed on automatically.)
2041 Some old versions of @command{make} do not set this variable.  The
2042 following macro allows you to use it even with those versions.
2044 @anchor{AC_PROG_MAKE_SET}
2045 @defmac AC_PROG_MAKE_SET
2046 @acindex{PROG_MAKE_SET}
2047 @ovindex SET_MAKE
2048 If the Make command, @code{$MAKE} if set or else @samp{make}, predefines
2049 @code{$(MAKE)}, define output variable @code{SET_MAKE} to be empty.
2050 Otherwise, define @code{SET_MAKE} to a macro definition that sets
2051 @code{$(MAKE)}, such as @samp{MAKE=make}.  Calls @code{AC_SUBST} for
2052 @code{SET_MAKE}.
2053 @end defmac
2055 If you use this macro, place a line like this in each @file{Makefile.in}
2056 that runs @command{MAKE} on other directories:
2058 @example
2059 @@SET_MAKE@@
2060 @end example
2064 @node Configuration Actions
2065 @section Performing Configuration Actions
2066 @cindex Configuration actions
2068 @file{configure} is designed so that it appears to do everything itself,
2069 but there is actually a hidden slave: @file{config.status}.
2070 @file{configure} is in charge of examining your system, but it is
2071 @file{config.status} that actually takes the proper actions based on the
2072 results of @file{configure}.  The most typical task of
2073 @file{config.status} is to @emph{instantiate} files.
2075 This section describes the common behavior of the four standard
2076 instantiating macros: @code{AC_CONFIG_FILES}, @code{AC_CONFIG_HEADERS},
2077 @code{AC_CONFIG_COMMANDS} and @code{AC_CONFIG_LINKS}.  They all
2078 have this prototype:
2080 @c FIXME: Can't use @ovar here, Texinfo 4.0 goes lunatic and emits something
2081 @c awful.
2082 @example
2083 AC_CONFIG_FOOS(@var{tag}@dots{}, [@var{commands}], [@var{init-cmds}])
2084 @end example
2086 @noindent
2087 where the arguments are:
2089 @table @var
2090 @item tag@dots{}
2091 A blank-or-newline-separated list of tags, which are typically the names of
2092 the files to instantiate.
2094 You are encouraged to use literals as @var{tags}.  In particular, you
2095 should avoid
2097 @example
2098 @dots{} && my_foos="$my_foos fooo"
2099 @dots{} && my_foos="$my_foos foooo"
2100 AC_CONFIG_FOOS([$my_foos])
2101 @end example
2103 @noindent
2104 and use this instead:
2106 @example
2107 @dots{} && AC_CONFIG_FOOS([fooo])
2108 @dots{} && AC_CONFIG_FOOS([foooo])
2109 @end example
2111 The macros @code{AC_CONFIG_FILES} and @code{AC_CONFIG_HEADERS} use
2112 special @var{tag} values: they may have the form @samp{@var{output}} or
2113 @samp{@var{output}:@var{inputs}}.  The file @var{output} is instantiated
2114 from its templates, @var{inputs} (defaulting to @samp{@var{output}.in}).
2116 @samp{AC_CONFIG_FILES([Makefile:boiler/top.mk:boiler/bot.mk)]},
2117 for example, asks for
2118 the creation of the file @file{Makefile} that contains the expansion of the
2119 output variables in the concatenation of @file{boiler/top.mk} and
2120 @file{boiler/bot.mk}.
2122 The special value @samp{-} might be used to denote the standard output
2123 when used in @var{output}, or the standard input when used in the
2124 @var{inputs}.  You most probably don't need to use this in
2125 @file{configure.ac}, but it is convenient when using the command line
2126 interface of @file{./config.status}, see @ref{config.status Invocation},
2127 for more details.
2129 The @var{inputs} may be absolute or relative file names.  In the latter
2130 case they are first looked for in the build tree, and then in the source
2131 tree.
2133 @item commands
2134 Shell commands output literally into @file{config.status}, and
2135 associated with a tag that the user can use to tell @file{config.status}
2136 which the commands to run.  The commands are run each time a @var{tag}
2137 request is given to @file{config.status}, typically each time the file
2138 @file{@var{tag}} is created.
2140 The variables set during the execution of @command{configure} are
2141 @emph{not} available here: you first need to set them via the
2142 @var{init-cmds}.  Nonetheless the following variables are precomputed:
2144 @table @code
2145 @item srcdir
2146 The name of the top source directory, assuming that the working
2147 directory is the top build directory.  This
2148 is what the @command{configure} option @option{--srcdir} sets.
2150 @item ac_top_srcdir
2151 The name of the top source directory, assuming that the working
2152 directory is the current build directory.
2155 @item ac_top_build_prefix
2156 The name of the top build directory, assuming that the working
2157 directory is the current build directory.
2158 It can be empty, or else ends with a slash, so that you may concatenate
2161 @item ac_srcdir
2162 The name of the corresponding source directory, assuming that the
2163 working directory is the current build directory.
2164 @end table
2166 @noindent
2167 The @dfn{current} directory refers to the directory (or
2168 pseudo-directory) containing the input part of @var{tags}.  For
2169 instance, running
2171 @example
2172 AC_CONFIG_COMMANDS([deep/dir/out:in/in.in], [@dots{}], [@dots{}])
2173 @end example
2175 @noindent
2176  with @option{--srcdir=../package} produces the following values:
2178 @example
2179 # Argument of --srcdir
2180 srcdir='../package'
2181 # Reversing deep/dir
2182 ac_top_build_prefix='../../'
2183 # Concatenation of $ac_top_build_prefix and srcdir
2184 ac_top_srcdir='../../../package'
2185 # Concatenation of $ac_top_srcdir and deep/dir
2186 ac_srcdir='../../../package/deep/dir'
2187 @end example
2189 @noindent
2190 independently of @samp{in/in.in}.
2192 @item init-cmds
2193 Shell commands output @emph{unquoted} near the beginning of
2194 @file{config.status}, and executed each time @file{config.status} runs
2195 (regardless of the tag).  Because they are unquoted, for example,
2196 @samp{$var} is output as the value of @code{var}.  @var{init-cmds}
2197 is typically used by @file{configure} to give @file{config.status} some
2198 variables it needs to run the @var{commands}.
2200 You should be extremely cautious in your variable names: all the
2201 @var{init-cmds} share the same name space and may overwrite each other
2202 in unpredictable ways.  Sorry@enddots{}
2203 @end table
2205 All these macros can be called multiple times, with different
2206 @var{tag} values, of course!
2209 @node Configuration Files
2210 @section Creating Configuration Files
2211 @cindex Creating configuration files
2212 @cindex Configuration file creation
2214 Be sure to read the previous section, @ref{Configuration Actions}.
2216 @anchor{AC_CONFIG_FILES}
2217 @defmac AC_CONFIG_FILES (@var{file}@dots{}, @ovar{cmds}, @ovar{init-cmds})
2218 @acindex{CONFIG_FILES}
2219 Make @code{AC_OUTPUT} create each @file{@var{file}} by copying an input
2220 file (by default @file{@var{file}.in}), substituting the output variable
2221 values.
2222 @c Before we used to have this feature, which was later rejected
2223 @c because it complicates the writing of makefiles:
2224 @c If the file would be unchanged, it is left untouched, to preserve
2225 @c timestamp.
2226 This macro is one of the instantiating macros; see @ref{Configuration
2227 Actions}.  @xref{Makefile Substitutions}, for more information on using
2228 output variables.  @xref{Setting Output Variables}, for more information
2229 on creating them.  This macro creates the directory that the file is in
2230 if it doesn't exist.  Usually, makefiles are created this way,
2231 but other files, such as @file{.gdbinit}, can be specified as well.
2233 Typical calls to @code{AC_CONFIG_FILES} look like this:
2235 @example
2236 AC_CONFIG_FILES([Makefile src/Makefile man/Makefile X/Imakefile])
2237 AC_CONFIG_FILES([autoconf], [chmod +x autoconf])
2238 @end example
2240 You can override an input file name by appending to @var{file} a
2241 colon-separated list of input files.  Examples:
2243 @example
2244 AC_CONFIG_FILES([Makefile:boiler/top.mk:boiler/bot.mk]
2245                 [lib/Makefile:boiler/lib.mk])
2246 @end example
2248 @noindent
2249 Doing this allows you to keep your file names acceptable to
2250 @acronym{DOS} variants, or
2251 to prepend and/or append boilerplate to the file.
2252 @end defmac
2256 @node Makefile Substitutions
2257 @section Substitutions in Makefiles
2258 @cindex Substitutions in makefiles
2259 @cindex Makefile substitutions
2261 Each subdirectory in a distribution that contains something to be
2262 compiled or installed should come with a file @file{Makefile.in}, from
2263 which @command{configure} creates a file @file{Makefile} in that directory.
2264 To create @file{Makefile}, @command{configure} performs a simple variable
2265 substitution, replacing occurrences of @samp{@@@var{variable}@@} in
2266 @file{Makefile.in} with the value that @command{configure} has determined
2267 for that variable.  Variables that are substituted into output files in
2268 this way are called @dfn{output variables}.  They are ordinary shell
2269 variables that are set in @command{configure}.  To make @command{configure}
2270 substitute a particular variable into the output files, the macro
2271 @code{AC_SUBST} must be called with that variable name as an argument.
2272 Any occurrences of @samp{@@@var{variable}@@} for other variables are
2273 left unchanged.  @xref{Setting Output Variables}, for more information
2274 on creating output variables with @code{AC_SUBST}.
2276 A software package that uses a @command{configure} script should be
2277 distributed with a file @file{Makefile.in}, but no makefile; that
2278 way, the user has to properly configure the package for the local system
2279 before compiling it.
2281 @xref{Makefile Conventions, , Makefile Conventions, standards, The
2282 @acronym{GNU} Coding Standards}, for more information on what to put in
2283 makefiles.
2285 @menu
2286 * Preset Output Variables::     Output variables that are always set
2287 * Installation Directory Variables::  Other preset output variables
2288 * Changed Directory Variables:: Warnings about @file{datarootdir}
2289 * Build Directories::           Supporting multiple concurrent compiles
2290 * Automatic Remaking::          Makefile rules for configuring
2291 @end menu
2293 @node Preset Output Variables
2294 @subsection Preset Output Variables
2295 @cindex Output variables
2297 Some output variables are preset by the Autoconf macros.  Some of the
2298 Autoconf macros set additional output variables, which are mentioned in
2299 the descriptions for those macros.  @xref{Output Variable Index}, for a
2300 complete list of output variables.  @xref{Installation Directory
2301 Variables}, for the list of the preset ones related to installation
2302 directories.  Below are listed the other preset ones.  They all are
2303 precious variables (@pxref{Setting Output Variables},
2304 @code{AC_ARG_VAR}).
2306 @c Just say no to ASCII sorting!  We're humans, not computers.
2307 @c These variables are listed as they would be in a dictionary:
2308 @c actor
2309 @c Actress
2310 @c actress
2312 @defvar CFLAGS
2313 @ovindex CFLAGS
2314 Debugging and optimization options for the C compiler.  If it is not set
2315 in the environment when @command{configure} runs, the default value is set
2316 when you call @code{AC_PROG_CC} (or empty if you don't).  @command{configure}
2317 uses this variable when compiling or linking programs to test for C features.
2319 If a compiler option affects only the behavior of the preprocessor
2320 (e.g., @option{-D @var{name}}), it should be put into @code{CPPFLAGS}
2321 instead.  If it affects only the linker (e.g., @option{-L
2322 @var{directory}}), it should be put into @code{LDFLAGS} instead.  If it
2323 affects only the compiler proper, @code{CFLAGS} is the natural home for
2324 it.  If an option affects multiple phases of the compiler, though,
2325 matters get tricky.  One approach to put such options directly into
2326 @code{CC}, e.g., @code{CC='gcc -m64'}.  Another is to put them into both
2327 @code{CPPFLAGS} and @code{LDFLAGS}, but not into @code{CFLAGS}.
2329 @end defvar
2331 @defvar configure_input
2332 @ovindex configure_input
2333 A comment saying that the file was generated automatically by
2334 @command{configure} and giving the name of the input file.
2335 @code{AC_OUTPUT} adds a comment line containing this variable to the top
2336 of every makefile it creates.  For other files, you should
2337 reference this variable in a comment at the top of each input file.  For
2338 example, an input shell script should begin like this:
2340 @example
2341 #!/bin/sh
2342 # @@configure_input@@
2343 @end example
2345 @noindent
2346 The presence of that line also reminds people editing the file that it
2347 needs to be processed by @command{configure} in order to be used.
2348 @end defvar
2350 @defvar CPPFLAGS
2351 @ovindex CPPFLAGS
2352 Preprocessor options for the C, C++, and Objective C preprocessors and
2353 compilers.  If
2354 it is not set in the environment when @command{configure} runs, the default
2355 value is empty.  @command{configure} uses this variable when preprocessing
2356 or compiling programs to test for C, C++, and Objective C features.
2358 This variable's contents should contain options like @option{-I},
2359 @option{-D}, and @option{-U} that affect only the behavior of the
2360 preprocessor.  Please see the explanation of @code{CFLAGS} for what you
2361 can do if an option affects other phases of the compiler as well.
2363 Currently, @command{configure} always links as part of a single
2364 invocation of the compiler that also preprocesses and compiles, so it
2365 uses this variable also when linking programs.  However, it is unwise to
2366 depend on this behavior because the @acronym{GNU} coding standards do
2367 not require it and many packages do not use @code{CPPFLAGS} when linking
2368 programs.
2370 @xref{Special Chars in Variables}, for limitations that @code{CPPFLAGS}
2371 might run into.
2372 @end defvar
2374 @defvar CXXFLAGS
2375 @ovindex CXXFLAGS
2376 Debugging and optimization options for the C++ compiler.  It acts like
2377 @code{CFLAGS}, but for C++ instead of C.
2378 @end defvar
2380 @defvar DEFS
2381 @ovindex DEFS
2382 @option{-D} options to pass to the C compiler.  If @code{AC_CONFIG_HEADERS}
2383 is called, @command{configure} replaces @samp{@@DEFS@@} with
2384 @option{-DHAVE_CONFIG_H} instead (@pxref{Configuration Headers}).  This
2385 variable is not defined while @command{configure} is performing its tests,
2386 only when creating the output files.  @xref{Setting Output Variables}, for
2387 how to check the results of previous tests.
2388 @end defvar
2390 @defvar ECHO_C
2391 @defvarx ECHO_N
2392 @defvarx ECHO_T
2393 @ovindex ECHO_C
2394 @ovindex ECHO_N
2395 @ovindex ECHO_T
2396 How does one suppress the trailing newline from @command{echo} for
2397 question-answer message pairs?  These variables provide a way:
2399 @example
2400 echo $ECHO_N "And the winner is... $ECHO_C"
2401 sleep 100000000000
2402 echo "$@{ECHO_T@}dead."
2403 @end example
2405 @noindent
2406 Some old and uncommon @command{echo} implementations offer no means to
2407 achieve this, in which case @code{ECHO_T} is set to tab.  You might not
2408 want to use it.
2409 @end defvar
2411 @defvar ERLCFLAGS
2412 @ovindex ERLCFLAGS
2413 Debugging and optimization options for the Erlang compiler.  If it is not set
2414 in the environment when @command{configure} runs, the default value is empty.
2415 @command{configure} uses this variable when compiling
2416 programs to test for Erlang features.
2417 @end defvar
2419 @defvar FCFLAGS
2420 @ovindex FCFLAGS
2421 Debugging and optimization options for the Fortran compiler.  If it
2422 is not set in the environment when @command{configure} runs, the default
2423 value is set when you call @code{AC_PROG_FC} (or empty if you don't).
2424 @command{configure} uses this variable when compiling or linking
2425 programs to test for Fortran features.
2426 @end defvar
2428 @defvar FFLAGS
2429 @ovindex FFLAGS
2430 Debugging and optimization options for the Fortran 77 compiler.  If it
2431 is not set in the environment when @command{configure} runs, the default
2432 value is set when you call @code{AC_PROG_F77} (or empty if you don't).
2433 @command{configure} uses this variable when compiling or linking
2434 programs to test for Fortran 77 features.
2435 @end defvar
2437 @defvar LDFLAGS
2438 @ovindex LDFLAGS
2439 Options for the linker.  If it is not set
2440 in the environment when @command{configure} runs, the default value is empty.
2441 @command{configure} uses this variable when linking programs to test for
2442 C, C++, Objective C, and Fortran features.
2444 This variable's contents should contain options like @option{-s} and
2445 @option{-L} that affect only the behavior of the linker.  Please see the
2446 explanation of @code{CFLAGS} for what you can do if an option also
2447 affects other phases of the compiler.
2449 Don't use this variable to pass library names
2450 (@option{-l}) to the linker; use @code{LIBS} instead.
2451 @end defvar
2453 @defvar LIBS
2454 @ovindex LIBS
2455 @option{-l} options to pass to the linker.  The default value is empty,
2456 but some Autoconf macros may prepend extra libraries to this variable if
2457 those libraries are found and provide necessary functions, see
2458 @ref{Libraries}.  @command{configure} uses this variable when linking
2459 programs to test for C, C++, and Fortran features.
2460 @end defvar
2462 @defvar OBJCFLAGS
2463 @ovindex OBJCFLAGS
2464 Debugging and optimization options for the Objective C compiler.  It
2465 acts like @code{CFLAGS}, but for Objective C instead of C.
2466 @end defvar
2468 @defvar builddir
2469 @ovindex builddir
2470 Rigorously equal to @samp{.}.  Added for symmetry only.
2471 @end defvar
2473 @defvar abs_builddir
2474 @ovindex abs_builddir
2475 Absolute name of @code{builddir}.
2476 @end defvar
2478 @defvar top_builddir
2479 @ovindex top_builddir
2480 The relative name of the top level of the current build tree.  In the
2481 top-level directory, this is the same as @code{builddir}.
2482 @end defvar
2484 @defvar top_build_prefix
2485 @ovindex top_build_prefix
2486 The relative name of the top level of the current build tree with final
2487 slash if nonemtpy.  This is the same as @code{top_builddir}, except that
2488 it contains of zero of more runs of @code{../}, so it should not be
2489 appended with a slash for concatenation.  This helps for @command{make}
2490 implementations that otherwise do not treat @file{./file} and @file{file}
2491 as equal in the toplevel build directory.
2492 @end defvar
2494 @defvar abs_top_builddir
2495 @ovindex abs_top_builddir
2496 Absolute name of @code{top_builddir}.
2497 @end defvar
2499 @defvar srcdir
2500 @ovindex srcdir
2501 The name of the directory that contains the source code for
2502 that makefile.
2503 @end defvar
2505 @defvar abs_srcdir
2506 @ovindex abs_srcdir
2507 Absolute name of @code{srcdir}.
2508 @end defvar
2510 @defvar top_srcdir
2511 @ovindex top_srcdir
2512 The name of the top-level source code directory for the
2513 package.  In the top-level directory, this is the same as @code{srcdir}.
2514 @end defvar
2516 @defvar abs_top_srcdir
2517 @ovindex abs_top_srcdir
2518 Absolute name of @code{top_srcdir}.
2519 @end defvar
2521 @node Installation Directory Variables
2522 @subsection Installation Directory Variables
2523 @cindex Installation directories
2524 @cindex Directories, installation
2526 The following variables specify the directories for
2527 package installation, see @ref{Directory Variables, , Variables for
2528 Installation Directories, standards, The @acronym{GNU} Coding
2529 Standards}, for more information.  Each variable corresponds to an
2530 argument of @command{configure}; trailing slashes are stripped so that
2531 expressions such as @samp{$@{prefix@}/lib} expand with only one slash
2532 between directory names.  See the end of this section for
2533 details on when and how to use these variables.
2535 @defvar bindir
2536 @ovindex bindir
2537 The directory for installing executables that users run.
2538 @end defvar
2540 @defvar datadir
2541 @ovindex datadir
2542 The directory for installing idiosyncratic read-only
2543 architecture-independent data.
2544 @end defvar
2546 @defvar datarootdir
2547 @ovindex datarootdir
2548 The root of the directory tree for read-only architecture-independent
2549 data files.
2550 @end defvar
2552 @defvar docdir
2553 @ovindex docdir
2554 The directory for installing documentation files (other than Info and
2555 man).
2556 @end defvar
2558 @defvar dvidir
2559 @ovindex dvidir
2560 The directory for installing documentation files in DVI format.
2561 @end defvar
2563 @defvar exec_prefix
2564 @ovindex exec_prefix
2565 The installation prefix for architecture-dependent files.  By default
2566 it's the same as @var{prefix}.  You should avoid installing anything
2567 directly to @var{exec_prefix}.  However, the default value for
2568 directories containing architecture-dependent files should be relative
2569 to @var{exec_prefix}.
2570 @end defvar
2572 @defvar htmldir
2573 @ovindex htmldir
2574 The directory for installing HTML documentation.
2575 @end defvar
2577 @defvar includedir
2578 @ovindex includedir
2579 The directory for installing C header files.
2580 @end defvar
2582 @defvar infodir
2583 @ovindex infodir
2584 The directory for installing documentation in Info format.
2585 @end defvar
2587 @defvar libdir
2588 @ovindex libdir
2589 The directory for installing object code libraries.
2590 @end defvar
2592 @defvar libexecdir
2593 @ovindex libexecdir
2594 The directory for installing executables that other programs run.
2595 @end defvar
2597 @defvar localedir
2598 @ovindex localedir
2599 The directory for installing locale-dependent but
2600 architecture-independent data, such as message catalogs.  This directory
2601 usually has a subdirectory per locale.
2602 @end defvar
2604 @defvar localstatedir
2605 @ovindex localstatedir
2606 The directory for installing modifiable single-machine data.
2607 @end defvar
2609 @defvar mandir
2610 @ovindex mandir
2611 The top-level directory for installing documentation in man format.
2612 @end defvar
2614 @defvar oldincludedir
2615 @ovindex oldincludedir
2616 The directory for installing C header files for non-@acronym{GCC} compilers.
2617 @end defvar
2619 @defvar pdfdir
2620 @ovindex pdfdir
2621 The directory for installing PDF documentation.
2622 @end defvar
2624 @defvar prefix
2625 @ovindex prefix
2626 The common installation prefix for all files.  If @var{exec_prefix}
2627 is defined to a different value, @var{prefix} is used only for
2628 architecture-independent files.
2629 @end defvar
2631 @defvar psdir
2632 @ovindex psdir
2633 The directory for installing PostScript documentation.
2634 @end defvar
2636 @defvar sbindir
2637 @ovindex sbindir
2638 The directory for installing executables that system
2639 administrators run.
2640 @end defvar
2642 @defvar sharedstatedir
2643 @ovindex sharedstatedir
2644 The directory for installing modifiable architecture-independent data.
2645 @end defvar
2647 @defvar sysconfdir
2648 @ovindex sysconfdir
2649 The directory for installing read-only single-machine data.
2650 @end defvar
2653 Most of these variables have values that rely on @code{prefix} or
2654 @code{exec_prefix}.  It is deliberate that the directory output
2655 variables keep them unexpanded: typically @samp{@@datarootdir@@} is
2656 replaced by @samp{$@{prefix@}/share}, not @samp{/usr/local/share}, and
2657 @samp{@@datadir@@} is replaced by @samp{$@{datarootdir@}}.
2659 This behavior is mandated by the @acronym{GNU} coding standards, so that when
2660 the user runs:
2662 @table @samp
2663 @item make
2664 she can still specify a different prefix from the one specified to
2665 @command{configure}, in which case, if needed, the package should hard
2666 code dependencies corresponding to the make-specified prefix.
2668 @item make install
2669 she can specify a different installation location, in which case the
2670 package @emph{must} still depend on the location which was compiled in
2671 (i.e., never recompile when @samp{make install} is run).  This is an
2672 extremely important feature, as many people may decide to install all
2673 the files of a package grouped together, and then install links from
2674 the final locations to there.
2675 @end table
2677 In order to support these features, it is essential that
2678 @code{datarootdir} remains being defined as @samp{$@{prefix@}/share} to
2679 depend upon the current value of @code{prefix}.
2681 A corollary is that you should not use these variables except in
2682 makefiles.  For instance, instead of trying to evaluate @code{datadir}
2683 in @file{configure} and hard-coding it in makefiles using
2684 e.g., @samp{AC_DEFINE_UNQUOTED([DATADIR], ["$datadir"], [Data directory.])},
2685 you should add
2686 @option{-DDATADIR='$(datadir)'} to your makefile's definition of
2687 @code{CPPFLAGS} (@code{AM_CPPFLAGS} if you are also using Automake).
2689 Similarly, you should not rely on @code{AC_CONFIG_FILES} to replace
2690 @code{datadir} and friends in your shell scripts and other files; instead,
2691 let @command{make} manage their replacement.  For instance Autoconf
2692 ships templates of its shell scripts ending with @samp{.in}, and uses a
2693 makefile snippet similar to the following to build scripts like
2694 @command{autoheader} and @command{autom4te}:
2696 @example
2697 @group
2698 edit = sed \
2699         -e 's|@@datadir[@@]|$(pkgdatadir)|g' \
2700         -e 's|@@prefix[@@]|$(prefix)|g'
2701 @end group
2703 @group
2704 autoheader autom4te: Makefile
2705         rm -f $@@ $@@.tmp
2706         $(edit) '$(srcdir)/$@@.in' >$@@.tmp
2707         chmod +x $@@.tmp
2708         chmod a-w $@@.tmp
2709         mv $@@.tmp $@@
2710 @end group
2712 @group
2713 autoheader: $(srcdir)/autoheader.in
2714 autom4te: $(srcdir)/autom4te.in
2715 @end group
2716 @end example
2718 Some details are noteworthy:
2720 @table @asis
2721 @item @samp{@@datadir[@@]}
2722 The brackets prevent @command{configure} from replacing
2723 @samp{@@datadir@@} in the Sed expression itself.
2724 Brackets are preferable to a backslash here, since
2725 Posix says @samp{\@@} is not portable.
2727 @item @samp{$(pkgdatadir)}
2728 Don't use @samp{@@pkgdatadir@@}!  Use the matching makefile variable
2729 instead.
2731 @item @samp{/}
2732 Don't use @samp{/} in the Sed expressions that replace file names since
2733 most likely the
2734 variables you use, such as @samp{$(pkgdatadir)}, contain @samp{/}.
2735 Use a shell metacharacter instead, such as @samp{|}.
2737 @item special characters
2738 File names, file name components, and the value of @code{VPATH} should
2739 not contain shell metacharacters or white
2740 space.  @xref{Special Chars in Variables}.
2742 @item dependency on @file{Makefile}
2743 Since @code{edit} uses values that depend on the configuration specific
2744 values (@code{prefix}, etc.)@: and not only on @code{VERSION} and so forth,
2745 the output depends on @file{Makefile}, not @file{configure.ac}.
2747 @item @samp{$@@}
2748 The main rule is generic, and uses @samp{$@@} extensively to
2749 avoid the need for multiple copies of the rule.
2751 @item Separated dependencies and single suffix rules
2752 You can't use them!  The above snippet cannot be (portably) rewritten
2755 @example
2756 autoconf autoheader: Makefile
2757 @group
2758 .in:
2759         rm -f $@@ $@@.tmp
2760         $(edit) $< >$@@.tmp
2761         chmod +x $@@.tmp
2762         mv $@@.tmp $@@
2763 @end group
2764 @end example
2766 @xref{Single Suffix Rules}, for details.
2768 @item @samp{$(srcdir)}
2769 Be sure to specify the name of the source directory,
2770 otherwise the package won't support separated builds.
2771 @end table
2773 For the more specific installation of Erlang libraries, the following variables
2774 are defined:
2776 @defvar ERLANG_INSTALL_LIB_DIR
2777 @ovindex ERLANG_INSTALL_LIB_DIR
2778 @acindex{ERLANG_SUBST_INSTALL_LIB_DIR}
2779 The common parent directory of Erlang library installation directories.
2780 This variable is set by calling the @code{AC_ERLANG_SUBST_INSTALL_LIB_DIR}
2781 macro in @file{configure.ac}.
2782 @end defvar
2784 @defvar ERLANG_INSTALL_LIB_DIR_@var{library}
2785 @ovindex ERLANG_INSTALL_LIB_DIR_@var{library}
2786 @acindex{ERLANG_SUBST_INSTALL_LIB_SUBDIR}
2787 The installation directory for Erlang library @var{library}.
2788 This variable is set by calling the
2789 @samp{AC_ERLANG_SUBST_INSTALL_LIB_SUBDIR(@var{library}, @var{version}}
2790 macro in @file{configure.ac}.
2791 @end defvar
2793 @xref{Erlang Libraries}, for details.
2796 @node Changed Directory Variables
2797 @subsection Changed Directory Variables
2798 @cindex @file{datarootdir}
2800 In Autoconf 2.60, the set of directory variables has changed, and the
2801 defaults of some variables have been adjusted
2802 (@pxref{Installation Directory Variables}) to changes in the
2803 @acronym{GNU} Coding Standards.  Notably, @file{datadir}, @file{infodir}, and
2804 @file{mandir} are now expressed in terms of @file{datarootdir}.  If you are
2805 upgrading from an earlier Autoconf version, you may need to adjust your files
2806 to ensure that the directory variables are substituted correctly
2807 (@pxref{Defining Directories}), and that a definition of @file{datarootdir} is
2808 in place.  For example, in a @file{Makefile.in}, adding
2810 @example
2811 datarootdir = @@datarootdir@@
2812 @end example
2814 @noindent
2815 is usually sufficient.  If you use Automake to create @file{Makefile.in},
2816 it will add this for you.
2818 To help with the transition, Autoconf warns about files that seem to use
2819 @code{datarootdir} without defining it.  In some cases, it then expands
2820 the value of @code{$datarootdir} in substitutions of the directory
2821 variables.  The following example shows such a warning:
2823 @example
2824 $ @kbd{cat configure.ac}
2825 AC_INIT
2826 AC_CONFIG_FILES([Makefile])
2827 AC_OUTPUT
2828 $ @kbd{cat Makefile.in}
2829 prefix = @@prefix@@
2830 datadir = @@datadir@@
2831 $ @kbd{autoconf}
2832 $ @kbd{configure}
2833 configure: creating ./config.status
2834 config.status: creating Makefile
2835 config.status: WARNING:
2836                Makefile.in seems to ignore the --datarootdir setting
2837 $ @kbd{cat Makefile}
2838 prefix = /usr/local
2839 datadir = $@{prefix@}/share
2840 @end example
2842 Usually one can easily change the file to accommodate both older and newer
2843 Autoconf releases:
2845 @example
2846 $ @kbd{cat Makefile.in}
2847 prefix = @@prefix@@
2848 datarootdir = @@datarootdir@@
2849 datadir = @@datadir@@
2850 $ @kbd{configure}
2851 configure: creating ./config.status
2852 config.status: creating Makefile
2853 $ @kbd{cat Makefile}
2854 prefix = /usr/local
2855 datarootdir = $@{prefix@}/share
2856 datadir = $@{datarootdir@}
2857 @end example
2859 @acindex{DATAROOTDIR_CHECKED}
2860 In some cases, however, the checks may not be able to detect that a suitable
2861 initialization of @code{datarootdir} is in place, or they may fail to detect
2862 that such an initialization is necessary in the output file.  If, after
2863 auditing your package, there are still spurious @file{configure} warnings about
2864 @code{datarootdir}, you may add the line
2866 @example
2867 AC_DEFUN([AC_DATAROOTDIR_CHECKED])
2868 @end example
2870 @noindent
2871 to your @file{configure.ac} to disable the warnings.  This is an exception
2872 to the usual rule that you should not define a macro whose name begins with
2873 @code{AC_} (@pxref{Macro Names}).
2877 @node Build Directories
2878 @subsection Build Directories
2879 @cindex Build directories
2880 @cindex Directories, build
2882 You can support compiling a software package for several architectures
2883 simultaneously from the same copy of the source code.  The object files
2884 for each architecture are kept in their own directory.
2886 To support doing this, @command{make} uses the @code{VPATH} variable to
2887 find the files that are in the source directory.  @acronym{GNU} Make
2888 can do this.  Most other recent @command{make} programs can do this as
2889 well, though they may have difficulties and it is often simpler to
2890 recommend @acronym{GNU} @command{make} (@pxref{VPATH and Make}).  Older
2891 @command{make} programs do not support @code{VPATH}; when using them, the
2892 source code must be in the same directory as the object files.
2894 To support @code{VPATH}, each @file{Makefile.in} should contain two
2895 lines that look like:
2897 @example
2898 srcdir = @@srcdir@@
2899 VPATH = @@srcdir@@
2900 @end example
2902 Do not set @code{VPATH} to the value of another variable, for example
2903 @samp{VPATH = $(srcdir)}, because some versions of @command{make} do not do
2904 variable substitutions on the value of @code{VPATH}.
2906 @command{configure} substitutes the correct value for @code{srcdir} when
2907 it produces @file{Makefile}.
2909 Do not use the @command{make} variable @code{$<}, which expands to the
2910 file name of the file in the source directory (found with @code{VPATH}),
2911 except in implicit rules.  (An implicit rule is one such as @samp{.c.o},
2912 which tells how to create a @file{.o} file from a @file{.c} file.)  Some
2913 versions of @command{make} do not set @code{$<} in explicit rules; they
2914 expand it to an empty value.
2916 Instead, Make command lines should always refer to source
2917 files by prefixing them with @samp{$(srcdir)/}.  For example:
2919 @example
2920 time.info: time.texinfo
2921         $(MAKEINFO) '$(srcdir)/time.texinfo'
2922 @end example
2924 @node Automatic Remaking
2925 @subsection Automatic Remaking
2926 @cindex Automatic remaking
2927 @cindex Remaking automatically
2929 You can put rules like the following in the top-level @file{Makefile.in}
2930 for a package to automatically update the configuration information when
2931 you change the configuration files.  This example includes all of the
2932 optional files, such as @file{aclocal.m4} and those related to
2933 configuration header files.  Omit from the @file{Makefile.in} rules for
2934 any of these files that your package does not use.
2936 The @samp{$(srcdir)/} prefix is included because of limitations in the
2937 @code{VPATH} mechanism.
2939 The @file{stamp-} files are necessary because the timestamps of
2940 @file{config.h.in} and @file{config.h} are not changed if remaking
2941 them does not change their contents.  This feature avoids unnecessary
2942 recompilation.  You should include the file @file{stamp-h.in} your
2943 package's distribution, so that @command{make} considers
2944 @file{config.h.in} up to date.  Don't use @command{touch}
2945 (@pxref{Limitations of Usual Tools}); instead, use @command{echo} (using
2946 @command{date} would cause needless differences, hence @acronym{CVS}
2947 conflicts, etc.).
2949 @example
2950 @group
2951 $(srcdir)/configure: configure.ac aclocal.m4
2952         cd '$(srcdir)' && autoconf
2954 # autoheader might not change config.h.in, so touch a stamp file.
2955 $(srcdir)/config.h.in: stamp-h.in
2956 $(srcdir)/stamp-h.in: configure.ac aclocal.m4
2957         cd '$(srcdir)' && autoheader
2958         echo timestamp > '$(srcdir)/stamp-h.in'
2960 config.h: stamp-h
2961 stamp-h: config.h.in config.status
2962         ./config.status
2964 Makefile: Makefile.in config.status
2965         ./config.status
2967 config.status: configure
2968         ./config.status --recheck
2969 @end group
2970 @end example
2972 @noindent
2973 (Be careful if you copy these lines directly into your makefile, as you
2974 need to convert the indented lines to start with the tab character.)
2976 In addition, you should use
2978 @example
2979 AC_CONFIG_FILES([stamp-h], [echo timestamp > stamp-h])
2980 @end example
2982 @noindent
2983 so @file{config.status} ensures that @file{config.h} is considered up to
2984 date.  @xref{Output}, for more information about @code{AC_OUTPUT}.
2986 @xref{config.status Invocation}, for more examples of handling
2987 configuration-related dependencies.
2989 @node Configuration Headers
2990 @section Configuration Header Files
2991 @cindex Configuration Header
2992 @cindex @file{config.h}
2994 When a package contains more than a few tests that define C preprocessor
2995 symbols, the command lines to pass @option{-D} options to the compiler
2996 can get quite long.  This causes two problems.  One is that the
2997 @command{make} output is hard to visually scan for errors.  More
2998 seriously, the command lines can exceed the length limits of some
2999 operating systems.  As an alternative to passing @option{-D} options to
3000 the compiler, @command{configure} scripts can create a C header file
3001 containing @samp{#define} directives.  The @code{AC_CONFIG_HEADERS}
3002 macro selects this kind of output.  Though it can be called anywhere
3003 between @code{AC_INIT} and @code{AC_OUTPUT}, it is customary to call
3004 it right after @code{AC_INIT}.
3006 The package should @samp{#include} the configuration header file before
3007 any other header files, to prevent inconsistencies in declarations (for
3008 example, if it redefines @code{const}).
3010 To provide for VPATH builds, remember to pass the C compiler a @option{-I.}
3011 option (or @option{-I..}; whichever directory contains @file{config.h}).
3012 Even if you use @samp{#include "config.h"}, the preprocessor searches only
3013 the directory of the currently read file, i.e., the source directory, not
3014 the build directory.
3016 With the appropriate @option{-I} option, you can use
3017 @samp{#include <config.h>}.  Actually, it's a good habit to use it,
3018 because in the rare case when the source directory contains another
3019 @file{config.h}, the build directory should be searched first.
3022 @defmac AC_CONFIG_HEADERS (@var{header} @dots{}, @ovar{cmds}, @ovar{init-cmds})
3023 @acindex{CONFIG_HEADERS}
3024 @cvindex HAVE_CONFIG_H
3025 This macro is one of the instantiating macros; see @ref{Configuration
3026 Actions}.  Make @code{AC_OUTPUT} create the file(s) in the
3027 blank-or-newline-separated list @var{header} containing C preprocessor
3028 @code{#define} statements, and replace @samp{@@DEFS@@} in generated
3029 files with @option{-DHAVE_CONFIG_H} instead of the value of @code{DEFS}.
3030 The usual name for @var{header} is @file{config.h}.
3032 If @var{header} already exists and its contents are identical to what
3033 @code{AC_OUTPUT} would put in it, it is left alone.  Doing this allows
3034 making some changes in the configuration without needlessly causing
3035 object files that depend on the header file to be recompiled.
3037 Usually the input file is named @file{@var{header}.in}; however, you can
3038 override the input file name by appending to @var{header} a
3039 colon-separated list of input files.  For example, you might need to make
3040 the input file name acceptable to @acronym{DOS} variants:
3042 @example
3043 AC_CONFIG_HEADERS([config.h:config.hin])
3044 @end example
3046 @end defmac
3048 @defmac AH_HEADER
3049 @ahindex{HEADER}
3050 This macro is defined as the name of the first declared config header
3051 and undefined if no config headers have been declared up to this point.
3052 A third-party macro may, for example, require use of a config header
3053 without invoking AC_CONFIG_HEADERS twice, like this:
3055 @example
3056 AC_CONFIG_COMMANDS_PRE(
3057         [m4_ifndef([AH_HEADER], [AC_CONFIG_HEADERS([config.h])])])
3058 @end example
3060 @end defmac
3062 @xref{Configuration Actions}, for more details on @var{header}.
3064 @menu
3065 * Header Templates::            Input for the configuration headers
3066 * autoheader Invocation::       How to create configuration templates
3067 * Autoheader Macros::           How to specify CPP templates
3068 @end menu
3070 @node Header Templates
3071 @subsection Configuration Header Templates
3072 @cindex Configuration Header Template
3073 @cindex Header templates
3074 @cindex @file{config.h.in}
3076 Your distribution should contain a template file that looks as you want
3077 the final header file to look, including comments, with @code{#undef}
3078 statements which are used as hooks.  For example, suppose your
3079 @file{configure.ac} makes these calls:
3081 @example
3082 AC_CONFIG_HEADERS([conf.h])
3083 AC_CHECK_HEADERS([unistd.h])
3084 @end example
3086 @noindent
3087 Then you could have code like the following in @file{conf.h.in}.
3088 The @file{conf.h} created by @command{configure} defines @samp{HAVE_UNISTD_H}
3089 to 1, if and only if the system has @file{unistd.h}.
3091 @example
3092 @group
3093 /* Define as 1 if you have unistd.h.  */
3094 #undef HAVE_UNISTD_H
3095 @end group
3096 @end example
3098 The format of the template file is stricter than what the C preprocessor
3099 is required to accept.  A directive line should contain only whitespace,
3100 @samp{#undef}, and @samp{HAVE_UNISTD_H}.  The use of @samp{#define}
3101 instead of @samp{#undef}, or of comments on the same line as
3102 @samp{#undef}, is strongly discouraged.  Each hook should only be listed
3103 once.  Other preprocessor lines, such as @samp{#ifdef} or
3104 @samp{#include}, are copied verbatim from the template into the
3105 generated header.
3107 Since it is a tedious task to keep a template header up to date, you may
3108 use @command{autoheader} to generate it, see @ref{autoheader Invocation}.
3110 During the instantiation of the header, each @samp{#undef} line in the
3111 template file for each symbol defined by @samp{AC_DEFINE} is changed to an
3112 appropriate @samp{#define}. If the corresponding @samp{AC_DEFINE} has not
3113 been executed during the @command{configure} run, the @samp{#undef} line is
3114 commented out.  (This is important, e.g., for @samp{_POSIX_SOURCE}:
3115 on many systems, it can be implicitly defined by the compiler, and
3116 undefining it in the header would then break compilation of subsequent
3117 headers.)
3119 Currently, @emph{all} remaining @samp{#undef} lines in the header
3120 template are commented out, whether or not there was a corresponding
3121 @samp{AC_DEFINE} for the macro name; but this behavior is not guaranteed
3122 for future releases of Autoconf.
3124 Generally speaking, since you should not use @samp{#define}, and you
3125 cannot guarantee whether a @samp{#undef} directive in the header
3126 template will be converted to a @samp{#define} or commented out in the
3127 generated header file, the template file cannot be used for conditional
3128 definition effects.  Consequently, if you need to use the construct
3130 @example
3131 @group
3132 #ifdef THIS
3133 # define THAT
3134 #endif
3135 @end group
3136 @end example
3138 @noindent
3139 you must place it outside of the template.
3140 If you absolutely need to hook it to the config header itself, please put
3141 the directives to a separate file, and @samp{#include} that file from the
3142 config header template.  If you are using @command{autoheader}, you would
3143 probably use @samp{AH_BOTTOM} to append the @samp{#include} directive.
3146 @node autoheader Invocation
3147 @subsection Using @command{autoheader} to Create @file{config.h.in}
3148 @cindex @command{autoheader}
3150 The @command{autoheader} program can create a template file of C
3151 @samp{#define} statements for @command{configure} to use.
3152 It searches for the first invocation of @code{AC_CONFIG_HEADERS} in
3153 @file{configure} sources to determine the name of the template.
3154 (If the first call of @code{AC_CONFIG_HEADERS} specifies more than one
3155 input file name, @command{autoheader} uses the first one.)
3157 It is recommended that only one input file is used.  If you want to append
3158 a boilerplate code, it is preferable to use
3159 @samp{AH_BOTTOM([#include <conf_post.h>])}.
3160 File @file{conf_post.h} is not processed during the configuration then,
3161 which make things clearer.  Analogically, @code{AH_TOP} can be used to
3162 prepend a boilerplate code.
3164 In order to do its job, @command{autoheader} needs you to document all
3165 of the symbols that you might use.  Typically this is done via an
3166 @code{AC_DEFINE} or @code{AC_DEFINE_UNQUOTED} call whose first argument
3167 is a literal symbol and whose third argument describes the symbol
3168 (@pxref{Defining Symbols}).  Alternatively, you can use
3169 @code{AH_TEMPLATE} (@pxref{Autoheader Macros}), or you can supply a
3170 suitable input file for a subsequent configuration header file.
3171 Symbols defined by Autoconf's builtin tests are already documented properly;
3172 you need to document only those that you
3173 define yourself.
3175 You might wonder why @command{autoheader} is needed: after all, why
3176 would @command{configure} need to ``patch'' a @file{config.h.in} to
3177 produce a @file{config.h} instead of just creating @file{config.h} from
3178 scratch?  Well, when everything rocks, the answer is just that we are
3179 wasting our time maintaining @command{autoheader}: generating
3180 @file{config.h} directly is all that is needed.  When things go wrong,
3181 however, you'll be thankful for the existence of @command{autoheader}.
3183 The fact that the symbols are documented is important in order to
3184 @emph{check} that @file{config.h} makes sense.  The fact that there is a
3185 well-defined list of symbols that should be defined (or not) is
3186 also important for people who are porting packages to environments where
3187 @command{configure} cannot be run: they just have to @emph{fill in the
3188 blanks}.
3190 But let's come back to the point: the invocation of @command{autoheader}@dots{}
3192 If you give @command{autoheader} an argument, it uses that file instead
3193 of @file{configure.ac} and writes the header file to the standard output
3194 instead of to @file{config.h.in}.  If you give @command{autoheader} an
3195 argument of @option{-}, it reads the standard input instead of
3196 @file{configure.ac} and writes the header file to the standard output.
3198 @command{autoheader} accepts the following options:
3200 @table @option
3201 @item --help
3202 @itemx -h
3203 Print a summary of the command line options and exit.
3205 @item --version
3206 @itemx -V
3207 Print the version number of Autoconf and exit.
3209 @item --verbose
3210 @itemx -v
3211 Report processing steps.
3213 @item --debug
3214 @itemx -d
3215 Don't remove the temporary files.
3217 @item --force
3218 @itemx -f
3219 Remake the template file even if newer than its input files.
3221 @item --include=@var{dir}
3222 @itemx -I @var{dir}
3223 Append @var{dir} to the include path.  Multiple invocations accumulate.
3225 @item --prepend-include=@var{dir}
3226 @itemx -B @var{dir}
3227 Prepend @var{dir} to the include path.  Multiple invocations accumulate.
3229 @item --warnings=@var{category}
3230 @itemx -W @var{category}
3231 @evindex WARNINGS
3232 Report the warnings related to @var{category} (which can actually be a
3233 comma separated list).  Current categories include:
3235 @table @samp
3236 @item obsolete
3237 report the uses of obsolete constructs
3239 @item all
3240 report all the warnings
3242 @item none
3243 report none
3245 @item error
3246 treats warnings as errors
3248 @item no-@var{category}
3249 disable warnings falling into @var{category}
3250 @end table
3252 @end table
3256 @node Autoheader Macros
3257 @subsection Autoheader Macros
3258 @cindex Autoheader macros
3260 @command{autoheader} scans @file{configure.ac} and figures out which C
3261 preprocessor symbols it might define.  It knows how to generate
3262 templates for symbols defined by @code{AC_CHECK_HEADERS},
3263 @code{AC_CHECK_FUNCS} etc., but if you @code{AC_DEFINE} any additional
3264 symbol, you must define a template for it.  If there are missing
3265 templates, @command{autoheader} fails with an error message.
3267 The template for a @var{symbol} is created
3268 by @command{autoheader} from
3269 the @var{description} argument to an @code{AC_DEFINE};
3270 see @ref{Defining Symbols}.
3272 For special needs, you can use the following macros.
3275 @defmac AH_TEMPLATE (@var{key}, @var{description})
3276 @ahindex{TEMPLATE}
3277 Tell @command{autoheader} to generate a template for @var{key}.  This macro
3278 generates standard templates just like @code{AC_DEFINE} when a
3279 @var{description} is given.
3281 For example:
3283 @example
3284 AH_TEMPLATE([CRAY_STACKSEG_END],
3285             [Define to one of _getb67, GETB67, getb67
3286              for Cray-2 and Cray-YMP systems.  This
3287              function is required for alloca.c support
3288              on those systems.])
3289 @end example
3291 @noindent
3292 generates the following template, with the description properly
3293 justified.
3295 @example
3296 /* Define to one of _getb67, GETB67, getb67 for Cray-2 and
3297    Cray-YMP systems.  This function is required for alloca.c
3298    support on those systems.  */
3299 #undef CRAY_STACKSEG_END
3300 @end example
3301 @end defmac
3304 @defmac AH_VERBATIM (@var{key}, @var{template})
3305 @ahindex{VERBATIM}
3306 Tell @command{autoheader} to include the @var{template} as-is in the header
3307 template file.  This @var{template} is associated with the @var{key},
3308 which is used to sort all the different templates and guarantee their
3309 uniqueness.  It should be a symbol that can be defined via @code{AC_DEFINE}.
3310 @end defmac
3313 @defmac AH_TOP (@var{text})
3314 @ahindex{TOP}
3315 Include @var{text} at the top of the header template file.
3316 @end defmac
3319 @defmac AH_BOTTOM (@var{text})
3320 @ahindex{BOTTOM}
3321 Include @var{text} at the bottom of the header template file.
3322 @end defmac
3325 Please note that @var{text} gets included ``verbatim'' to the template file,
3326 not to the resulting config header, so it can easily get mangled when the
3327 template is processed.  There is rarely a need for something other than
3329 @example
3330 AH_BOTTOM([#include <custom.h>])
3331 @end example
3335 @node Configuration Commands
3336 @section Running Arbitrary Configuration Commands
3337 @cindex Configuration commands
3338 @cindex Commands for configuration
3340 You can execute arbitrary commands before, during, and after
3341 @file{config.status} is run.  The three following macros accumulate the
3342 commands to run when they are called multiple times.
3343 @code{AC_CONFIG_COMMANDS} replaces the obsolete macro
3344 @code{AC_OUTPUT_COMMANDS}; see @ref{Obsolete Macros}, for details.
3346 @anchor{AC_CONFIG_COMMANDS}
3347 @defmac AC_CONFIG_COMMANDS (@var{tag}@dots{}, @ovar{cmds}, @ovar{init-cmds})
3348 @acindex{CONFIG_COMMANDS}
3349 Specify additional shell commands to run at the end of
3350 @file{config.status}, and shell commands to initialize any variables
3351 from @command{configure}.  Associate the commands with @var{tag}.
3352 Since typically the @var{cmds} create a file, @var{tag} should
3353 naturally be the name of that file.  If needed, the directory hosting
3354 @var{tag} is created.  This macro is one of the instantiating macros;
3355 see @ref{Configuration Actions}.
3357 Here is an unrealistic example:
3358 @example
3359 fubar=42
3360 AC_CONFIG_COMMANDS([fubar],
3361                    [echo this is extra $fubar, and so on.],
3362                    [fubar=$fubar])
3363 @end example
3365 Here is a better one:
3366 @example
3367 AC_CONFIG_COMMANDS([timestamp], [date >timestamp])
3368 @end example
3369 @end defmac
3371 The following two macros look similar, but in fact they are not of the same
3372 breed: they are executed directly by @file{configure}, so you cannot use
3373 @file{config.status} to rerun them.
3375 @c Yet it is good to leave them here.  The user sees them together and
3376 @c decides which best fits their needs.
3378 @defmac AC_CONFIG_COMMANDS_PRE (@var{cmds})
3379 @acindex{CONFIG_COMMANDS_PRE}
3380 Execute the @var{cmds} right before creating @file{config.status}.
3382 This macro presents the last opportunity to call @code{AC_SUBST},
3383 @code{AC_DEFINE}, or @code{AC_CONFIG_FOOS} macros.
3384 @end defmac
3386 @defmac AC_CONFIG_COMMANDS_POST (@var{cmds})
3387 @acindex{CONFIG_COMMANDS_POST}
3388 Execute the @var{cmds} right after creating @file{config.status}.
3389 @end defmac
3394 @node Configuration Links
3395 @section Creating Configuration Links
3396 @cindex Configuration links
3397 @cindex Links for configuration
3399 You may find it convenient to create links whose destinations depend upon
3400 results of tests.  One can use @code{AC_CONFIG_COMMANDS} but the
3401 creation of relative symbolic links can be delicate when the package is
3402 built in a directory different from the source directory.
3404 @anchor{AC_CONFIG_LINKS}
3405 @defmac AC_CONFIG_LINKS (@var{dest}:@var{source}@dots{}, @ovar{cmds}, @
3406   @ovar{init-cmds})
3407 @acindex{CONFIG_LINKS}
3408 @cindex Links
3409 Make @code{AC_OUTPUT} link each of the existing files @var{source} to
3410 the corresponding link name @var{dest}.  Makes a symbolic link if
3411 possible, otherwise a hard link if possible, otherwise a copy.  The
3412 @var{dest} and @var{source} names should be relative to the top level
3413 source or build directory.  This macro is one of the instantiating
3414 macros; see @ref{Configuration Actions}.
3416 For example, this call:
3418 @example
3419 AC_CONFIG_LINKS([host.h:config/$machine.h
3420                 object.h:config/$obj_format.h])
3421 @end example
3423 @noindent
3424 creates in the current directory @file{host.h} as a link to
3425 @file{@var{srcdir}/config/$machine.h}, and @file{object.h} as a
3426 link to @file{@var{srcdir}/config/$obj_format.h}.
3428 The tempting value @samp{.} for @var{dest} is invalid: it makes it
3429 impossible for @samp{config.status} to guess the links to establish.
3431 One can then run:
3432 @example
3433 ./config.status host.h object.h
3434 @end example
3435 @noindent
3436 to create the links.
3437 @end defmac
3441 @node Subdirectories
3442 @section Configuring Other Packages in Subdirectories
3443 @cindex Configure subdirectories
3444 @cindex Subdirectory configure
3446 In most situations, calling @code{AC_OUTPUT} is sufficient to produce
3447 makefiles in subdirectories.  However, @command{configure} scripts
3448 that control more than one independent package can use
3449 @code{AC_CONFIG_SUBDIRS} to run @command{configure} scripts for other
3450 packages in subdirectories.
3452 @defmac AC_CONFIG_SUBDIRS (@var{dir} @dots{})
3453 @acindex{CONFIG_SUBDIRS}
3454 @ovindex subdirs
3455 Make @code{AC_OUTPUT} run @command{configure} in each subdirectory
3456 @var{dir} in the given blank-or-newline-separated list.  Each @var{dir} should
3457 be a literal, i.e., please do not use:
3459 @example
3460 if test "$package_foo_enabled" = yes; then
3461   $my_subdirs="$my_subdirs foo"
3463 AC_CONFIG_SUBDIRS([$my_subdirs])
3464 @end example
3466 @noindent
3467 because this prevents @samp{./configure --help=recursive} from
3468 displaying the options of the package @code{foo}.  Instead, you should
3469 write:
3471 @example
3472 if test "$package_foo_enabled" = yes; then
3473   AC_CONFIG_SUBDIRS([foo])
3475 @end example
3477 If a given @var{dir} is not found, an error is reported: if the
3478 subdirectory is optional, write:
3480 @example
3481 if test -d "$srcdir/foo"; then
3482   AC_CONFIG_SUBDIRS([foo])
3484 @end example
3486 @c NB: Yes, below we mean configure.in, not configure.ac.
3487 If a given @var{dir} contains @command{configure.gnu}, it is run instead
3488 of @command{configure}.  This is for packages that might use a
3489 non-Autoconf script @command{Configure}, which can't be called through a
3490 wrapper @command{configure} since it would be the same file on
3491 case-insensitive file systems.  Likewise, if a @var{dir} contains
3492 @file{configure.in} but no @command{configure}, the Cygnus
3493 @command{configure} script found by @code{AC_CONFIG_AUX_DIR} is used.
3495 The subdirectory @command{configure} scripts are given the same command
3496 line options that were given to this @command{configure} script, with minor
3497 changes if needed, which include:
3499 @itemize @minus
3500 @item
3501 adjusting a relative name for the cache file;
3503 @item
3504 adjusting a relative name for the source directory;
3506 @item
3507 propagating the current value of @code{$prefix}, including if it was
3508 defaulted, and if the default values of the top level and of the subdirectory
3509 @file{configure} differ.
3510 @end itemize
3512 This macro also sets the output variable @code{subdirs} to the list of
3513 directories @samp{@var{dir} @dots{}}.  Make rules can use
3514 this variable to determine which subdirectories to recurse into.
3516 This macro may be called multiple times.
3517 @end defmac
3519 @node Default Prefix
3520 @section Default Prefix
3521 @cindex Install prefix
3522 @cindex Prefix for install
3524 By default, @command{configure} sets the prefix for files it installs to
3525 @file{/usr/local}.  The user of @command{configure} can select a different
3526 prefix using the @option{--prefix} and @option{--exec-prefix} options.
3527 There are two ways to change the default: when creating
3528 @command{configure}, and when running it.
3530 Some software packages might want to install in a directory other than
3531 @file{/usr/local} by default.  To accomplish that, use the
3532 @code{AC_PREFIX_DEFAULT} macro.
3534 @defmac AC_PREFIX_DEFAULT (@var{prefix})
3535 @acindex{PREFIX_DEFAULT}
3536 Set the default installation prefix to @var{prefix} instead of
3537 @file{/usr/local}.
3538 @end defmac
3540 It may be convenient for users to have @command{configure} guess the
3541 installation prefix from the location of a related program that they
3542 have already installed.  If you wish to do that, you can call
3543 @code{AC_PREFIX_PROGRAM}.
3545 @anchor{AC_PREFIX_PROGRAM}
3546 @defmac AC_PREFIX_PROGRAM (@var{program})
3547 @acindex{PREFIX_PROGRAM}
3548 If the user did not specify an installation prefix (using the
3549 @option{--prefix} option), guess a value for it by looking for
3550 @var{program} in @env{PATH}, the way the shell does.  If @var{program}
3551 is found, set the prefix to the parent of the directory containing
3552 @var{program}, else default the prefix as described above
3553 (@file{/usr/local} or @code{AC_PREFIX_DEFAULT}).  For example, if
3554 @var{program} is @code{gcc} and the @env{PATH} contains
3555 @file{/usr/local/gnu/bin/gcc}, set the prefix to @file{/usr/local/gnu}.
3556 @end defmac
3560 @c ======================================================== Existing tests
3562 @node Existing Tests
3563 @chapter Existing Tests
3565 These macros test for particular system features that packages might
3566 need or want to use.  If you need to test for a kind of feature that
3567 none of these macros check for, you can probably do it by calling
3568 primitive test macros with appropriate arguments (@pxref{Writing
3569 Tests}).
3571 These tests print messages telling the user which feature they're
3572 checking for, and what they find.  They cache their results for future
3573 @command{configure} runs (@pxref{Caching Results}).
3575 Some of these macros set output variables.  @xref{Makefile
3576 Substitutions}, for how to get their values.  The phrase ``define
3577 @var{name}'' is used below as a shorthand to mean ``define the C
3578 preprocessor symbol @var{name} to the value 1''.  @xref{Defining
3579 Symbols}, for how to get those symbol definitions into your program.
3581 @menu
3582 * Common Behavior::             Macros' standard schemes
3583 * Alternative Programs::        Selecting between alternative programs
3584 * Files::                       Checking for the existence of files
3585 * Libraries::                   Library archives that might be missing
3586 * Library Functions::           C library functions that might be missing
3587 * Header Files::                Header files that might be missing
3588 * Declarations::                Declarations that may be missing
3589 * Structures::                  Structures or members that might be missing
3590 * Types::                       Types that might be missing
3591 * Compilers and Preprocessors::  Checking for compiling programs
3592 * System Services::             Operating system services
3593 * Posix Variants::              Special kludges for specific Posix variants
3594 * Erlang Libraries::            Checking for the existence of Erlang libraries
3595 @end menu
3597 @node Common Behavior
3598 @section Common Behavior
3599 @cindex Common autoconf behavior
3601 Much effort has been expended to make Autoconf easy to learn.  The most
3602 obvious way to reach this goal is simply to enforce standard interfaces
3603 and behaviors, avoiding exceptions as much as possible.  Because of
3604 history and inertia, unfortunately, there are still too many exceptions
3605 in Autoconf; nevertheless, this section describes some of the common
3606 rules.
3608 @menu
3609 * Standard Symbols::            Symbols defined by the macros
3610 * Default Includes::            Includes used by the generic macros
3611 @end menu
3613 @node Standard Symbols
3614 @subsection Standard Symbols
3615 @cindex Standard symbols
3617 All the generic macros that @code{AC_DEFINE} a symbol as a result of
3618 their test transform their @var{argument} values to a standard alphabet.
3619 First, @var{argument} is converted to upper case and any asterisks
3620 (@samp{*}) are each converted to @samp{P}.  Any remaining characters
3621 that are not alphanumeric are converted to underscores.
3623 For instance,
3625 @example
3626 AC_CHECK_TYPES([struct $Expensive*])
3627 @end example
3629 @noindent
3630 defines the symbol @samp{HAVE_STRUCT__EXPENSIVEP} if the check
3631 succeeds.
3634 @node Default Includes
3635 @subsection Default Includes
3636 @cindex Default includes
3637 @cindex Includes, default
3639 Several tests depend upon a set of header files.  Since these headers
3640 are not universally available, tests actually have to provide a set of
3641 protected includes, such as:
3643 @example
3644 @group
3645 #ifdef TIME_WITH_SYS_TIME
3646 # include <sys/time.h>
3647 # include <time.h>
3648 #else
3649 # ifdef HAVE_SYS_TIME_H
3650 #  include <sys/time.h>
3651 # else
3652 #  include <time.h>
3653 # endif
3654 #endif
3655 @end group
3656 @end example
3658 @noindent
3659 Unless you know exactly what you are doing, you should avoid using
3660 unconditional includes, and check the existence of the headers you
3661 include beforehand (@pxref{Header Files}).
3663 Most generic macros use the following macro to provide the default set
3664 of includes:
3666 @defmac AC_INCLUDES_DEFAULT (@ovar{include-directives})
3667 @acindex{INCLUDES_DEFAULT}
3668 Expand to @var{include-directives} if defined, otherwise to:
3670 @example
3671 @group
3672 #include <stdio.h>
3673 #ifdef HAVE_SYS_TYPES_H
3674 # include <sys/types.h>
3675 #endif
3676 #ifdef HAVE_SYS_STAT_H
3677 # include <sys/stat.h>
3678 #endif
3679 #ifdef STDC_HEADERS
3680 # include <stdlib.h>
3681 # include <stddef.h>
3682 #else
3683 # ifdef HAVE_STDLIB_H
3684 #  include <stdlib.h>
3685 # endif
3686 #endif
3687 #ifdef HAVE_STRING_H
3688 # if !defined STDC_HEADERS && defined HAVE_MEMORY_H
3689 #  include <memory.h>
3690 # endif
3691 # include <string.h>
3692 #endif
3693 #ifdef HAVE_STRINGS_H
3694 # include <strings.h>
3695 #endif
3696 #ifdef HAVE_INTTYPES_H
3697 # include <inttypes.h>
3698 #endif
3699 #ifdef HAVE_STDINT_H
3700 # include <stdint.h>
3701 #endif
3702 #ifdef HAVE_UNISTD_H
3703 # include <unistd.h>
3704 #endif
3705 @end group
3706 @end example
3708 If the default includes are used, then check for the presence of these
3709 headers and their compatibility, i.e., you don't need to run
3710 @code{AC_HEADER_STDC}, nor check for @file{stdlib.h} etc.
3712 These headers are checked for in the same order as they are included.
3713 For instance, on some systems @file{string.h} and @file{strings.h} both
3714 exist, but conflict.  Then @code{HAVE_STRING_H} is defined, not
3715 @code{HAVE_STRINGS_H}.
3716 @end defmac
3718 @node Alternative Programs
3719 @section Alternative Programs
3720 @cindex Programs, checking
3722 These macros check for the presence or behavior of particular programs.
3723 They are used to choose between several alternative programs and to
3724 decide what to do once one has been chosen.  If there is no macro
3725 specifically defined to check for a program you need, and you don't need
3726 to check for any special properties of it, then you can use one of the
3727 general program-check macros.
3729 @menu
3730 * Particular Programs::         Special handling to find certain programs
3731 * Generic Programs::            How to find other programs
3732 @end menu
3734 @node Particular Programs
3735 @subsection Particular Program Checks
3737 These macros check for particular programs---whether they exist, and
3738 in some cases whether they support certain features.
3740 @defmac AC_PROG_AWK
3741 @acindex{PROG_AWK}
3742 @ovindex AWK
3743 Check for @code{gawk}, @code{mawk}, @code{nawk}, and @code{awk}, in that
3744 order, and set output variable @code{AWK} to the first one that is found.
3745 It tries @code{gawk} first because that is reported to be the
3746 best implementation.
3747 @end defmac
3749 @defmac AC_PROG_GREP
3750 @acindex{PROG_GREP}
3751 @ovindex GREP
3752 Look for the best available @code{grep} or @code{ggrep} that accepts the
3753 longest input lines possible, and that supports multiple @option{-e} options.
3754 Set the output variable @code{GREP} to whatever is chosen.
3755 @xref{Limitations of Usual Tools}, for more information about
3756 portability problems with the @command{grep} command family.
3757 @end defmac
3759 @defmac AC_PROG_EGREP
3760 @acindex{PROG_EGREP}
3761 @ovindex EGREP
3762 Check whether @code{$GREP -E} works, or else look for the best available
3763 @code{egrep} or @code{gegrep} that accepts the longest input lines possible.
3764 Set the output variable @code{EGREP} to whatever is chosen.
3765 @end defmac
3767 @defmac AC_PROG_FGREP
3768 @acindex{PROG_FGREP}
3769 @ovindex FGREP
3770 Check whether @code{$GREP -F} works, or else look for the best available
3771 @code{fgrep} or @code{gfgrep} that accepts the longest input lines possible.
3772 Set the output variable @code{FGREP} to whatever is chosen.
3773 @end defmac
3775 @defmac AC_PROG_INSTALL
3776 @acindex{PROG_INSTALL}
3777 @ovindex INSTALL
3778 @ovindex INSTALL_PROGRAM
3779 @ovindex INSTALL_DATA
3780 @ovindex INSTALL_SCRIPT
3781 Set output variable @code{INSTALL} to the name of a @acronym{BSD}-compatible
3782 @command{install} program, if one is found in the current @env{PATH}.
3783 Otherwise, set @code{INSTALL} to @samp{@var{dir}/install-sh -c},
3784 checking the directories specified to @code{AC_CONFIG_AUX_DIR} (or its
3785 default directories) to determine @var{dir} (@pxref{Output}).  Also set
3786 the variables @code{INSTALL_PROGRAM} and @code{INSTALL_SCRIPT} to
3787 @samp{$@{INSTALL@}} and @code{INSTALL_DATA} to @samp{$@{INSTALL@} -m 644}.
3789 @samp{@@INSTALL@@} is special, as its value may vary for different
3790 configuration files.
3792 This macro screens out various instances of @command{install} known not to
3793 work.  It prefers to find a C program rather than a shell script, for
3794 speed.  Instead of @file{install-sh}, it can also use @file{install.sh},
3795 but that name is obsolete because some @command{make} programs have a rule
3796 that creates @file{install} from it if there is no makefile.  Further, this
3797 macro requires @command{install} to be able to install multiple files into a
3798 target directory in a single invocation.
3800 Autoconf comes with a copy of @file{install-sh} that you can use.  If
3801 you use @code{AC_PROG_INSTALL}, you must include either
3802 @file{install-sh} or @file{install.sh} in your distribution; otherwise
3803 @command{configure} produces an error message saying it can't find
3804 them---even if the system you're on has a good @command{install} program.
3805 This check is a safety measure to prevent you from accidentally leaving
3806 that file out, which would prevent your package from installing on
3807 systems that don't have a @acronym{BSD}-compatible @command{install} program.
3809 If you need to use your own installation program because it has features
3810 not found in standard @command{install} programs, there is no reason to use
3811 @code{AC_PROG_INSTALL}; just put the file name of your program into your
3812 @file{Makefile.in} files.
3813 @end defmac
3815 @defmac AC_PROG_MKDIR_P
3816 @acindex{PROG_MKDIR_P}
3817 @ovindex MKDIR_P
3818 Set output variable @code{MKDIR_P} to a program that ensures that for
3819 each argument, a directory named by this argument exists, creating it
3820 and its parent directories if needed, and without race conditions when
3821 two instances of the program attempt to make the same directory at
3822 nearly the same time.
3824 This macro uses the @samp{mkdir -p} command if possible.  Otherwise, it
3825 falls back on invoking @command{install-sh} with the @option{-d} option,
3826 so your package should
3827 contain @file{install-sh} as described under @code{AC_PROG_INSTALL}.
3828 An @file{install-sh} file that predates Autoconf 2.60 or Automake 1.10
3829 is vulnerable to race conditions, so if you want to support parallel
3830 installs from
3831 different packages into the same directory you need to make sure you
3832 have an up-to-date @file{install-sh}.  In particular, be careful about
3833 using @samp{autoreconf -if} if your Automake predates Automake 1.10.
3835 This macro is related to the @code{AS_MKDIR_P} macro (@pxref{Programming
3836 in M4sh}), but it sets an output variable intended for use in other
3837 files, whereas @code{AS_MKDIR_P} is intended for use in scripts like
3838 @command{configure}.  Also, @code{AS_MKDIR_P} does not accept options,
3839 but @code{MKDIR_P} supports the @option{-m} option, e.g., a makefile
3840 might invoke @code{$(MKDIR_P) -m 0 dir} to create an inaccessible
3841 directory, and conversely a makefile should use @code{$(MKDIR_P) --
3842 $(FOO)} if @var{FOO} might yield a value that begins with @samp{-}.
3843 Finally, @code{AS_MKDIR_P} does not check for race condition
3844 vulnerability, whereas @code{AC_PROG_MKDIR_P} does.
3846 @samp{@@MKDIR_P@@} is special, as its value may vary for different
3847 configuration files.
3848 @end defmac
3850 @anchor{AC_PROG_LEX}
3851 @defmac AC_PROG_LEX
3852 @acindex{PROG_LEX}
3853 @ovindex LEX
3854 @ovindex LEXLIB
3855 @cvindex YYTEXT_POINTER
3856 @ovindex LEX_OUTPUT_ROOT
3857 If @code{flex} is found, set output variable @code{LEX} to @samp{flex}
3858 and @code{LEXLIB} to @option{-lfl}, if that library is in a standard
3859 place.  Otherwise set @code{LEX} to @samp{lex} and @code{LEXLIB} to
3860 @option{-ll}.
3862 Define @code{YYTEXT_POINTER} if @code{yytext} defaults to @samp{char *} instead
3863 of to @samp{char []}.  Also set output variable @code{LEX_OUTPUT_ROOT} to
3864 the base of the file name that the lexer generates; usually
3865 @file{lex.yy}, but sometimes something else.  These results vary
3866 according to whether @code{lex} or @code{flex} is being used.
3868 You are encouraged to use Flex in your sources, since it is both more
3869 pleasant to use than plain Lex and the C source it produces is portable.
3870 In order to ensure portability, however, you must either provide a
3871 function @code{yywrap} or, if you don't use it (e.g., your scanner has
3872 no @samp{#include}-like feature), simply include a @samp{%noyywrap}
3873 statement in the scanner's source.  Once this done, the scanner is
3874 portable (unless @emph{you} felt free to use nonportable constructs) and
3875 does not depend on any library.  In this case, and in this case only, it
3876 is suggested that you use this Autoconf snippet:
3878 @example
3879 AC_PROG_LEX
3880 if test "$LEX" != flex; then
3881   LEX="$SHELL $missing_dir/missing flex"
3882   AC_SUBST([LEX_OUTPUT_ROOT], [lex.yy])
3883   AC_SUBST([LEXLIB], [''])
3885 @end example
3887 The shell script @command{missing} can be found in the Automake
3888 distribution.
3890 To ensure backward compatibility, Automake's @code{AM_PROG_LEX} invokes
3891 (indirectly) this macro twice, which causes an annoying but benign
3892 ``@code{AC_PROG_LEX} invoked multiple times'' warning.  Future versions
3893 of Automake will fix this issue; meanwhile, just ignore this message.
3895 As part of running the test, this macro may delete any file in the
3896 configuration directory named @file{lex.yy.c} or @file{lexyy.c}.
3897 @end defmac
3899 @anchor{AC_PROG_LN_S}
3900 @defmac AC_PROG_LN_S
3901 @acindex{PROG_LN_S}
3902 @ovindex LN_S
3903 If @samp{ln -s} works on the current file system (the operating system
3904 and file system support symbolic links), set the output variable
3905 @code{LN_S} to @samp{ln -s}; otherwise, if @samp{ln} works, set
3906 @code{LN_S} to @samp{ln}, and otherwise set it to @samp{cp -p}.
3908 If you make a link in a directory other than the current directory, its
3909 meaning depends on whether @samp{ln} or @samp{ln -s} is used.  To safely
3910 create links using @samp{$(LN_S)}, either find out which form is used
3911 and adjust the arguments, or always invoke @code{ln} in the directory
3912 where the link is to be created.
3914 In other words, it does not work to do:
3915 @example
3916 $(LN_S) foo /x/bar
3917 @end example
3919 Instead, do:
3921 @example
3922 (cd /x && $(LN_S) foo bar)
3923 @end example
3924 @end defmac
3926 @defmac AC_PROG_RANLIB
3927 @acindex{PROG_RANLIB}
3928 @ovindex RANLIB
3929 Set output variable @code{RANLIB} to @samp{ranlib} if @code{ranlib}
3930 is found, and otherwise to @samp{:} (do nothing).
3931 @end defmac
3933 @defmac AC_PROG_SED
3934 @acindex{PROG_SED}
3935 @ovindex SED
3936 Set output variable @code{SED} to a Sed implementation that conforms to
3937 Posix and does not have arbitrary length limits.  Report an error if no
3938 acceptable Sed is found.  @xref{Limitations of Usual Tools}, for more
3939 information about portability problems with Sed.
3940 @end defmac
3942 @defmac AC_PROG_YACC
3943 @acindex{PROG_YACC}
3944 @ovindex YACC
3945 If @code{bison} is found, set output variable @code{YACC} to @samp{bison
3946 -y}.  Otherwise, if @code{byacc} is found, set @code{YACC} to
3947 @samp{byacc}.  Otherwise set @code{YACC} to @samp{yacc}.
3948 @end defmac
3950 @node Generic Programs
3951 @subsection Generic Program and File Checks
3953 These macros are used to find programs not covered by the ``particular''
3954 test macros.  If you need to check the behavior of a program as well as
3955 find out whether it is present, you have to write your own test for it
3956 (@pxref{Writing Tests}).  By default, these macros use the environment
3957 variable @env{PATH}.  If you need to check for a program that might not
3958 be in the user's @env{PATH}, you can pass a modified path to use
3959 instead, like this:
3961 @example
3962 AC_PATH_PROG([INETD], [inetd], [/usr/libexec/inetd],
3963              [$PATH$PATH_SEPARATOR/usr/libexec$PATH_SEPARATOR]dnl
3964 [/usr/sbin$PATH_SEPARATOR/usr/etc$PATH_SEPARATOR/etc])
3965 @end example
3967 You are strongly encouraged to declare the @var{variable} passed to
3968 @code{AC_CHECK_PROG} etc.@: as precious, @xref{Setting Output Variables},
3969 @code{AC_ARG_VAR}, for more details.
3971 @anchor{AC_CHECK_PROG}
3972 @defmac AC_CHECK_PROG (@var{variable}, @var{prog-to-check-for}, @
3973   @var{value-if-found}, @ovar{value-if-not-found}, @dvar{path, $PATH}, @
3974   @ovar{reject})
3975 @acindex{CHECK_PROG}
3976 Check whether program @var{prog-to-check-for} exists in @var{path}.  If
3977 it is found, set @var{variable} to @var{value-if-found}, otherwise to
3978 @var{value-if-not-found}, if given.  Always pass over @var{reject} (an
3979 absolute file name) even if it is the first found in the search path; in
3980 that case, set @var{variable} using the absolute file name of the
3981 @var{prog-to-check-for} found that is not @var{reject}.  If
3982 @var{variable} was already set, do nothing.  Calls @code{AC_SUBST} for
3983 @var{variable}.
3984 @end defmac
3986 @anchor{AC_CHECK_PROGS}
3987 @defmac AC_CHECK_PROGS (@var{variable}, @var{progs-to-check-for}, @
3988   @ovar{value-if-not-found}, @dvar{path, $PATH})
3989 @acindex{CHECK_PROGS}
3990 Check for each program in the blank-separated list
3991 @var{progs-to-check-for} existing in the @var{path}.  If one is found, set
3992 @var{variable} to the name of that program.  Otherwise, continue
3993 checking the next program in the list.  If none of the programs in the
3994 list are found, set @var{variable} to @var{value-if-not-found}; if
3995 @var{value-if-not-found} is not specified, the value of @var{variable}
3996 is not changed.  Calls @code{AC_SUBST} for @var{variable}.
3997 @end defmac
3999 @defmac AC_CHECK_TARGET_TOOL (@var{variable}, @var{prog-to-check-for}, @
4000   @ovar{value-if-not-found}, @dvar{path, $PATH})
4001 @acindex{CHECK_TARGET_TOOL}
4002 Like @code{AC_CHECK_PROG}, but first looks for @var{prog-to-check-for}
4003 with a prefix of the target type as determined by
4004 @code{AC_CANONICAL_TARGET}, followed by a dash (@pxref{Canonicalizing}).
4005 If the tool cannot be found with a prefix, and if the build and target
4006 types are equal, then it is also searched for without a prefix.
4008 As noted in @ref{Specifying Names, , Specifying the system type}, the
4009 target is rarely specified, because most of the time it is the same
4010 as the host: it is the type of system for which any compiler tool in
4011 the package produces code.  What this macro looks for is,
4012 for example, @emph{a tool @r{(assembler, linker, etc.)}@: that the
4013 compiler driver @r{(@command{gcc} for the @acronym{GNU} C Compiler)}
4014 uses to produce objects, archives or executables}.
4015 @end defmac
4017 @defmac AC_CHECK_TOOL (@var{variable}, @var{prog-to-check-for}, @
4018   @ovar{value-if-not-found}, @dvar{path, $PATH})
4019 @acindex{CHECK_TOOL}
4020 Like @code{AC_CHECK_PROG}, but first looks for @var{prog-to-check-for}
4021 with a prefix of the host type as specified by @option{--host}, followed by a
4022 dash.  For example, if the user runs
4023 @samp{configure --build=x86_64-gnu --host=i386-gnu}, then this call:
4024 @example
4025 AC_CHECK_TOOL([RANLIB], [ranlib], [:])
4026 @end example
4027 @noindent
4028 sets @code{RANLIB} to @file{i386-gnu-ranlib} if that program exists in
4029 @var{path}, or otherwise to @samp{ranlib} if that program exists in
4030 @var{path}, or to @samp{:} if neither program exists.
4032 In the future, when cross-compiling this macro will @emph{only}
4033 accept program names that are prefixed with the host type.
4034 For more information, see @ref{Specifying Names, , Specifying the
4035 system type}.
4036 @end defmac
4038 @defmac AC_CHECK_TARGET_TOOLS (@var{variable}, @var{progs-to-check-for}, @
4039   @ovar{value-if-not-found}, @dvar{path, $PATH})
4040 @acindex{CHECK_TARGET_TOOLS}
4041 Like @code{AC_CHECK_TARGET_TOOL}, each of the tools in the list
4042 @var{progs-to-check-for} are checked with a prefix of the target type as
4043 determined by @code{AC_CANONICAL_TARGET}, followed by a dash
4044 (@pxref{Canonicalizing}).  If none of the tools can be found with a
4045 prefix, and if the build and target types are equal, then the first one
4046 without a prefix is used.  If a tool is found, set @var{variable} to
4047 the name of that program.  If none of the tools in the list are found,
4048 set @var{variable} to @var{value-if-not-found}; if @var{value-if-not-found}
4049 is not specified, the value of @var{variable} is not changed.  Calls
4050 @code{AC_SUBST} for @var{variable}.
4051 @end defmac
4053 @defmac AC_CHECK_TOOLS (@var{variable}, @var{progs-to-check-for}, @
4054   @ovar{value-if-not-found}, @dvar{path, $PATH})
4055 @acindex{CHECK_TOOLS}
4056 Like @code{AC_CHECK_TOOL}, each of the tools in the list
4057 @var{progs-to-check-for} are checked with a prefix of the host type as
4058 determined by @code{AC_CANONICAL_HOST}, followed by a dash
4059 (@pxref{Canonicalizing}).  If none of the tools can be found with a
4060 prefix, then the first one without a prefix is used.  If a tool is found,
4061 set @var{variable} to the name of that program.  If none of the tools in
4062 the list are found, set @var{variable} to @var{value-if-not-found}; if
4063 @var{value-if-not-found} is not specified, the value of @var{variable}
4064 is not changed.  Calls @code{AC_SUBST} for @var{variable}.
4066 In the future, when cross-compiling this macro will @emph{not}
4067 accept program names that are not prefixed with the host type.
4068 @end defmac
4070 @anchor{AC_PATH_PROG}
4071 @defmac AC_PATH_PROG (@var{variable}, @var{prog-to-check-for}, @
4072   @ovar{value-if-not-found}, @dvar{path, $PATH})
4073 @acindex{PATH_PROG}
4074 Like @code{AC_CHECK_PROG}, but set @var{variable} to the absolute
4075 name of @var{prog-to-check-for} if found.
4076 @end defmac
4078 @anchor{AC_PATH_PROGS}
4079 @defmac AC_PATH_PROGS (@var{variable}, @var{progs-to-check-for}, @
4080   @ovar{value-if-not-found}, @dvar{path, $PATH})
4081 @acindex{PATH_PROGS}
4082 Like @code{AC_CHECK_PROGS}, but if any of @var{progs-to-check-for}
4083 are found, set @var{variable} to the absolute name of the program
4084 found.
4085 @end defmac
4087 @defmac AC_PATH_PROGS_FEATURE_CHECK (@var{variable}, @
4088   @var{progs-to-check-for}, @var{feature-test}, @
4089   @ovar{action-if-not-found}, @dvar{path, $PATH})
4090 @acindex{PATH_PROGS_FEATURE_CHECK}
4091 This macro was introduced in Autoconf 2.62.  If @var{variable} is not
4092 empty, then set the cache variable @code{$ac_cv_path_@var{variable}} to
4093 its value.  Otherwise, check for each program in the blank-separated
4094 list @var{progs-to-check-for} existing in @var{path}.  For each program
4095 found, execute @var{feature-test} with @code{$ac_path_@var{variable}}
4096 set to the absolute name of the candidate program.  If no invocation of
4097 @var{feature-test} sets the shell variable
4098 @code{$ac_cv_path_@var{variable}}, then @var{action-if-not-found} is
4099 executed.  @var{feature-test} will be run even when
4100 @code{ac_cv_path_@var{variable}} is set, to provide the ability to
4101 choose a better candidate found later in @var{path}; to accept the
4102 current setting and bypass all futher checks, @var{feature-test} can
4103 execute @code{ac_path_@var{variable}_found=:}.
4105 Note that this macro has some subtle differences from
4106 @code{AC_CHECK_PROGS}.  It is designed to be run inside
4107 @code{AC_CACHE_VAL}, therefore, it should have no side effects.  In
4108 particular, @var{variable} is not set to the final value of
4109 @code{ac_cv_path_@var{variable}}, nor is @code{AC_SUBST} automatically
4110 run.  Also, on failure, any action can be performed, whereas
4111 @code{AC_CHECK_PROGS} only performs
4112 @code{@var{variable}=@var{value-if-not-found}}.
4114 Here is an example, similar to what Autoconf uses in its own configure
4115 script.  It will search for an implementation of @command{m4} that
4116 supports the @code{indir} builtin, even if it goes by the name
4117 @command{gm4} or is not the first implementation on @env{PATH}.
4119 @example
4120 AC_CACHE_CHECK([for m4 that supports indir], [ac_cv_path_M4],
4121   [AC_PATH_PROGS_FEATURE_CHECK([M4], [m4 gm4],
4122     [[m4out=`echo 'changequote([,])indir([divnum])' | $ac_path_M4`
4123       test "x$m4out" = x0 \
4124       && ac_cv_path_M4=$ac_path_M4 ac_path_M4_found=:]],
4125     [AC_MSG_ERROR([could not find m4 that supports indir])])])
4126 AC_SUBST([M4], [$ac_cv_path_M4])
4127 @end example
4128 @end defmac
4130 @defmac AC_PATH_TARGET_TOOL (@var{variable}, @var{prog-to-check-for}, @
4131   @ovar{value-if-not-found}, @dvar{path, $PATH})
4132 @acindex{PATH_TARGET_TOOL}
4133 Like @code{AC_CHECK_TARGET_TOOL}, but set @var{variable} to the absolute
4134 name of the program if it is found.
4135 @end defmac
4137 @defmac AC_PATH_TOOL (@var{variable}, @var{prog-to-check-for}, @
4138   @ovar{value-if-not-found}, @dvar{path, $PATH})
4139 @acindex{PATH_TOOL}
4140 Like @code{AC_CHECK_TOOL}, but set @var{variable} to the absolute
4141 name of the program if it is found.
4143 In the future, when cross-compiling this macro will @emph{not}
4144 accept program names that are not prefixed with the host type.
4145 @end defmac
4148 @node Files
4149 @section Files
4150 @cindex File, checking
4152 You might also need to check for the existence of files.  Before using
4153 these macros, ask yourself whether a runtime test might not be a better
4154 solution.  Be aware that, like most Autoconf macros, they test a feature
4155 of the host machine, and therefore, they die when cross-compiling.
4157 @defmac AC_CHECK_FILE (@var{file}, @ovar{action-if-found}, @
4158   @ovar{action-if-not-found})
4159 @acindex{CHECK_FILE}
4160 Check whether file @var{file} exists on the native system.  If it is
4161 found, execute @var{action-if-found}, otherwise do
4162 @var{action-if-not-found}, if given.
4163 @end defmac
4165 @defmac AC_CHECK_FILES (@var{files}, @ovar{action-if-found}, @
4166   @ovar{action-if-not-found})
4167 @acindex{CHECK_FILES}
4168 Executes @code{AC_CHECK_FILE} once for each file listed in @var{files}.
4169 Additionally, defines @samp{HAVE_@var{file}} (@pxref{Standard Symbols})
4170 for each file found.
4171 @end defmac
4174 @node Libraries
4175 @section Library Files
4176 @cindex Library, checking
4178 The following macros check for the presence of certain C, C++, or Fortran
4179 library archive files.
4181 @anchor{AC_CHECK_LIB}
4182 @defmac AC_CHECK_LIB (@var{library}, @var{function}, @
4183   @ovar{action-if-found}, @ovar{action-if-not-found}, @ovar{other-libraries})
4184 @acindex{CHECK_LIB}
4185 Test whether the library @var{library} is available by trying to link
4186 a test program that calls function @var{function} with the library.
4187 @var{function} should be a function provided by the library.
4188 Use the base
4189 name of the library; e.g., to check for @option{-lmp}, use @samp{mp} as
4190 the @var{library} argument.
4192 @var{action-if-found} is a list of shell commands to run if the link
4193 with the library succeeds; @var{action-if-not-found} is a list of shell
4194 commands to run if the link fails.  If @var{action-if-found} is not
4195 specified, the default action prepends @option{-l@var{library}} to
4196 @code{LIBS} and defines @samp{HAVE_LIB@var{library}} (in all
4197 capitals).  This macro is intended to support building @code{LIBS} in
4198 a right-to-left (least-dependent to most-dependent) fashion such that
4199 library dependencies are satisfied as a natural side effect of
4200 consecutive tests.  Linkers are sensitive to library ordering
4201 so the order in which @code{LIBS} is generated is important to reliable
4202 detection of libraries.
4204 If linking with @var{library} results in unresolved symbols that would
4205 be resolved by linking with additional libraries, give those libraries
4206 as the @var{other-libraries} argument, separated by spaces:
4207 e.g., @option{-lXt -lX11}.  Otherwise, this macro fails to detect
4208 that @var{library} is present, because linking the test program
4209 always fails with unresolved symbols.  The @var{other-libraries} argument
4210 should be limited to cases where it is desirable to test for one library
4211 in the presence of another that is not already in @code{LIBS}.
4213 @code{AC_CHECK_LIB} requires some care in usage, and should be avoided
4214 in some common cases.  Many standard functions like @code{gethostbyname}
4215 appear in the standard C library on some hosts, and in special libraries
4216 like @code{nsl} on other hosts.  On some hosts the special libraries
4217 contain variant implementations that you may not want to use.  These
4218 days it is normally better to use @code{AC_SEARCH_LIBS([gethostbyname],
4219 [nsl])} instead of @code{AC_CHECK_LIB([nsl], [gethostbyname])}.
4220 @end defmac
4222 @anchor{AC_SEARCH_LIBS}
4223 @defmac AC_SEARCH_LIBS (@var{function}, @var{search-libs}, @
4224   @ovar{action-if-found}, @ovar{action-if-not-found}, @ovar{other-libraries})
4225 @acindex{SEARCH_LIBS}
4226 Search for a library defining @var{function} if it's not already
4227 available.  This equates to calling
4228 @samp{AC_LINK_IFELSE([AC_LANG_CALL([], [@var{function}])])} first with
4229 no libraries, then for each library listed in @var{search-libs}.
4231 Add @option{-l@var{library}} to @code{LIBS} for the first library found
4232 to contain @var{function}, and run @var{action-if-found}.  If the
4233 function is not found, run @var{action-if-not-found}.
4235 If linking with @var{library} results in unresolved symbols that would
4236 be resolved by linking with additional libraries, give those libraries
4237 as the @var{other-libraries} argument, separated by spaces:
4238 e.g., @option{-lXt -lX11}.  Otherwise, this macro fails to detect
4239 that @var{function} is present, because linking the test program
4240 always fails with unresolved symbols.
4241 @end defmac
4245 @node Library Functions
4246 @section Library Functions
4248 The following macros check for particular C library functions.
4249 If there is no macro specifically defined to check for a function you need,
4250 and you don't need to check for any special properties of
4251 it, then you can use one of the general function-check macros.
4253 @menu
4254 * Function Portability::        Pitfalls with usual functions
4255 * Particular Functions::        Special handling to find certain functions
4256 * Generic Functions::           How to find other functions
4257 @end menu
4259 @node Function Portability
4260 @subsection Portability of C Functions
4261 @cindex Portability of C functions
4262 @cindex C function portability
4264 Most usual functions can either be missing, or be buggy, or be limited
4265 on some architectures.  This section tries to make an inventory of these
4266 portability issues.  By definition, this list always requires
4267 additions.  Please help us keeping it as complete as possible.
4269 @table @asis
4270 @item @code{exit}
4271 @c @fuindex exit
4272 @prindex @code{exit}
4273 On ancient hosts, @code{exit} returned @code{int}.
4274 This is because @code{exit} predates @code{void}, and there was a long
4275 tradition of it returning @code{int}.
4277 On current hosts, the problem more likely is that @code{exit} is not
4278 declared, due to C++ problems of some sort or another.  For this reason
4279 we suggest that test programs not invoke @code{exit}, but return from
4280 @code{main} instead.
4282 @item @code{free}
4283 @c @fuindex free
4284 @prindex @code{free}
4285 The C standard says a call @code{free (NULL)} does nothing, but
4286 some old systems don't support this (e.g., NextStep).
4288 @item @code{isinf}
4289 @itemx @code{isnan}
4290 @c @fuindex isinf
4291 @c @fuindex isnan
4292 @prindex @code{isinf}
4293 @prindex @code{isnan}
4294 The C99 standard says that @code{isinf} and @code{isnan} are
4295 macros.  On some systems just macros are available
4296 (e.g., @acronym{HP-UX} and Solaris 10), on
4297 some systems both macros and functions (e.g., glibc 2.3.2), and on some
4298 systems only functions (e.g., IRIX 6 and Solaris 9).  In some cases
4299 these functions are declared in nonstandard headers like
4300 @code{<sunmath.h>} and defined in non-default libraries like
4301 @option{-lm} or @option{-lsunmath}.
4303 The C99 @code{isinf} and @code{isnan} macros work correctly with
4304 @code{long double} arguments, but pre-C99 systems that use functions
4305 typically assume @code{double} arguments.  On such a system,
4306 @code{isinf} incorrectly returns true for a finite @code{long double}
4307 argument that is outside the range of @code{double}.
4309 To work around this porting mess, you can use code like the following.
4311 @smallexample
4312 #include <math.h>
4314 #ifndef isnan
4315 # define isnan(x) \
4316     (sizeof (x) == sizeof (long double) ? isnan_ld (x) \
4317      : sizeof (x) == sizeof (double) ? isnan_d (x) \
4318      : isnan_f (x))
4319 static inline int isnan_f  (float       x) @{ return x != x; @}
4320 static inline int isnan_d  (double      x) @{ return x != x; @}
4321 static inline int isnan_ld (long double x) @{ return x != x; @}
4322 #endif
4324 #ifndef isinf
4325 # define isinf(x) \
4326     (sizeof (x) == sizeof (long double) ? isinf_ld (x) \
4327      : sizeof (x) == sizeof (double) ? isinf_d (x) \
4328      : isinf_f (x))
4329 static inline int isinf_f  (float       x) @{ return isnan (x - x); @}
4330 static inline int isinf_d  (double      x) @{ return isnan (x - x); @}
4331 static inline int isinf_ld (long double x) @{ return isnan (x - x); @}
4332 #endif
4333 @end smallexample
4335 Use @code{AC_C_INLINE} (@pxref{C Compiler}) so that this code works on
4336 compilers that lack the @code{inline} keyword.  Some optimizing
4337 compilers mishandle these definitions, but systems with that bug
4338 typically have missing or broken @code{isnan} functions anyway, so it's
4339 probably not worth worrying about.
4341 @item @code{malloc}
4342 @c @fuindex malloc
4343 @prindex @code{malloc}
4344 The C standard says a call @code{malloc (0)} is implementation
4345 dependent.  It can return either @code{NULL} or a new non-null pointer.
4346 The latter is more common (e.g., the @acronym{GNU} C Library) but is by
4347 no means universal.  @code{AC_FUNC_MALLOC}
4348 can be used to insist on non-@code{NULL} (@pxref{Particular Functions}).
4350 @item @code{putenv}
4351 @c @fuindex putenv
4352 @prindex @code{putenv}
4353 Posix prefers @code{setenv} to @code{putenv}; among other things,
4354 @code{putenv} is not required of all Posix implementations, but
4355 @code{setenv} is.
4357 Posix specifies that @code{putenv} puts the given string directly in
4358 @code{environ}, but some systems make a copy of it instead (e.g.,
4359 glibc 2.0, or @acronym{BSD}).  And when a copy is made, @code{unsetenv} might
4360 not free it, causing a memory leak (e.g., Free@acronym{BSD} 4).
4362 On some systems @code{putenv ("FOO")} removes @samp{FOO} from the
4363 environment, but this is not standard usage and it dumps core
4364 on some systems (e.g., AIX).
4366 On MinGW, a call @code{putenv ("FOO=")} removes @samp{FOO} from the
4367 environment, rather than inserting it with an empty value.
4369 @item @code{realloc}
4370 @c @fuindex realloc
4371 @prindex @code{realloc}
4372 The C standard says a call @code{realloc (NULL, size)} is equivalent
4373 to @code{malloc (size)}, but some old systems don't support this (e.g.,
4374 NextStep).
4376 @item @code{signal} handler
4377 @c @fuindex signal
4378 @prindex @code{signal}
4379 @prindex @code{sigaction}
4380 Normally @code{signal} takes a handler function with a return type of
4381 @code{void}, but some old systems required @code{int} instead.  Any
4382 actual @code{int} value returned is not used; this is only a
4383 difference in the function prototype demanded.
4385 All systems we know of in current use return @code{void}.  The
4386 @code{int} was to support K&R C, where of course @code{void} is not
4387 available.  The obsolete macro @code{AC_TYPE_SIGNAL}
4388 (@pxref{AC_TYPE_SIGNAL}) can be used to establish the correct type in
4389 all cases.
4391 In most cases, it is more robust to use @code{sigaction} when it is
4392 available, rather than @code{signal}.
4394 @item @code{snprintf}
4395 @c @fuindex snprintf
4396 @prindex @code{snprintf}
4397 @c @fuindex vsnprintf
4398 @prindex @code{vsnprintf}
4399 The C99 standard says that if the output array isn't big enough
4400 and if no other errors occur, @code{snprintf} and @code{vsnprintf}
4401 truncate the output and return the number of bytes that ought to have
4402 been produced.  Some older systems return the truncated length (e.g.,
4403 @acronym{GNU} C Library 2.0.x or @sc{irix} 6.5), some a negative value
4404 (e.g., earlier @acronym{GNU} C Library versions), and some the buffer
4405 length without truncation (e.g., 32-bit Solaris 7).  Also, some buggy
4406 older systems ignore the length and overrun the buffer (e.g., 64-bit
4407 Solaris 7).
4409 @item @code{sprintf}
4410 @c @fuindex sprintf
4411 @prindex @code{sprintf}
4412 @c @fuindex vsprintf
4413 @prindex @code{vsprintf}
4414 The C standard says @code{sprintf} and @code{vsprintf} return the
4415 number of bytes written.  On some ancient systems (SunOS 4 for
4416 instance) they return the buffer pointer instead, but these no
4417 longer need to be worried about.
4419 @item @code{sscanf}
4420 @c @fuindex sscanf
4421 @prindex @code{sscanf}
4422 On various old systems, e.g., @acronym{HP-UX} 9, @code{sscanf} requires
4423 that its
4424 input string be writable (though it doesn't actually change it).  This
4425 can be a problem when using @command{gcc} since it normally puts
4426 constant strings in read-only memory (@pxref{Incompatibilities,
4427 Incompatibilities of @acronym{GCC}, , gcc, Using and
4428 Porting the @acronym{GNU} Compiler Collection}).  Apparently in some cases even
4429 having format strings read-only can be a problem.
4431 @item @code{strerror_r}
4432 @c @fuindex strerror_r
4433 @prindex @code{strerror_r}
4434 Posix specifies that @code{strerror_r} returns an @code{int}, but many
4435 systems (e.g., @acronym{GNU} C Library version 2.2.4) provide a
4436 different version returning a @code{char *}.  @code{AC_FUNC_STRERROR_R}
4437 can detect which is in use (@pxref{Particular Functions}).
4439 @item @code{strnlen}
4440 @c @fuindex strnlen
4441 @prindex @code{strnlen}
4442 @acronym{AIX} 4.3 provides a broken version which produces the
4443 following results:
4445 @example
4446 strnlen ("foobar", 0) = 0
4447 strnlen ("foobar", 1) = 3
4448 strnlen ("foobar", 2) = 2
4449 strnlen ("foobar", 3) = 1
4450 strnlen ("foobar", 4) = 0
4451 strnlen ("foobar", 5) = 6
4452 strnlen ("foobar", 6) = 6
4453 strnlen ("foobar", 7) = 6
4454 strnlen ("foobar", 8) = 6
4455 strnlen ("foobar", 9) = 6
4456 @end example
4458 @item @code{sysconf}
4459 @c @fuindex sysconf
4460 @prindex @code{sysconf}
4461 @code{_SC_PAGESIZE} is standard, but some older systems (e.g., @acronym{HP-UX}
4462 9) have @code{_SC_PAGE_SIZE} instead.  This can be tested with
4463 @code{#ifdef}.
4465 @item @code{unlink}
4466 @c @fuindex unlink
4467 @prindex @code{unlink}
4468 The Posix spec says that @code{unlink} causes the given file to be
4469 removed only after there are no more open file handles for it.  Some
4470 non-Posix hosts have trouble with this requirement, though,
4471 and some @acronym{DOS} variants even corrupt the file system.
4473 @item @code{unsetenv}
4474 @c @fuindex unsetenv
4475 @prindex @code{unsetenv}
4476 On MinGW, @code{unsetenv} is not available, but a variable @samp{FOO}
4477 can be removed with a call @code{putenv ("FOO=")}, as described under
4478 @code{putenv} above.
4480 @item @code{va_copy}
4481 @c @fuindex va_copy
4482 @prindex @code{va_copy}
4483 The C99 standard provides @code{va_copy} for copying
4484 @code{va_list} variables.  It may be available in older environments
4485 too, though possibly as @code{__va_copy} (e.g., @command{gcc} in strict
4486 pre-C99 mode).  These can be tested with @code{#ifdef}.  A fallback to
4487 @code{memcpy (&dst, &src, sizeof (va_list))} gives maximum
4488 portability.
4490 @item @code{va_list}
4491 @c @fuindex va_list
4492 @prindex @code{va_list}
4493 @code{va_list} is not necessarily just a pointer.  It can be a
4494 @code{struct} (e.g., @command{gcc} on Alpha), which means @code{NULL} is
4495 not portable.  Or it can be an array (e.g., @command{gcc} in some
4496 PowerPC configurations), which means as a function parameter it can be
4497 effectively call-by-reference and library routines might modify the
4498 value back in the caller (e.g., @code{vsnprintf} in the @acronym{GNU} C Library
4499 2.1).
4501 @item Signed @code{>>}
4502 Normally the C @code{>>} right shift of a signed type replicates the
4503 high bit, giving a so-called ``arithmetic'' shift.  But care should be
4504 taken since Standard C doesn't require that behavior.  On those
4505 few processors without a native arithmetic shift (for instance Cray
4506 vector systems) zero bits may be shifted in, the same as a shift of an
4507 unsigned type.
4509 @item Integer @code{/}
4510 C divides signed integers by truncating their quotient toward zero,
4511 yielding the same result as Fortran.  However, before C99 the standard
4512 allowed C implementations to take the floor or ceiling of the quotient
4513 in some cases.  Hardly any implementations took advantage of this
4514 freedom, though, and it's probably not worth worrying about this issue
4515 nowadays.
4516 @end table
4519 @node Particular Functions
4520 @subsection Particular Function Checks
4521 @cindex Function, checking
4523 These macros check for particular C functions---whether they exist, and
4524 in some cases how they respond when given certain arguments.
4526 @anchor{AC_FUNC_ALLOCA}
4527 @defmac AC_FUNC_ALLOCA
4528 @acindex{FUNC_ALLOCA}
4529 @cvindex C_ALLOCA
4530 @cvindex HAVE_ALLOCA_H
4531 @ovindex ALLOCA
4532 @c @fuindex alloca
4533 @prindex @code{alloca}
4534 @hdrindex{alloca.h}
4535 Check how to get @code{alloca}.  Tries to get a builtin version by
4536 checking for @file{alloca.h} or the predefined C preprocessor macros
4537 @code{__GNUC__} and @code{_AIX}.  If this macro finds @file{alloca.h},
4538 it defines @code{HAVE_ALLOCA_H}.
4540 If those attempts fail, it looks for the function in the standard C
4541 library.  If any of those methods succeed, it defines
4542 @code{HAVE_ALLOCA}.  Otherwise, it sets the output variable
4543 @code{ALLOCA} to @samp{$@{LIBOBJDIR@}alloca.o} and defines
4544 @code{C_ALLOCA} (so programs can periodically call @samp{alloca (0)} to
4545 garbage collect).  This variable is separate from @code{LIBOBJS} so
4546 multiple programs can share the value of @code{ALLOCA} without needing
4547 to create an actual library, in case only some of them use the code in
4548 @code{LIBOBJS}.  The @samp{$@{LIBOBJDIR@}} prefix serves the same
4549 purpose as in @code{LIBOBJS} (@pxref{AC_LIBOBJ vs LIBOBJS}).
4551 This macro does not try to get @code{alloca} from the System V R3
4552 @file{libPW} or the System V R4 @file{libucb} because those libraries
4553 contain some incompatible functions that cause trouble.  Some versions
4554 do not even contain @code{alloca} or contain a buggy version.  If you
4555 still want to use their @code{alloca}, use @code{ar} to extract
4556 @file{alloca.o} from them instead of compiling @file{alloca.c}.
4558 Source files that use @code{alloca} should start with a piece of code
4559 like the following, to declare it properly.
4561 @example
4562 @group
4563 #ifdef HAVE_ALLOCA_H
4564 # include <alloca.h>
4565 #elif defined __GNUC__
4566 # define alloca __builtin_alloca
4567 #elif defined _AIX
4568 # define alloca __alloca
4569 #elif defined _MSC_VER
4570 # include <malloc.h>
4571 # define alloca _alloca
4572 #else
4573 # include <stddef.h>
4574 # ifdef  __cplusplus
4575 extern "C"
4576 # endif
4577 void *alloca (size_t);
4578 #endif
4579 @end group
4580 @end example
4581 @end defmac
4583 @defmac AC_FUNC_CHOWN
4584 @acindex{FUNC_CHOWN}
4585 @cvindex HAVE_CHOWN
4586 @c @fuindex chown
4587 @prindex @code{chown}
4588 If the @code{chown} function is available and works (in particular, it
4589 should accept @option{-1} for @code{uid} and @code{gid}), define
4590 @code{HAVE_CHOWN}.
4591 @end defmac
4593 @anchor{AC_FUNC_CLOSEDIR_VOID}
4594 @defmac AC_FUNC_CLOSEDIR_VOID
4595 @acindex{FUNC_CLOSEDIR_VOID}
4596 @cvindex CLOSEDIR_VOID
4597 @c @fuindex closedir
4598 @prindex @code{closedir}
4599 If the @code{closedir} function does not return a meaningful value,
4600 define @code{CLOSEDIR_VOID}.  Otherwise, callers ought to check its
4601 return value for an error indicator.
4603 Currently this test is implemented by running a test program.  When
4604 cross compiling the pessimistic assumption that @code{closedir} does not
4605 return a meaningful value is made.
4607 This macro is obsolescent, as @code{closedir} returns a meaningful value
4608 on current systems.  New programs need not use this macro.
4609 @end defmac
4611 @defmac AC_FUNC_ERROR_AT_LINE
4612 @acindex{FUNC_ERROR_AT_LINE}
4613 @c @fuindex error_at_line
4614 @prindex @code{error_at_line}
4615 If the @code{error_at_line} function is not found, require an
4616 @code{AC_LIBOBJ} replacement of @samp{error}.
4617 @end defmac
4619 @defmac AC_FUNC_FNMATCH
4620 @acindex{FUNC_FNMATCH}
4621 @c @fuindex fnmatch
4622 @prindex @code{fnmatch}
4623 If the @code{fnmatch} function conforms to Posix, define
4624 @code{HAVE_FNMATCH}.  Detect common implementation bugs, for example,
4625 the bugs in Solaris 2.4.
4627 Unlike the other specific
4628 @code{AC_FUNC} macros, @code{AC_FUNC_FNMATCH} does not replace a
4629 broken/missing @code{fnmatch}.  This is for historical reasons.
4630 See @code{AC_REPLACE_FNMATCH} below.
4632 This macro is obsolescent.  New programs should use Gnulib's
4633 @code{fnmatch-posix} module.  @xref{Gnulib}.
4634 @end defmac
4636 @defmac AC_FUNC_FNMATCH_GNU
4637 @acindex{FUNC_FNMATCH_GNU}
4638 @c @fuindex fnmatch
4639 @prindex @code{fnmatch}
4640 Behave like @code{AC_REPLACE_FNMATCH} (@emph{replace}) but also test
4641 whether @code{fnmatch} supports @acronym{GNU} extensions.  Detect common
4642 implementation bugs, for example, the bugs in the @acronym{GNU} C
4643 Library 2.1.
4645 This macro is obsolescent.  New programs should use Gnulib's
4646 @code{fnmatch-gnu} module.  @xref{Gnulib}.
4647 @end defmac
4649 @anchor{AC_FUNC_FORK}
4650 @defmac AC_FUNC_FORK
4651 @acindex{FUNC_FORK}
4652 @cvindex HAVE_VFORK_H
4653 @cvindex HAVE_WORKING_FORK
4654 @cvindex HAVE_WORKING_VFORK
4655 @cvindex vfork
4656 @c @fuindex fork
4657 @prindex @code{fork}
4658 @c @fuindex vfork
4659 @prindex @code{vfork}
4660 @hdrindex{vfork.h}
4661 This macro checks for the @code{fork} and @code{vfork} functions.  If a
4662 working @code{fork} is found, define @code{HAVE_WORKING_FORK}.  This macro
4663 checks whether @code{fork} is just a stub by trying to run it.
4665 If @file{vfork.h} is found, define @code{HAVE_VFORK_H}.  If a working
4666 @code{vfork} is found, define @code{HAVE_WORKING_VFORK}.  Otherwise,
4667 define @code{vfork} to be @code{fork} for backward compatibility with
4668 previous versions of @command{autoconf}.  This macro checks for several known
4669 errors in implementations of @code{vfork} and considers the system to not
4670 have a working @code{vfork} if it detects any of them.  It is not considered
4671 to be an implementation error if a child's invocation of @code{signal}
4672 modifies the parent's signal handler, since child processes rarely change
4673 their signal handlers.
4675 Since this macro defines @code{vfork} only for backward compatibility with
4676 previous versions of @command{autoconf} you're encouraged to define it
4677 yourself in new code:
4678 @example
4679 @group
4680 #ifndef HAVE_WORKING_VFORK
4681 # define vfork fork
4682 #endif
4683 @end group
4684 @end example
4685 @end defmac
4687 @defmac AC_FUNC_FSEEKO
4688 @acindex{FUNC_FSEEKO}
4689 @cvindex _LARGEFILE_SOURCE
4690 @cvindex HAVE_FSEEKO
4691 @c @fuindex fseeko
4692 @prindex @code{fseeko}
4693 If the @code{fseeko} function is available, define @code{HAVE_FSEEKO}.
4694 Define @code{_LARGEFILE_SOURCE} if necessary to make the prototype
4695 visible on some systems (e.g., glibc 2.2).  Otherwise linkage problems
4696 may occur when compiling with @code{AC_SYS_LARGEFILE} on
4697 largefile-sensitive systems where @code{off_t} does not default to a
4698 64bit entity.
4699 @end defmac
4701 @defmac AC_FUNC_GETGROUPS
4702 @acindex{FUNC_GETGROUPS}
4703 @cvindex HAVE_GETGROUPS
4704 @ovindex GETGROUPS_LIBS
4705 @c @fuindex getgroups
4706 @prindex @code{getgroups}
4707 If the @code{getgroups} function is available and works (unlike on
4708 Ultrix 4.3, where @samp{getgroups (0, 0)} always fails), define
4709 @code{HAVE_GETGROUPS}.  Set @code{GETGROUPS_LIBS} to any libraries
4710 needed to get that function.  This macro runs @code{AC_TYPE_GETGROUPS}.
4711 @end defmac
4713 @anchor{AC_FUNC_GETLOADAVG}
4714 @defmac AC_FUNC_GETLOADAVG
4715 @acindex{FUNC_GETLOADAVG}
4716 @cvindex SVR4
4717 @cvindex DGUX
4718 @cvindex UMAX
4719 @cvindex UMAX4_3
4720 @cvindex HAVE_NLIST_H
4721 @cvindex NLIST_NAME_UNION
4722 @cvindex GETLOADAVG_PRIVILEGED
4723 @cvindex NEED_SETGID
4724 @cvindex C_GETLOADAVG
4725 @ovindex LIBOBJS
4726 @ovindex NEED_SETGID
4727 @ovindex KMEM_GROUP
4728 @ovindex GETLOADAVG_LIBS
4729 @c @fuindex getloadavg
4730 @prindex @code{getloadavg}
4731 Check how to get the system load averages.  To perform its tests
4732 properly, this macro needs the file @file{getloadavg.c}; therefore, be
4733 sure to set the @code{AC_LIBOBJ} replacement directory properly (see
4734 @ref{Generic Functions}, @code{AC_CONFIG_LIBOBJ_DIR}).
4736 If the system has the @code{getloadavg} function, define
4737 @code{HAVE_GETLOADAVG}, and set @code{GETLOADAVG_LIBS} to any libraries
4738 necessary to get that function.  Also add @code{GETLOADAVG_LIBS} to
4739 @code{LIBS}.  Otherwise, require an @code{AC_LIBOBJ} replacement for
4740 @samp{getloadavg} with source code in @file{@var{dir}/getloadavg.c}, and
4741 possibly define several other C preprocessor macros and output
4742 variables:
4744 @enumerate
4745 @item
4746 Define @code{C_GETLOADAVG}.
4748 @item
4749 Define @code{SVR4}, @code{DGUX}, @code{UMAX}, or @code{UMAX4_3} if on
4750 those systems.
4752 @item
4753 @hdrindex{nlist.h}
4754 If @file{nlist.h} is found, define @code{HAVE_NLIST_H}.
4756 @item
4757 If @samp{struct nlist} has an @samp{n_un.n_name} member, define
4758 @code{HAVE_STRUCT_NLIST_N_UN_N_NAME}.  The obsolete symbol
4759 @code{NLIST_NAME_UNION} is still defined, but do not depend upon it.
4761 @item
4762 Programs may need to be installed set-group-ID (or set-user-ID) for
4763 @code{getloadavg} to work.  In this case, define
4764 @code{GETLOADAVG_PRIVILEGED}, set the output variable @code{NEED_SETGID}
4765 to @samp{true} (and otherwise to @samp{false}), and set
4766 @code{KMEM_GROUP} to the name of the group that should own the installed
4767 program.
4768 @end enumerate
4770 The @code{AC_FUNC_GETLOADAVG} macro is obsolescent.  New programs should
4771 use Gnulib's @code{getloadavg} module.  @xref{Gnulib}.
4772 @end defmac
4774 @anchor{AC_FUNC_GETMNTENT}
4775 @defmac AC_FUNC_GETMNTENT
4776 @acindex{FUNC_GETMNTENT}
4777 @cvindex HAVE_GETMNTENT
4778 @c @fuindex getmntent
4779 @prindex @code{getmntent}
4780 Check for @code{getmntent} in the standard C library, and then in the
4781 @file{sun}, @file{seq}, and @file{gen} libraries, for @sc{unicos},
4782 @sc{irix} 4, @sc{ptx}, and UnixWare, respectively.  Then, if
4783 @code{getmntent} is available, define @code{HAVE_GETMNTENT}.
4784 @end defmac
4786 @defmac AC_FUNC_GETPGRP
4787 @acindex{FUNC_GETPGRP}
4788 @cvindex GETPGRP_VOID
4789 @c @fuindex getpgid
4790 @c @fuindex getpgrp
4791 @prindex @code{getpgid}
4792 @prindex @code{getpgrp}
4793 Define @code{GETPGRP_VOID} if it is an error to pass 0 to
4794 @code{getpgrp}; this is the Posix behavior.  On older @acronym{BSD}
4795 systems, you must pass 0 to @code{getpgrp}, as it takes an argument and
4796 behaves like Posix's @code{getpgid}.
4798 @example
4799 #ifdef GETPGRP_VOID
4800   pid = getpgrp ();
4801 #else
4802   pid = getpgrp (0);
4803 #endif
4804 @end example
4806 This macro does not check whether
4807 @code{getpgrp} exists at all; if you need to work in that situation,
4808 first call @code{AC_CHECK_FUNC} for @code{getpgrp}.
4810 This macro is obsolescent, as current systems have a @code{getpgrp}
4811 whose signature conforms to Posix.  New programs need not use this macro.
4812 @end defmac
4814 @defmac AC_FUNC_LSTAT_FOLLOWS_SLASHED_SYMLINK
4815 @acindex{FUNC_LSTAT_FOLLOWS_SLASHED_SYMLINK}
4816 @cvindex LSTAT_FOLLOWS_SLASHED_SYMLINK
4817 @c @fuindex lstat
4818 @prindex @code{lstat}
4819 If @file{link} is a symbolic link, then @code{lstat} should treat
4820 @file{link/} the same as @file{link/.}.  However, many older
4821 @code{lstat} implementations incorrectly ignore trailing slashes.
4823 It is safe to assume that if @code{lstat} incorrectly ignores
4824 trailing slashes, then other symbolic-link-aware functions like
4825 @code{unlink} also incorrectly ignore trailing slashes.
4827 If @code{lstat} behaves properly, define
4828 @code{LSTAT_FOLLOWS_SLASHED_SYMLINK}, otherwise require an
4829 @code{AC_LIBOBJ} replacement of @code{lstat}.
4830 @end defmac
4832 @defmac AC_FUNC_MALLOC
4833 @acindex{FUNC_MALLOC}
4834 @cvindex HAVE_MALLOC
4835 @cvindex malloc
4836 @c @fuindex malloc
4837 @prindex @code{malloc}
4838 If the @code{malloc} function is compatible with the @acronym{GNU} C
4839 library @code{malloc} (i.e., @samp{malloc (0)} returns a valid
4840 pointer), define @code{HAVE_MALLOC} to 1.  Otherwise define
4841 @code{HAVE_MALLOC} to 0, ask for an @code{AC_LIBOBJ} replacement for
4842 @samp{malloc}, and define @code{malloc} to @code{rpl_malloc} so that the
4843 native @code{malloc} is not used in the main project.
4845 Typically, the replacement file @file{malloc.c} should look like (note
4846 the @samp{#undef malloc}):
4848 @verbatim
4849 #include <config.h>
4850 #undef malloc
4852 #include <sys/types.h>
4854 void *malloc ();
4856 /* Allocate an N-byte block of memory from the heap.
4857    If N is zero, allocate a 1-byte block.  */
4859 void *
4860 rpl_malloc (size_t n)
4862   if (n == 0)
4863     n = 1;
4864   return malloc (n);
4866 @end verbatim
4867 @end defmac
4869 @defmac AC_FUNC_MEMCMP
4870 @acindex{FUNC_MEMCMP}
4871 @ovindex LIBOBJS
4872 @c @fuindex memcmp
4873 @prindex @code{memcmp}
4874 If the @code{memcmp} function is not available, or does not work on
4875 8-bit data (like the one on SunOS 4.1.3), or fails when comparing 16
4876 bytes or more and with at least one buffer not starting on a 4-byte
4877 boundary (such as the one on NeXT x86 OpenStep), require an
4878 @code{AC_LIBOBJ} replacement for @samp{memcmp}.
4880 This macro is obsolescent, as current systems have a working
4881 @code{memcmp}.  New programs need not use this macro.
4882 @end defmac
4884 @defmac AC_FUNC_MBRTOWC
4885 @acindex{FUNC_MBRTOWC}
4886 @cvindex HAVE_MBRTOWC
4887 @c @fuindex mbrtowc
4888 @prindex @code{mbrtowc}
4889 Define @code{HAVE_MBRTOWC} to 1 if the function @code{mbrtowc} and the
4890 type @code{mbstate_t} are properly declared.
4891 @end defmac
4893 @defmac AC_FUNC_MKTIME
4894 @acindex{FUNC_MKTIME}
4895 @ovindex LIBOBJS
4896 @c @fuindex mktime
4897 @prindex @code{mktime}
4898 If the @code{mktime} function is not available, or does not work
4899 correctly, require an @code{AC_LIBOBJ} replacement for @samp{mktime}.
4900 For the purposes of this test, @code{mktime} should conform to the
4901 Posix standard and should be the inverse of
4902 @code{localtime}.
4903 @end defmac
4905 @anchor{AC_FUNC_MMAP}
4906 @defmac AC_FUNC_MMAP
4907 @acindex{FUNC_MMAP}
4908 @cvindex HAVE_MMAP
4909 @c @fuindex mmap
4910 @prindex @code{mmap}
4911 If the @code{mmap} function exists and works correctly, define
4912 @code{HAVE_MMAP}.  This checks only private fixed mapping of already-mapped
4913 memory.
4914 @end defmac
4916 @defmac AC_FUNC_OBSTACK
4917 @acindex{FUNC_OBSTACK}
4918 @cvindex HAVE_OBSTACK
4919 @cindex obstack
4920 If the obstacks are found, define @code{HAVE_OBSTACK}, else require an
4921 @code{AC_LIBOBJ} replacement for @samp{obstack}.
4922 @end defmac
4924 @defmac AC_FUNC_REALLOC
4925 @acindex{FUNC_REALLOC}
4926 @cvindex HAVE_REALLOC
4927 @cvindex realloc
4928 @c @fuindex realloc
4929 @prindex @code{realloc}
4930 If the @code{realloc} function is compatible with the @acronym{GNU} C
4931 library @code{realloc} (i.e., @samp{realloc (NULL, 0)} returns a
4932 valid pointer), define @code{HAVE_REALLOC} to 1.  Otherwise define
4933 @code{HAVE_REALLOC} to 0, ask for an @code{AC_LIBOBJ} replacement for
4934 @samp{realloc}, and define @code{realloc} to @code{rpl_realloc} so that
4935 the native @code{realloc} is not used in the main project.  See
4936 @code{AC_FUNC_MALLOC} for details.
4937 @end defmac
4939 @defmac AC_FUNC_SELECT_ARGTYPES
4940 @acindex{FUNC_SELECT_ARGTYPES}
4941 @cvindex SELECT_TYPE_ARG1
4942 @cvindex SELECT_TYPE_ARG234
4943 @cvindex SELECT_TYPE_ARG5
4944 @c @fuindex select
4945 @prindex @code{select}
4946 Determines the correct type to be passed for each of the
4947 @code{select} function's arguments, and defines those types
4948 in @code{SELECT_TYPE_ARG1}, @code{SELECT_TYPE_ARG234}, and
4949 @code{SELECT_TYPE_ARG5} respectively.  @code{SELECT_TYPE_ARG1} defaults
4950 to @samp{int}, @code{SELECT_TYPE_ARG234} defaults to @samp{int *},
4951 and @code{SELECT_TYPE_ARG5} defaults to @samp{struct timeval *}.
4953 This macro is obsolescent, as current systems have a @code{select} whose
4954 signature conforms to Posix.  New programs need not use this macro.
4955 @end defmac
4957 @defmac AC_FUNC_SETPGRP
4958 @acindex{FUNC_SETPGRP}
4959 @cvindex SETPGRP_VOID
4960 @c @fuindex setpgrp
4961 @prindex @code{setpgrp}
4962 If @code{setpgrp} takes no argument (the Posix version), define
4963 @code{SETPGRP_VOID}.  Otherwise, it is the @acronym{BSD} version, which takes
4964 two process IDs as arguments.  This macro does not check whether
4965 @code{setpgrp} exists at all; if you need to work in that situation,
4966 first call @code{AC_CHECK_FUNC} for @code{setpgrp}.
4968 This macro is obsolescent, as current systems have a @code{setpgrp}
4969 whose signature conforms to Posix.  New programs need not use this macro.
4970 @end defmac
4972 @defmac AC_FUNC_STAT
4973 @defmacx AC_FUNC_LSTAT
4974 @acindex{FUNC_STAT}
4975 @acindex{FUNC_LSTAT}
4976 @cvindex HAVE_STAT_EMPTY_STRING_BUG
4977 @cvindex HAVE_LSTAT_EMPTY_STRING_BUG
4978 @c @fuindex stat
4979 @prindex @code{stat}
4980 @c @fuindex lstat
4981 @prindex @code{lstat}
4982 Determine whether @code{stat} or @code{lstat} have the bug that it
4983 succeeds when given the zero-length file name as argument.  The @code{stat}
4984 and @code{lstat} from SunOS 4.1.4 and the Hurd (as of 1998-11-01) do
4985 this.
4987 If it does, then define @code{HAVE_STAT_EMPTY_STRING_BUG} (or
4988 @code{HAVE_LSTAT_EMPTY_STRING_BUG}) and ask for an @code{AC_LIBOBJ}
4989 replacement of it.
4991 These macros are obsolescent, as no current systems have the bug.
4992 New programs need not use these macros.
4993 @end defmac
4995 @anchor{AC_FUNC_STRCOLL}
4996 @defmac AC_FUNC_STRCOLL
4997 @acindex{FUNC_STRCOLL}
4998 @cvindex HAVE_STRCOLL
4999 @c @fuindex strcoll
5000 @prindex @code{strcoll}
5001 If the @code{strcoll} function exists and works correctly, define
5002 @code{HAVE_STRCOLL}.  This does a bit more than
5003 @samp{AC_CHECK_FUNCS(strcoll)}, because some systems have incorrect
5004 definitions of @code{strcoll} that should not be used.
5005 @end defmac
5007 @defmac AC_FUNC_STRERROR_R
5008 @acindex{FUNC_STRERROR_R}
5009 @cvindex HAVE_STRERROR_R
5010 @cvindex HAVE_DECL_STRERROR_R
5011 @cvindex STRERROR_R_CHAR_P
5012 @c @fuindex strerror_r
5013 @prindex @code{strerror_r}
5014 If @code{strerror_r} is available, define @code{HAVE_STRERROR_R}, and if
5015 it is declared, define @code{HAVE_DECL_STRERROR_R}.  If it returns a
5016 @code{char *} message, define @code{STRERROR_R_CHAR_P}; otherwise it
5017 returns an @code{int} error number.  The Thread-Safe Functions option of
5018 Posix requires @code{strerror_r} to return @code{int}, but
5019 many systems (including, for example, version 2.2.4 of the @acronym{GNU} C
5020 Library) return a @code{char *} value that is not necessarily equal to
5021 the buffer argument.
5022 @end defmac
5024 @anchor{AC_FUNC_STRFTIME}
5025 @defmac AC_FUNC_STRFTIME
5026 @acindex{FUNC_STRFTIME}
5027 @cvindex HAVE_STRFTIME
5028 @c @fuindex strftime
5029 @prindex @code{strftime}
5030 Check for @code{strftime} in the @file{intl} library, for SCO Unix.
5031 Then, if @code{strftime} is available, define @code{HAVE_STRFTIME}.
5033 This macro is obsolescent, as no current systems require the @file{intl}
5034 library for @code{strftime}.  New programs need not use this macro.
5035 @end defmac
5037 @defmac AC_FUNC_STRTOD
5038 @acindex{FUNC_STRTOD}
5039 @ovindex POW_LIB
5040 @c @fuindex strtod
5041 @prindex @code{strtod}
5042 If the @code{strtod} function does not exist or doesn't work correctly,
5043 ask for an @code{AC_LIBOBJ} replacement of @samp{strtod}.  In this case,
5044 because @file{strtod.c} is likely to need @samp{pow}, set the output
5045 variable @code{POW_LIB} to the extra library needed.
5046 @end defmac
5048 @defmac AC_FUNC_STRTOLD
5049 @acindex{FUNC_STRTOLD}
5050 @cvindex HAVE_STRTOLD
5051 @prindex @code{strtold}
5052 If the @code{strtold} function exists and conforms to C99, define
5053 @code{HAVE_STRTOLD}.
5054 @end defmac
5056 @defmac AC_FUNC_STRNLEN
5057 @acindex{FUNC_STRNLEN}
5058 @cvindex HAVE_STRNLEN
5059 @c @fuindex strnlen
5060 @prindex @code{strnlen}
5061 If the @code{strnlen} function is not available, or is buggy (like the one
5062 from @acronym{AIX} 4.3), require an @code{AC_LIBOBJ} replacement for it.
5063 @end defmac
5065 @anchor{AC_FUNC_UTIME_NULL}
5066 @defmac AC_FUNC_UTIME_NULL
5067 @acindex{FUNC_UTIME_NULL}
5068 @cvindex HAVE_UTIME_NULL
5069 @c @fuindex utime
5070 @prindex @code{utime}
5071 If @samp{utime (@var{file}, NULL)} sets @var{file}'s timestamp to
5072 the present, define @code{HAVE_UTIME_NULL}.
5074 This macro is obsolescent, as all current systems have a @code{utime}
5075 that behaves this way.  New programs need not use this macro.
5076 @end defmac
5078 @anchor{AC_FUNC_VPRINTF}
5079 @defmac AC_FUNC_VPRINTF
5080 @acindex{FUNC_VPRINTF}
5081 @cvindex HAVE_VPRINTF
5082 @cvindex HAVE_DOPRNT
5083 @c @fuindex vprintf
5084 @prindex @code{vprintf}
5085 If @code{vprintf} is found, define @code{HAVE_VPRINTF}.  Otherwise, if
5086 @code{_doprnt} is found, define @code{HAVE_DOPRNT}.  (If @code{vprintf}
5087 is available, you may assume that @code{vfprintf} and @code{vsprintf}
5088 are also available.)
5090 This macro is obsolescent, as all current systems have @code{vprintf}.
5091 New programs need not use this macro.
5092 @end defmac
5094 @defmac AC_REPLACE_FNMATCH
5095 @acindex{REPLACE_FNMATCH}
5096 @c @fuindex fnmatch
5097 @prindex @code{fnmatch}
5098 @hdrindex{fnmatch.h}
5099 If the @code{fnmatch} function does not conform to Posix (see
5100 @code{AC_FUNC_FNMATCH}), ask for its @code{AC_LIBOBJ} replacement.
5102 The files @file{fnmatch.c}, @file{fnmatch_loop.c}, and @file{fnmatch_.h}
5103 in the @code{AC_LIBOBJ} replacement directory are assumed to contain a
5104 copy of the source code of @acronym{GNU} @code{fnmatch}.  If necessary,
5105 this source code is compiled as an @code{AC_LIBOBJ} replacement, and the
5106 @file{fnmatch_.h} file is linked to @file{fnmatch.h} so that it can be
5107 included in place of the system @code{<fnmatch.h>}.
5109 This macro is obsolescent, as it assumes the use of particular source
5110 files.  New programs should use Gnulib's @code{fnmatch-posix} module,
5111 which provides this macro along with the source files.  @xref{Gnulib}.
5112 @end defmac
5116 @node Generic Functions
5117 @subsection Generic Function Checks
5119 These macros are used to find functions not covered by the ``particular''
5120 test macros.  If the functions might be in libraries other than the
5121 default C library, first call @code{AC_CHECK_LIB} for those libraries.
5122 If you need to check the behavior of a function as well as find out
5123 whether it is present, you have to write your own test for
5124 it (@pxref{Writing Tests}).
5126 @anchor{AC_CHECK_FUNC}
5127 @defmac AC_CHECK_FUNC (@var{function}, @ovar{action-if-found}, @
5128   @ovar{action-if-not-found})
5129 @acindex{CHECK_FUNC}
5130 If C function @var{function} is available, run shell commands
5131 @var{action-if-found}, otherwise @var{action-if-not-found}.  If you just
5132 want to define a symbol if the function is available, consider using
5133 @code{AC_CHECK_FUNCS} instead.  This macro checks for functions with C
5134 linkage even when @code{AC_LANG(C++)} has been called, since C is more
5135 standardized than C++.  (@pxref{Language Choice}, for more information
5136 about selecting the language for checks.)
5137 @end defmac
5139 @anchor{AC_CHECK_FUNCS}
5140 @defmac AC_CHECK_FUNCS (@var{function}@dots{}, @ovar{action-if-found}, @
5141   @ovar{action-if-not-found})
5142 @acindex{CHECK_FUNCS}
5143 @cvindex HAVE_@var{function}
5144 For each @var{function} enumerated in the blank-or-newline-separated argument
5145 list, define @code{HAVE_@var{function}} (in all capitals) if it is available.
5146 If @var{action-if-found} is given, it is additional shell code to
5147 execute when one of the functions is found.  You can give it a value of
5148 @samp{break} to break out of the loop on the first match.  If
5149 @var{action-if-not-found} is given, it is executed when one of the
5150 functions is not found.
5151 @end defmac
5153 @defmac AC_CHECK_FUNCS_ONCE (@var{function}@dots{})
5154 @acindex{CHECK_FUNCS_ONCE}
5155 @cvindex HAVE_@var{function}
5156 For each @var{function} enumerated in the blank-or-newline-separated argument
5157 list, define @code{HAVE_@var{function}} (in all capitals) if it is available.
5158 This is a once-only variant of @code{AC_CHECK_FUNCS}.  It generates the
5159 checking code at most once, so that @command{configure} is smaller and
5160 faster; but the checks cannot be conditionalized and are always done once,
5161 early during the @command{configure} run.
5162 @end defmac
5164 @sp 1
5166 Autoconf follows a philosophy that was formed over the years by those
5167 who have struggled for portability: isolate the portability issues in
5168 specific files, and then program as if you were in a Posix
5169 environment.  Some functions may be missing or unfixable, and your
5170 package must be ready to replace them.
5172 Suitable replacements for many such problem functions are available from
5173 Gnulib (@pxref{Gnulib}).
5175 @defmac AC_LIBOBJ (@var{function})
5176 @acindex{LIBOBJ}
5177 @ovindex LIBOBJS
5178 Specify that @samp{@var{function}.c} must be included in the executables
5179 to replace a missing or broken implementation of @var{function}.
5181 Technically, it adds @samp{@var{function}.$ac_objext} to the output
5182 variable @code{LIBOBJS} if it is not already in, and calls
5183 @code{AC_LIBSOURCE} for @samp{@var{function}.c}.  You should not
5184 directly change @code{LIBOBJS}, since this is not traceable.
5185 @end defmac
5187 @defmac AC_LIBSOURCE (@var{file})
5188 @acindex{LIBSOURCE}
5189 Specify that @var{file} might be needed to compile the project.  If you
5190 need to know what files might be needed by a @file{configure.ac}, you
5191 should trace @code{AC_LIBSOURCE}.  @var{file} must be a literal.
5193 This macro is called automatically from @code{AC_LIBOBJ}, but you must
5194 call it explicitly if you pass a shell variable to @code{AC_LIBOBJ}.  In
5195 that case, since shell variables cannot be traced statically, you must
5196 pass to @code{AC_LIBSOURCE} any possible files that the shell variable
5197 might cause @code{AC_LIBOBJ} to need.  For example, if you want to pass
5198 a variable @code{$foo_or_bar} to @code{AC_LIBOBJ} that holds either
5199 @code{"foo"} or @code{"bar"}, you should do:
5201 @example
5202 AC_LIBSOURCE([foo.c])
5203 AC_LIBSOURCE([bar.c])
5204 AC_LIBOBJ([$foo_or_bar])
5205 @end example
5207 @noindent
5208 There is usually a way to avoid this, however, and you are encouraged to
5209 simply call @code{AC_LIBOBJ} with literal arguments.
5211 Note that this macro replaces the obsolete @code{AC_LIBOBJ_DECL}, with
5212 slightly different semantics: the old macro took the function name,
5213 e.g., @code{foo}, as its argument rather than the file name.
5214 @end defmac
5216 @defmac AC_LIBSOURCES (@var{files})
5217 @acindex{LIBSOURCES}
5218 Like @code{AC_LIBSOURCE}, but accepts one or more @var{files} in a
5219 comma-separated M4 list.  Thus, the above example might be rewritten:
5221 @example
5222 AC_LIBSOURCES([foo.c, bar.c])
5223 AC_LIBOBJ([$foo_or_bar])
5224 @end example
5225 @end defmac
5227 @defmac AC_CONFIG_LIBOBJ_DIR (@var{directory})
5228 @acindex{CONFIG_LIBOBJ_DIR}
5229 Specify that @code{AC_LIBOBJ} replacement files are to be found in
5230 @var{directory}, a name relative to the top level of the
5231 source tree.  The replacement directory defaults to @file{.}, the top
5232 level directory, and the most typical value is @file{lib}, corresponding
5233 to @samp{AC_CONFIG_LIBOBJ_DIR([lib])}.
5235 @command{configure} might need to know the replacement directory for the
5236 following reasons: (i) some checks use the replacement files, (ii) some
5237 macros bypass broken system headers by installing links to the
5238 replacement headers (iii) when used in conjunction with Automake,
5239 within each makefile, @var{directory} is used as a relative path
5240 from @code{$(top_srcdir)} to each object named in @code{LIBOBJS} and
5241 @code{LTLIBOBJS}, etc.
5242 @end defmac
5244 @sp 1
5246 It is common to merely check for the existence of a function, and ask
5247 for its @code{AC_LIBOBJ} replacement if missing.  The following macro is
5248 a convenient shorthand.
5250 @defmac AC_REPLACE_FUNCS (@var{function}@dots{})
5251 @acindex{REPLACE_FUNCS}
5252 @cvindex HAVE_@var{function}
5253 @ovindex LIBOBJS
5254 Like @code{AC_CHECK_FUNCS}, but uses @samp{AC_LIBOBJ(@var{function})} as
5255 @var{action-if-not-found}.  You can declare your replacement function by
5256 enclosing the prototype in @samp{#ifndef HAVE_@var{function}}.  If the
5257 system has the function, it probably declares it in a header file you
5258 should be including, so you shouldn't redeclare it lest your declaration
5259 conflict.
5260 @end defmac
5262 @node Header Files
5263 @section Header Files
5264 @cindex Header, checking
5266 The following macros check for the presence of certain C header files.
5267 If there is no macro specifically defined to check for a header file you need,
5268 and you don't need to check for any special properties of
5269 it, then you can use one of the general header-file check macros.
5271 @menu
5272 * Header Portability::          Collected knowledge on common headers
5273 * Particular Headers::          Special handling to find certain headers
5274 * Generic Headers::             How to find other headers
5275 @end menu
5277 @node Header Portability
5278 @subsection Portability of Headers
5279 @cindex Portability of headers
5280 @cindex Header portability
5282 This section tries to collect knowledge about common headers, and the
5283 problems they cause.  By definition, this list always requires
5284 additions.  Please help us keeping it as complete as possible.
5286 @table @asis
5288 @item @file{limits.h}
5289 C99 says that @file{limits.h} defines @code{LLONG_MIN},
5290 @code{LLONG_MAX}, and @code{ULLONG_MAX}, but many almost-C99
5291 environments (e.g., default @acronym{GCC} 4.0.2 + glibc 2.4) do not
5292 define them.
5294 @item @file{inttypes.h} vs.@: @file{stdint.h}
5295 @hdrindex{inttypes.h}
5296 @hdrindex{stdint.h}
5297 The C99 standard says that @file{inttypes.h} includes
5298 @file{stdint.h}, so there's no need to include @file{stdint.h}
5299 separately in a standard environment.  Some implementations have
5300 @file{inttypes.h} but not @file{stdint.h} (e.g., Solaris 7), but we don't
5301 know of any implementation that has @file{stdint.h} but not
5302 @file{inttypes.h}.
5304 @item @file{linux/irda.h}
5305 @hdrindex{linux/irda.h}
5306 It requires @file{linux/types.h} and @file{sys/socket.h}.
5308 @item @file{linux/random.h}
5309 @hdrindex{linux/random.h}
5310 It requires @file{linux/types.h}.
5312 @item @file{net/if.h}
5313 @hdrindex{net/if.h}
5314 On Darwin, this file requires that @file{sys/socket.h} be included
5315 beforehand.  One should run:
5317 @example
5318 AC_CHECK_HEADERS([sys/socket.h])
5319 AC_CHECK_HEADERS([net/if.h], [], [],
5320 [#include <stdio.h>
5321 #ifdef STDC_HEADERS
5322 # include <stdlib.h>
5323 # include <stddef.h>
5324 #else
5325 # ifdef HAVE_STDLIB_H
5326 #  include <stdlib.h>
5327 # endif
5328 #endif
5329 #ifdef HAVE_SYS_SOCKET_H
5330 # include <sys/socket.h>
5331 #endif
5333 @end example
5335 @item @file{netinet/if_ether.h}
5336 @hdrindex{netinet/if_ether.h}
5337 On Darwin, this file requires that @file{stdio.h} and
5338 @file{sys/socket.h} be included beforehand.  One should run:
5340 @example
5341 AC_CHECK_HEADERS([sys/socket.h])
5342 AC_CHECK_HEADERS([netinet/if_ether.h], [], [],
5343 [#include <stdio.h>
5344 #ifdef STDC_HEADERS
5345 # include <stdlib.h>
5346 # include <stddef.h>
5347 #else
5348 # ifdef HAVE_STDLIB_H
5349 #  include <stdlib.h>
5350 # endif
5351 #endif
5352 #ifdef HAVE_SYS_SOCKET_H
5353 # include <sys/socket.h>
5354 #endif
5356 @end example
5358 @item @file{stdint.h}
5359 See above, item @file{inttypes.h} vs.@: @file{stdint.h}.
5361 @item @file{stdlib.h}
5362 @hdrindex{stdlib.h}
5363 On many systems (e.g., Darwin), @file{stdio.h} is a prerequisite.
5365 @item @file{sys/mount.h}
5366 @hdrindex{sys/mount.h}
5367 On Free@acronym{BSD} 4.8 on ia32 and using gcc version 2.95.4,
5368 @file{sys/params.h} is a prerequisite.
5370 @item @file{sys/ptem.h}
5371 @hdrindex{sys/ptem.h}
5372 On Solaris 8, @file{sys/stream.h} is a prerequisite.
5374 @item @file{sys/socket.h}
5375 @hdrindex{sys/socket.h}
5376 On Darwin, @file{stdlib.h} is a prerequisite.
5378 @item @file{sys/ucred.h}
5379 @hdrindex{sys/ucred.h}
5380 On Tru64 5.1, @file{sys/types.h} is a prerequisite.
5382 @item @file{X11/extensions/scrnsaver.h}
5383 @hdrindex{X11/extensions/scrnsaver.h}
5384 Using XFree86, this header requires @file{X11/Xlib.h}, which is probably
5385 so required that you might not even consider looking for it.
5387 @example
5388 AC_CHECK_HEADERS([X11/extensions/scrnsaver.h], [], [],
5389 [[#include <X11/Xlib.h>
5391 @end example
5392 @end table
5395 @node Particular Headers
5396 @subsection Particular Header Checks
5398 These macros check for particular system header files---whether they
5399 exist, and in some cases whether they declare certain symbols.
5401 @defmac AC_HEADER_ASSERT
5402 @acindex{HEADER_ASSERT}
5403 @cvindex NDEBUG
5404 @hdrindex{assert.h}
5405 Check whether to enable assertions in the style of @file{assert.h}.
5406 Assertions are enabled by default, but the user can override this by
5407 invoking @command{configure} with the @option{--disable-assert} option.
5408 @end defmac
5410 @anchor{AC_HEADER_DIRENT}
5411 @defmac AC_HEADER_DIRENT
5412 @acindex{HEADER_DIRENT}
5413 @cvindex HAVE_DIRENT_H
5414 @cvindex HAVE_NDIR_H
5415 @cvindex HAVE_SYS_DIR_H
5416 @cvindex HAVE_SYS_NDIR_H
5417 @hdrindex{dirent.h}
5418 @hdrindex{sys/ndir.h}
5419 @hdrindex{sys/dir.h}
5420 @hdrindex{ndir.h}
5421 Check for the following header files.  For the first one that is
5422 found and defines @samp{DIR}, define the listed C preprocessor macro:
5424 @multitable {@file{sys/ndir.h}} {@code{HAVE_SYS_NDIR_H}}
5425 @item @file{dirent.h}   @tab @code{HAVE_DIRENT_H}
5426 @item @file{sys/ndir.h} @tab @code{HAVE_SYS_NDIR_H}
5427 @item @file{sys/dir.h}  @tab @code{HAVE_SYS_DIR_H}
5428 @item @file{ndir.h}     @tab @code{HAVE_NDIR_H}
5429 @end multitable
5431 The directory-library declarations in your source code should look
5432 something like the following:
5434 @example
5435 @group
5436 #include <sys/types.h>
5437 #ifdef HAVE_DIRENT_H
5438 # include <dirent.h>
5439 # define NAMLEN(dirent) strlen ((dirent)->d_name)
5440 #else
5441 # define dirent direct
5442 # define NAMLEN(dirent) ((dirent)->d_namlen)
5443 # ifdef HAVE_SYS_NDIR_H
5444 #  include <sys/ndir.h>
5445 # endif
5446 # ifdef HAVE_SYS_DIR_H
5447 #  include <sys/dir.h>
5448 # endif
5449 # ifdef HAVE_NDIR_H
5450 #  include <ndir.h>
5451 # endif
5452 #endif
5453 @end group
5454 @end example
5456 Using the above declarations, the program would declare variables to be
5457 of type @code{struct dirent}, not @code{struct direct}, and would access
5458 the length of a directory entry name by passing a pointer to a
5459 @code{struct dirent} to the @code{NAMLEN} macro.
5461 This macro also checks for the SCO Xenix @file{dir} and @file{x} libraries.
5463 This macro is obsolescent, as all current systems with directory
5464 libraries have @code{<dirent.h>}.  New programs need not use this macro.
5466 Also see @code{AC_STRUCT_DIRENT_D_INO} and
5467 @code{AC_STRUCT_DIRENT_D_TYPE} (@pxref{Particular Structures}).
5468 @end defmac
5470 @anchor{AC_HEADER_MAJOR}
5471 @defmac AC_HEADER_MAJOR
5472 @acindex{HEADER_MAJOR}
5473 @cvindex MAJOR_IN_MKDEV
5474 @cvindex MAJOR_IN_SYSMACROS
5475 @hdrindex{sys/mkdev.h}
5476 @hdrindex{sys/sysmacros.h}
5477 If @file{sys/types.h} does not define @code{major}, @code{minor}, and
5478 @code{makedev}, but @file{sys/mkdev.h} does, define
5479 @code{MAJOR_IN_MKDEV}; otherwise, if @file{sys/sysmacros.h} does, define
5480 @code{MAJOR_IN_SYSMACROS}.
5481 @end defmac
5483 @defmac AC_HEADER_RESOLV
5484 @acindex{HEADER_RESOLV}
5485 @cvindex HAVE_RESOLV_H
5486 @hdrindex{resolv.h}
5487 Checks for header @file{resolv.h}, checking for prerequisites first.
5488 To properly use @file{resolv.h}, your code should contain something like
5489 the following:
5491 @verbatim
5492 #ifdef HAVE_SYS_TYPES_H
5493 #  include <sys/types.h>
5494 #endif
5495 #ifdef HAVE_NETINET_IN_H
5496 #  include <netinet/in.h>   /* inet_ functions / structs */
5497 #endif
5498 #ifdef HAVE_ARPA_NAMESER_H
5499 #  include <arpa/nameser.h> /* DNS HEADER struct */
5500 #endif
5501 #ifdef HAVE_NETDB_H
5502 #  include <netdb.h>
5503 #endif
5504 #include <resolv.h>
5505 @end verbatim
5506 @end defmac
5508 @anchor{AC_HEADER_STAT}
5509 @defmac AC_HEADER_STAT
5510 @acindex{HEADER_STAT}
5511 @cvindex STAT_MACROS_BROKEN
5512 @hdrindex{sys/stat.h}
5513 If the macros @code{S_ISDIR}, @code{S_ISREG}, etc.@: defined in
5514 @file{sys/stat.h} do not work properly (returning false positives),
5515 define @code{STAT_MACROS_BROKEN}.  This is the case on Tektronix UTekV,
5516 Amdahl UTS and Motorola System V/88.
5518 This macro is obsolescent, as no current systems have the bug.
5519 New programs need not use this macro.
5520 @end defmac
5522 @defmac AC_HEADER_STDBOOL
5523 @acindex{HEADER_STDBOOL}
5524 @cvindex HAVE_STDBOOL_H
5525 @cvindex HAVE__BOOL
5526 @hdrindex{stdbool.h}
5527 @hdrindex{system.h}
5528 If @file{stdbool.h} exists and conforms to C99, define
5529 @code{HAVE_STDBOOL_H} to 1; if the type @code{_Bool} is defined, define
5530 @code{HAVE__BOOL} to 1.  To fulfill the C99 requirements, your
5531 @file{system.h} could contain the following code:
5533 @verbatim
5534 #ifdef HAVE_STDBOOL_H
5535 # include <stdbool.h>
5536 #else
5537 # ifndef HAVE__BOOL
5538 #  ifdef __cplusplus
5539 typedef bool _Bool;
5540 #  else
5541 #   define _Bool signed char
5542 #  endif
5543 # endif
5544 # define bool _Bool
5545 # define false 0
5546 # define true 1
5547 # define __bool_true_false_are_defined 1
5548 #endif
5549 @end verbatim
5551 Alternatively you can use the @samp{stdbool} package of Gnulib
5552 (@pxref{Gnulib}); it packages the above code into a replacement header
5553 and contains a few other bells and whistles.
5555 @end defmac
5557 @anchor{AC_HEADER_STDC}
5558 @defmac AC_HEADER_STDC
5559 @acindex{HEADER_STDC}
5560 @cvindex STDC_HEADERS
5561 @hdrindex{stdlib.h}
5562 @hdrindex{stdarg.h}
5563 @hdrindex{string.h}
5564 @hdrindex{float.h}
5565 @hdrindex{ctype.h}
5566 Define @code{STDC_HEADERS} if the system has C header files
5567 conforming to @acronym{ANSI} C89 (@acronym{ISO} C90).
5568 Specifically, this macro checks for @file{stdlib.h}, @file{stdarg.h},
5569 @file{string.h}, and @file{float.h}; if the system has those, it
5570 probably has the rest of the C89 header files.  This macro also
5571 checks whether @file{string.h} declares @code{memchr} (and thus
5572 presumably the other @code{mem} functions), whether @file{stdlib.h}
5573 declare @code{free} (and thus presumably @code{malloc} and other related
5574 functions), and whether the @file{ctype.h} macros work on characters
5575 with the high bit set, as the C standard requires.
5577 If you use this macro, your code can refer to @code{STDC_HEADERS} to
5578 determine whether the system has conforming header files (and probably C
5579 library functions).
5581 This macro is obsolescent, as current systems have conforming header
5582 files.  New programs need not use this macro.
5584 @hdrindex{string.h}
5585 @hdrindex{strings.h}
5586 Nowadays @file{string.h} is part of the C standard and declares functions like
5587 @code{strcpy}, and @file{strings.h} is standardized by Posix and declares
5588 @acronym{BSD} functions like @code{bcopy}; but
5589 historically, string functions were a major sticking point in this area.
5590 If you still want to worry about portability to ancient systems without
5591 standard headers, there is so much variation
5592 that it is probably easier to declare the functions you use than to
5593 figure out exactly what the system header files declare.  Some ancient systems
5594 contained a mix of functions from the C standard and from @acronym{BSD};
5595 some were mostly standard but lacked @samp{memmove}; some defined the
5596 @acronym{BSD} functions as macros in @file{string.h} or
5597 @file{strings.h}; some had only the @acronym{BSD} functions but
5598 @file{string.h}; some declared the memory functions in @file{memory.h},
5599 some in @file{string.h}; etc.  It is probably sufficient to check for
5600 one string function and one memory function; if the library had the
5601 standard versions of those then it probably had most of the others.
5602 If you put the following in @file{configure.ac}:
5604 @example
5605 # This example is obsolescent.
5606 # Nowadays you can omit these macro calls.
5607 AC_HEADER_STDC
5608 AC_CHECK_FUNCS([strchr memcpy])
5609 @end example
5611 @noindent
5612 then, in your code, you can use declarations like this:
5614 @example
5615 @group
5616 /* This example is obsolescent.
5617    Nowadays you can just #include <string.h>.  */
5618 #ifdef STDC_HEADERS
5619 # include <string.h>
5620 #else
5621 # ifndef HAVE_STRCHR
5622 #  define strchr index
5623 #  define strrchr rindex
5624 # endif
5625 char *strchr (), *strrchr ();
5626 # ifndef HAVE_MEMCPY
5627 #  define memcpy(d, s, n) bcopy ((s), (d), (n))
5628 #  define memmove(d, s, n) bcopy ((s), (d), (n))
5629 # endif
5630 #endif
5631 @end group
5632 @end example
5634 @noindent
5635 If you use a function like @code{memchr}, @code{memset}, @code{strtok},
5636 or @code{strspn}, which have no @acronym{BSD} equivalent, then macros don't
5637 suffice to port to ancient hosts; you must provide an implementation of
5638 each function.  An easy
5639 way to incorporate your implementations only when needed (since the ones
5640 in system C libraries may be hand optimized) is to, taking @code{memchr}
5641 for example, put it in @file{memchr.c} and use
5642 @samp{AC_REPLACE_FUNCS([memchr])}.
5643 @end defmac
5645 @defmac AC_HEADER_SYS_WAIT
5646 @acindex{HEADER_SYS_WAIT}
5647 @cvindex HAVE_SYS_WAIT_H
5648 @hdrindex{sys/wait.h}
5649 If @file{sys/wait.h} exists and is compatible with Posix, define
5650 @code{HAVE_SYS_WAIT_H}.  Incompatibility can occur if @file{sys/wait.h}
5651 does not exist, or if it uses the old @acronym{BSD} @code{union wait} instead
5652 of @code{int} to store a status value.  If @file{sys/wait.h} is not
5653 Posix compatible, then instead of including it, define the
5654 Posix macros with their usual interpretations.  Here is an
5655 example:
5657 @example
5658 @group
5659 #include <sys/types.h>
5660 #ifdef HAVE_SYS_WAIT_H
5661 # include <sys/wait.h>
5662 #endif
5663 #ifndef WEXITSTATUS
5664 # define WEXITSTATUS(stat_val) ((unsigned int) (stat_val) >> 8)
5665 #endif
5666 #ifndef WIFEXITED
5667 # define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
5668 #endif
5669 @end group
5670 @end example
5672 @noindent
5673 This macro is obsolescent, as current systems are compatible with Posix.
5674 New programs need not use this macro.
5675 @end defmac
5677 @cvindex _POSIX_VERSION
5678 @hdrindex{unistd.h}
5679 @code{_POSIX_VERSION} is defined when @file{unistd.h} is included on
5680 Posix systems.  If there is no @file{unistd.h}, it is definitely
5681 not a Posix system.  However, some non-Posix systems do
5682 have @file{unistd.h}.
5684 The way to check whether the system supports Posix is:
5686 @example
5687 @group
5688 #ifdef HAVE_UNISTD_H
5689 # include <sys/types.h>
5690 # include <unistd.h>
5691 #endif
5693 #ifdef _POSIX_VERSION
5694 /* Code for Posix systems.  */
5695 #endif
5696 @end group
5697 @end example
5699 @anchor{AC_HEADER_TIME}
5700 @defmac AC_HEADER_TIME
5701 @acindex{HEADER_TIME}
5702 @cvindex TIME_WITH_SYS_TIME
5703 @hdrindex{time.h}
5704 @hdrindex{sys/time.h}
5705 If a program may include both @file{time.h} and @file{sys/time.h},
5706 define @code{TIME_WITH_SYS_TIME}.  On some ancient systems,
5707 @file{sys/time.h} included @file{time.h}, but @file{time.h} was not
5708 protected against multiple inclusion, so programs could not explicitly
5709 include both files.  This macro is useful in programs that use, for
5710 example, @code{struct timeval} as well as
5711 @code{struct tm}.  It is best used in conjunction with
5712 @code{HAVE_SYS_TIME_H}, which can be checked for using
5713 @code{AC_CHECK_HEADERS([sys/time.h])}.
5715 @example
5716 @group
5717 #ifdef TIME_WITH_SYS_TIME
5718 # include <sys/time.h>
5719 # include <time.h>
5720 #else
5721 # ifdef HAVE_SYS_TIME_H
5722 #  include <sys/time.h>
5723 # else
5724 #  include <time.h>
5725 # endif
5726 #endif
5727 @end group
5728 @end example
5730 @noindent
5731 This macro is obsolescent, as current systems can include both files
5732 when they exist.  New programs need not use this macro.
5733 @end defmac
5736 @defmac AC_HEADER_TIOCGWINSZ
5737 @acindex{HEADER_TIOCGWINSZ}
5738 @cvindex GWINSZ_IN_SYS_IOCTL
5739 @hdrindex{sys/ioctl.h}
5740 @hdrindex{termios.h}
5741 @c FIXME: I need clarifications from Jim.
5742 If the use of @code{TIOCGWINSZ} requires @file{<sys/ioctl.h>}, then
5743 define @code{GWINSZ_IN_SYS_IOCTL}.  Otherwise @code{TIOCGWINSZ} can be
5744 found in @file{<termios.h>}.
5746 Use:
5748 @example
5749 @group
5750 #ifdef HAVE_TERMIOS_H
5751 # include <termios.h>
5752 #endif
5754 #ifdef GWINSZ_IN_SYS_IOCTL
5755 # include <sys/ioctl.h>
5756 #endif
5757 @end group
5758 @end example
5759 @end defmac
5761 @node Generic Headers
5762 @subsection Generic Header Checks
5764 These macros are used to find system header files not covered by the
5765 ``particular'' test macros.  If you need to check the contents of a header
5766 as well as find out whether it is present, you have to write your own
5767 test for it (@pxref{Writing Tests}).
5769 @anchor{AC_CHECK_HEADER}
5770 @defmac AC_CHECK_HEADER (@var{header-file}, @ovar{action-if-found}, @
5771   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
5772 @acindex{CHECK_HEADER}
5773 If the system header file @var{header-file} is compilable, execute shell
5774 commands @var{action-if-found}, otherwise execute
5775 @var{action-if-not-found}.  If you just want to define a symbol if the
5776 header file is available, consider using @code{AC_CHECK_HEADERS}
5777 instead.
5779 @var{includes} is a series of include directives, defaulting to
5780 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
5781 prior to the header under test.
5783 For compatibility issues with older versions of Autoconf, please read
5784 below.
5785 @end defmac
5787 @anchor{AC_CHECK_HEADERS}
5788 @defmac AC_CHECK_HEADERS (@var{header-file}@dots{}, @
5789   @ovar{action-if-found}, @ovar{action-if-not-found}, @
5790   @dvar{includes, AC_INCLUDES_DEFAULT})
5791 @acindex{CHECK_HEADERS}
5792 @cvindex HAVE_@var{header}
5793 For each given system header file @var{header-file} in the
5794 blank-separated argument list that exists, define
5795 @code{HAVE_@var{header-file}} (in all capitals).  If @var{action-if-found}
5796 is given, it is additional shell code to execute when one of the header
5797 files is found.  You can give it a value of @samp{break} to break out of
5798 the loop on the first match.  If @var{action-if-not-found} is given, it
5799 is executed when one of the header files is not found.
5801 @var{includes} is a series of include directives, defaulting to
5802 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
5803 prior to the headers under test.
5805 For compatibility issues with older versions of Autoconf, please read
5806 below.
5807 @end defmac
5809 Previous versions of Autoconf merely checked whether the header was
5810 accepted by the preprocessor.  This was changed because the old test was
5811 inappropriate for typical uses.  Headers are typically used to compile,
5812 not merely to preprocess, and the old behavior sometimes accepted
5813 headers that clashed at compile-time.  If you need to check whether a
5814 header is preprocessable, you can use @code{AC_PREPROC_IFELSE}
5815 (@pxref{Running the Preprocessor}).
5817 This scheme, which improves the robustness of the test, also requires
5818 that you make sure that headers that must be included before the
5819 @var{header-file} be part of the @var{includes}, (@pxref{Default
5820 Includes}).  If looking for @file{bar.h}, which requires that
5821 @file{foo.h} be included before if it exists, we suggest the following
5822 scheme:
5824 @verbatim
5825 AC_CHECK_HEADERS([foo.h])
5826 AC_CHECK_HEADERS([bar.h], [], [],
5827 [#ifdef HAVE_FOO_H
5828 # include <foo.h>
5829 # endif
5831 @end verbatim
5833 The following variant generates smaller, faster @command{configure}
5834 files if you do not need the full power of @code{AC_CHECK_HEADERS}.
5836 @defmac AC_CHECK_HEADERS_ONCE (@var{header-file}@dots{})
5837 @acindex{CHECK_HEADERS_ONCE}
5838 @cvindex HAVE_@var{header}
5839 For each given system header file @var{header-file} in the
5840 blank-separated argument list that exists, define
5841 @code{HAVE_@var{header-file}} (in all capitals).
5842 This is a once-only variant of @code{AC_CHECK_HEADERS}.  It generates the
5843 checking code at most once, so that @command{configure} is smaller and
5844 faster; but the checks cannot be conditionalized and are always done once,
5845 early during the @command{configure} run.
5846 @end defmac
5848 @node Declarations
5849 @section Declarations
5850 @cindex Declaration, checking
5852 The following macros check for the declaration of variables and
5853 functions.  If there is no macro specifically defined to check for a
5854 symbol you need, then you can use the general macros (@pxref{Generic
5855 Declarations}) or, for more complex tests, you may use
5856 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}).
5858 @menu
5859 * Particular Declarations::     Macros to check for certain declarations
5860 * Generic Declarations::        How to find other declarations
5861 @end menu
5863 @node Particular Declarations
5864 @subsection Particular Declaration Checks
5866 There are no specific macros for declarations.
5868 @node Generic Declarations
5869 @subsection Generic Declaration Checks
5871 These macros are used to find declarations not covered by the ``particular''
5872 test macros.
5874 @defmac AC_CHECK_DECL (@var{symbol}, @ovar{action-if-found}, @
5875   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
5876 @acindex{CHECK_DECL}
5877 If @var{symbol} (a function, variable, or constant) is not declared in
5878 @var{includes} and a declaration is needed, run the shell commands
5879 @var{action-if-not-found}, otherwise @var{action-if-found}.
5880 @var{includes} is a series of include directives, defaulting to
5881 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
5882 prior to the declaration under test.
5884 This macro actually tests whether @var{symbol} is defined as a macro or
5885 can be used as an r-value, not whether it is really declared, because it
5886 is much safer to avoid
5887 introducing extra declarations when they are not needed.
5888 @end defmac
5890 @anchor{AC_CHECK_DECLS}
5891 @defmac AC_CHECK_DECLS (@var{symbols}, @ovar{action-if-found}, @
5892   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
5893 @acindex{CHECK_DECLS}
5894 @cvindex HAVE_DECL_@var{symbol}
5895 For each of the @var{symbols} (@emph{comma}-separated list), define
5896 @code{HAVE_DECL_@var{symbol}} (in all capitals) to @samp{1} if
5897 @var{symbol} is declared, otherwise to @samp{0}.  If
5898 @var{action-if-not-found} is given, it is additional shell code to
5899 execute when one of the function declarations is needed, otherwise
5900 @var{action-if-found} is executed.
5902 @var{includes} is a series of include directives, defaulting to
5903 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
5904 prior to the declarations under test.
5906 This macro uses an M4 list as first argument:
5907 @example
5908 AC_CHECK_DECLS([strdup])
5909 AC_CHECK_DECLS([strlen])
5910 AC_CHECK_DECLS([malloc, realloc, calloc, free])
5911 AC_CHECK_DECLS([j0], [], [], [[#include <math.h>]])
5912 @end example
5914 Unlike the other @samp{AC_CHECK_*S} macros, when a @var{symbol} is not
5915 declared, @code{HAVE_DECL_@var{symbol}} is defined to @samp{0} instead
5916 of leaving @code{HAVE_DECL_@var{symbol}} undeclared.  When you are
5917 @emph{sure} that the check was performed, use
5918 @code{HAVE_DECL_@var{symbol}} in @code{#if}:
5920 @example
5921 #if !HAVE_DECL_SYMBOL
5922 extern char *symbol;
5923 #endif
5924 @end example
5926 @noindent
5927 If the test may have not been performed, however, because it is safer
5928 @emph{not} to declare a symbol than to use a declaration that conflicts
5929 with the system's one, you should use:
5931 @example
5932 #if defined HAVE_DECL_MALLOC && !HAVE_DECL_MALLOC
5933 void *malloc (size_t *s);
5934 #endif
5935 @end example
5937 @noindent
5938 You fall into the second category only in extreme situations: either
5939 your files may be used without being configured, or they are used during
5940 the configuration.  In most cases the traditional approach is enough.
5941 @end defmac
5943 @defmac AC_CHECK_DECLS_ONCE (@var{symbols})
5944 @acindex{CHECK_DECLS_ONCE}
5945 @cvindex HAVE_DECL_@var{symbol}
5946 For each of the @var{symbols} (@emph{comma}-separated list), define
5947 @code{HAVE_DECL_@var{symbol}} (in all capitals) to @samp{1} if
5948 @var{symbol} is declared in the default include files, otherwise to
5949 @samp{0}.  This is a once-only variant of @code{AC_CHECK_DECLS}.  It
5950 generates the checking code at most once, so that @command{configure} is
5951 smaller and faster; but the checks cannot be conditionalized and are
5952 always done once, early during the @command{configure} run.
5953 @end defmac
5956 @node Structures
5957 @section Structures
5958 @cindex Structure, checking
5960 The following macros check for the presence of certain members in C
5961 structures.  If there is no macro specifically defined to check for a
5962 member you need, then you can use the general structure-member macros
5963 (@pxref{Generic Structures}) or, for more complex tests, you may use
5964 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}).
5966 @menu
5967 * Particular Structures::       Macros to check for certain structure members
5968 * Generic Structures::          How to find other structure members
5969 @end menu
5971 @node Particular Structures
5972 @subsection Particular Structure Checks
5974 The following macros check for certain structures or structure members.
5976 @defmac AC_STRUCT_DIRENT_D_INO
5977 @acindex{STRUCT_DIRENT_D_INO}
5978 @cvindex HAVE_STRUCT_DIRENT_D_INO
5979 Perform all the actions of @code{AC_HEADER_DIRENT} (@pxref{Particular
5980 Headers}).  Then, if @code{struct dirent} contains a @code{d_ino}
5981 member, define @code{HAVE_STRUCT_DIRENT_D_INO}.
5983 @code{HAVE_STRUCT_DIRENT_D_INO} indicates only the presence of
5984 @code{d_ino}, not whether its contents are always reliable.
5985 Traditionally, a zero @code{d_ino} indicated a deleted directory entry,
5986 though current systems hide this detail from the user and never return
5987 zero @code{d_ino} values.
5988 Many current systems report an incorrect @code{d_ino} for a directory
5989 entry that is a mount point.
5990 @end defmac
5992 @defmac AC_STRUCT_DIRENT_D_TYPE
5993 @acindex{STRUCT_DIRENT_D_TYPE}
5994 @cvindex HAVE_STRUCT_DIRENT_D_TYPE
5995 Perform all the actions of @code{AC_HEADER_DIRENT} (@pxref{Particular
5996 Headers}).  Then, if @code{struct dirent} contains a @code{d_type}
5997 member, define @code{HAVE_STRUCT_DIRENT_D_TYPE}.
5998 @end defmac
6000 @anchor{AC_STRUCT_ST_BLOCKS}
6001 @defmac AC_STRUCT_ST_BLOCKS
6002 @acindex{STRUCT_ST_BLOCKS}
6003 @cvindex HAVE_STRUCT_STAT_ST_BLOCKS
6004 @cvindex HAVE_ST_BLOCKS
6005 @ovindex LIBOBJS
6006 If @code{struct stat} contains an @code{st_blocks} member, define
6007 @code{HAVE_STRUCT_STAT_ST_BLOCKS}.  Otherwise, require an
6008 @code{AC_LIBOBJ} replacement of @samp{fileblocks}.  The former name,
6009 @code{HAVE_ST_BLOCKS} is to be avoided, as its support will cease in the
6010 future.
6011 @end defmac
6013 @defmac AC_STRUCT_TM
6014 @acindex{STRUCT_TM}
6015 @cvindex TM_IN_SYS_TIME
6016 @hdrindex{time.h}
6017 @hdrindex{sys/time.h}
6018 If @file{time.h} does not define @code{struct tm}, define
6019 @code{TM_IN_SYS_TIME}, which means that including @file{sys/time.h}
6020 had better define @code{struct tm}.
6022 This macro is obsolescent, as @file{time.h} defines @code{struct tm} in
6023 current systems.  New programs need not use this macro.
6024 @end defmac
6026 @anchor{AC_STRUCT_TIMEZONE}
6027 @defmac AC_STRUCT_TIMEZONE
6028 @acindex{STRUCT_TIMEZONE}
6029 @cvindex HAVE_DECL_TZNAME
6030 @cvindex HAVE_STRUCT_TM_TM_ZONE
6031 @cvindex HAVE_TM_ZONE
6032 @cvindex HAVE_TZNAME
6033 Figure out how to get the current timezone.  If @code{struct tm} has a
6034 @code{tm_zone} member, define @code{HAVE_STRUCT_TM_TM_ZONE} (and the
6035 obsoleted @code{HAVE_TM_ZONE}).  Otherwise, if the external array
6036 @code{tzname} is found, define @code{HAVE_TZNAME}; if it is declared,
6037 define @code{HAVE_DECL_TZNAME}.
6038 @end defmac
6040 @node Generic Structures
6041 @subsection Generic Structure Checks
6043 These macros are used to find structure members not covered by the
6044 ``particular'' test macros.
6046 @defmac AC_CHECK_MEMBER (@var{aggregate}.@var{member}, @
6047   @ovar{action-if-found}, @ovar{action-if-not-found}, @
6048   @dvar{includes, AC_INCLUDES_DEFAULT})
6049 @acindex{CHECK_MEMBER}
6050 Check whether @var{member} is a member of the aggregate @var{aggregate}.
6051 If no @var{includes} are specified, the default includes are used
6052 (@pxref{Default Includes}).
6054 @example
6055 AC_CHECK_MEMBER([struct passwd.pw_gecos], [],
6056                 [AC_MSG_ERROR([We need `passwd.pw_gecos'!])],
6057                 [[#include <pwd.h>]])
6058 @end example
6060 You can use this macro for submembers:
6062 @example
6063 AC_CHECK_MEMBER(struct top.middle.bot)
6064 @end example
6065 @end defmac
6067 @anchor{AC_CHECK_MEMBERS}
6068 @defmac AC_CHECK_MEMBERS (@var{members}, @ovar{action-if-found}, @
6069   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6070 @acindex{CHECK_MEMBERS}
6071 @cvindex HAVE_@var{aggregate}_@var{member}
6072 Check for the existence of each @samp{@var{aggregate}.@var{member}} of
6073 @var{members} using the previous macro.  When @var{member} belongs to
6074 @var{aggregate}, define @code{HAVE_@var{aggregate}_@var{member}} (in all
6075 capitals, with spaces and dots replaced by underscores).  If
6076 @var{action-if-found} is given, it is executed for each of the found
6077 members.  If @var{action-if-not-found} is given, it is executed for each
6078 of the members that could not be found.
6080 @var{includes} is a series of include directives, defaulting to
6081 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
6082 prior to the members under test.
6084 This macro uses M4 lists:
6085 @example
6086 AC_CHECK_MEMBERS([struct stat.st_rdev, struct stat.st_blksize])
6087 @end example
6088 @end defmac
6091 @node Types
6092 @section Types
6093 @cindex Types
6094 @cindex C types
6096 The following macros check for C types, either builtin or typedefs.  If
6097 there is no macro specifically defined to check for a type you need, and
6098 you don't need to check for any special properties of it, then you can
6099 use a general type-check macro.
6101 @menu
6102 * Particular Types::            Special handling to find certain types
6103 * Generic Types::               How to find other types
6104 @end menu
6106 @node Particular Types
6107 @subsection Particular Type Checks
6109 @hdrindex{sys/types.h}
6110 @hdrindex{stdlib.h}
6111 @hdrindex{stdint.h}
6112 @hdrindex{inttypes.h}
6113 These macros check for particular C types in @file{sys/types.h},
6114 @file{stdlib.h}, @file{stdint.h}, @file{inttypes.h} and others, if they
6115 exist.
6117 The Gnulib @code{stdint} module is an alternate way to define many of
6118 these symbols; it is useful if you prefer your code to assume a
6119 C99-or-better environment.  @xref{Gnulib}.
6121 @anchor{AC_TYPE_GETGROUPS}
6122 @defmac AC_TYPE_GETGROUPS
6123 @acindex{TYPE_GETGROUPS}
6124 @cvindex GETGROUPS_T
6125 Define @code{GETGROUPS_T} to be whichever of @code{gid_t} or @code{int}
6126 is the base type of the array argument to @code{getgroups}.
6127 @end defmac
6129 @defmac AC_TYPE_INT8_T
6130 @acindex{TYPE_INT8_T}
6131 @cvindex HAVE_INT8_T
6132 @cvindex int8_t
6133 If @file{stdint.h} or @file{inttypes.h} does not define the type
6134 @code{int8_t}, define @code{int8_t} to a signed
6135 integer type that is exactly 8 bits wide and that uses two's complement
6136 representation, if such a type exists.
6137 If you are worried about porting to hosts that lack such a type, you can
6138 use the results of this macro in C89-or-later code as follows:
6140 @example
6141 #if HAVE_STDINT_H
6142 # include <stdint.h>
6143 #endif
6144 #if defined INT8_MAX || defined int8_t
6145  @emph{code using int8_t}
6146 #else
6147  @emph{complicated alternative using >8-bit 'signed char'}
6148 #endif
6149 @end example
6150 @end defmac
6152 @defmac AC_TYPE_INT16_T
6153 @acindex{TYPE_INT16_T}
6154 @cvindex HAVE_INT16_T
6155 @cvindex int16_t
6156 This is like @code{AC_TYPE_INT8_T}, except for 16-bit integers.
6157 @end defmac
6159 @defmac AC_TYPE_INT32_T
6160 @acindex{TYPE_INT32_T}
6161 @cvindex HAVE_INT32_T
6162 @cvindex int32_t
6163 This is like @code{AC_TYPE_INT8_T}, except for 32-bit integers.
6164 @end defmac
6166 @defmac AC_TYPE_INT64_T
6167 @acindex{TYPE_INT64_T}
6168 @cvindex HAVE_INT64_T
6169 @cvindex int64_t
6170 This is like @code{AC_TYPE_INT8_T}, except for 64-bit integers.
6171 @end defmac
6173 @defmac AC_TYPE_INTMAX_T
6174 @acindex{TYPE_INTMAX_T}
6175 @cvindex HAVE_INTMAX_T
6176 @cvindex intmax_t
6177 If @file{stdint.h} or @file{inttypes.h} defines the type @code{intmax_t},
6178 define @code{HAVE_INTMAX_T}.  Otherwise, define @code{intmax_t} to the
6179 widest signed integer type.
6180 @end defmac
6182 @defmac AC_TYPE_INTPTR_T
6183 @acindex{TYPE_INTPTR_T}
6184 @cvindex HAVE_INTPTR_T
6185 @cvindex intptr_t
6186 If @file{stdint.h} or @file{inttypes.h} defines the type @code{intptr_t},
6187 define @code{HAVE_INTPTR_T}.  Otherwise, define @code{intptr_t} to a
6188 signed integer type wide enough to hold a pointer, if such a type
6189 exists.
6190 @end defmac
6192 @defmac AC_TYPE_LONG_DOUBLE
6193 @acindex{TYPE_LONG_DOUBLE}
6194 @cvindex HAVE_LONG_DOUBLE
6195 If the C compiler supports a working @code{long double} type, define
6196 @code{HAVE_LONG_DOUBLE}.  The @code{long double} type might have the
6197 same range and precision as @code{double}.
6199 This macro is obsolescent, as current C compilers support @code{long
6200 double}.  New programs need not use this macro.
6201 @end defmac
6203 @defmac AC_TYPE_LONG_DOUBLE_WIDER
6204 @acindex{TYPE_LONG_DOUBLE_WIDER}
6205 @cvindex HAVE_LONG_DOUBLE_WIDER
6206 If the C compiler supports a working @code{long double} type with more
6207 range or precision than the @code{double} type, define
6208 @code{HAVE_LONG_DOUBLE_WIDER}.
6209 @end defmac
6211 @defmac AC_TYPE_LONG_LONG_INT
6212 @acindex{TYPE_LONG_LONG_INT}
6213 @cvindex HAVE_LONG_LONG_INT
6214 If the C compiler supports a working @code{long long int} type, define
6215 @code{HAVE_LONG_LONG_INT}.  However, this test does not test
6216 @code{long long int} values in preprocessor @code{#if} expressions,
6217 because too many compilers mishandle such expressions.
6218 @xref{Preprocessor Arithmetic}.
6219 @end defmac
6221 @defmac AC_TYPE_MBSTATE_T
6222 @acindex{TYPE_MBSTATE_T}
6223 @cvindex mbstate_t
6224 @hdrindex{wchar.h}
6225 Define @code{HAVE_MBSTATE_T} if @code{<wchar.h>} declares the
6226 @code{mbstate_t} type.  Also, define @code{mbstate_t} to be a type if
6227 @code{<wchar.h>} does not declare it.
6228 @end defmac
6230 @anchor{AC_TYPE_MODE_T}
6231 @defmac AC_TYPE_MODE_T
6232 @acindex{TYPE_MODE_T}
6233 @cvindex mode_t
6234 Define @code{mode_t} to a suitable type, if standard headers do not
6235 define it.
6236 @end defmac
6238 @anchor{AC_TYPE_OFF_T}
6239 @defmac AC_TYPE_OFF_T
6240 @acindex{TYPE_OFF_T}
6241 @cvindex off_t
6242 Define @code{off_t} to a suitable type, if standard headers do not
6243 define it.
6244 @end defmac
6246 @anchor{AC_TYPE_PID_T}
6247 @defmac AC_TYPE_PID_T
6248 @acindex{TYPE_PID_T}
6249 @cvindex pid_t
6250 Define @code{pid_t} to a suitable type, if standard headers do not
6251 define it.
6252 @end defmac
6254 @anchor{AC_TYPE_SIZE_T}
6255 @defmac AC_TYPE_SIZE_T
6256 @acindex{TYPE_SIZE_T}
6257 @cvindex size_t
6258 Define @code{size_t} to a suitable type, if standard headers do not
6259 define it.
6260 @end defmac
6262 @defmac AC_TYPE_SSIZE_T
6263 @acindex{TYPE_SSIZE_T}
6264 @cvindex ssize_t
6265 Define @code{ssize_t} to a suitable type, if standard headers do not
6266 define it.
6267 @end defmac
6269 @anchor{AC_TYPE_UID_T}
6270 @defmac AC_TYPE_UID_T
6271 @acindex{TYPE_UID_T}
6272 @cvindex uid_t
6273 @cvindex gid_t
6274 Define @code{uid_t} and @code{gid_t} to suitable types, if standard
6275 headers do not define them.
6276 @end defmac
6278 @defmac AC_TYPE_UINT8_T
6279 @acindex{TYPE_UINT8_T}
6280 @cvindex HAVE_UINT8_T
6281 @cvindex uint8_t
6282 If @file{stdint.h} or @file{inttypes.h} does not define the type
6283 @code{uint8_t}, define @code{uint8_t} to an
6284 unsigned integer type that is exactly 8 bits wide, if such a type
6285 exists.
6286 This is like @code{AC_TYPE_INT8_T}, except for unsigned integers.
6287 @end defmac
6289 @defmac AC_TYPE_UINT16_T
6290 @acindex{TYPE_UINT16_T}
6291 @cvindex HAVE_UINT16_T
6292 @cvindex uint16_t
6293 This is like @code{AC_TYPE_UINT8_T}, except for 16-bit integers.
6294 @end defmac
6296 @defmac AC_TYPE_UINT32_T
6297 @acindex{TYPE_UINT32_T}
6298 @cvindex HAVE_UINT32_T
6299 @cvindex uint32_t
6300 This is like @code{AC_TYPE_UINT8_T}, except for 32-bit integers.
6301 @end defmac
6303 @defmac AC_TYPE_UINT64_T
6304 @acindex{TYPE_UINT64_T}
6305 @cvindex HAVE_UINT64_T
6306 @cvindex uint64_t
6307 This is like @code{AC_TYPE_UINT8_T}, except for 64-bit integers.
6308 @end defmac
6310 @defmac AC_TYPE_UINTMAX_T
6311 @acindex{TYPE_UINTMAX_T}
6312 @cvindex HAVE_UINTMAX_T
6313 @cvindex uintmax_t
6314 If @file{stdint.h} or @file{inttypes.h} defines the type @code{uintmax_t},
6315 define @code{HAVE_UINTMAX_T}.  Otherwise, define @code{uintmax_t} to the
6316 widest unsigned integer type.
6317 @end defmac
6319 @defmac AC_TYPE_UINTPTR_T
6320 @acindex{TYPE_UINTPTR_T}
6321 @cvindex HAVE_UINTPTR_T
6322 @cvindex uintptr_t
6323 If @file{stdint.h} or @file{inttypes.h} defines the type @code{uintptr_t},
6324 define @code{HAVE_UINTPTR_T}.  Otherwise, define @code{uintptr_t} to an
6325 unsigned integer type wide enough to hold a pointer, if such a type
6326 exists.
6327 @end defmac
6329 @defmac AC_TYPE_UNSIGNED_LONG_LONG_INT
6330 @acindex{TYPE_UNSIGNED_LONG_LONG_INT}
6331 @cvindex HAVE_UNSIGNED_LONG_LONG_INT
6332 If the C compiler supports a working @code{unsigned long long int} type,
6333 define @code{HAVE_UNSIGNED_LONG_LONG_INT}.  However, this test does not test
6334 @code{unsigned long long int} values in preprocessor @code{#if} expressions,
6335 because too many compilers mishandle such expressions.
6336 @xref{Preprocessor Arithmetic}.
6337 @end defmac
6339 @node Generic Types
6340 @subsection Generic Type Checks
6342 These macros are used to check for types not covered by the ``particular''
6343 test macros.
6345 @defmac AC_CHECK_TYPE (@var{type}, @ovar{action-if-found}, @
6346   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6347 @acindex{CHECK_TYPE}
6348 Check whether @var{type} is defined.  It may be a compiler builtin type
6349 or defined by the @var{includes}.  @var{includes} is a series of include
6350 directives, defaulting to @code{AC_INCLUDES_DEFAULT} (@pxref{Default
6351 Includes}), which are used prior to the type under test.
6353 In C, @var{type} must be a type-name, so that the expression @samp{sizeof
6354 (@var{type})} is valid (but @samp{sizeof ((@var{type}))} is not).  The
6355 same test is applied when compiling for C++, which means that in C++
6356 @var{type} should be a type-id and should not be an anonymous
6357 @samp{struct} or @samp{union}.
6358 @end defmac
6361 @defmac AC_CHECK_TYPES (@var{types}, @ovar{action-if-found}, @
6362   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6363 @acindex{CHECK_TYPES}
6364 @cvindex HAVE_@var{type}
6365 For each @var{type} of the @var{types} that is defined, define
6366 @code{HAVE_@var{type}} (in all capitals).  Each @var{type} must follow
6367 the rules of @code{AC_CHECK_TYPE}.  If no @var{includes} are
6368 specified, the default includes are used (@pxref{Default Includes}).  If
6369 @var{action-if-found} is given, it is additional shell code to execute
6370 when one of the types is found.  If @var{action-if-not-found} is given,
6371 it is executed when one of the types is not found.
6373 This macro uses M4 lists:
6374 @example
6375 AC_CHECK_TYPES([ptrdiff_t])
6376 AC_CHECK_TYPES([unsigned long long int, uintmax_t])
6377 AC_CHECK_TYPES([float_t], [], [], [[#include <math.h>]])
6378 @end example
6380 @end defmac
6382 Autoconf, up to 2.13, used to provide to another version of
6383 @code{AC_CHECK_TYPE}, broken by design.  In order to keep backward
6384 compatibility, a simple heuristic, quite safe but not totally, is
6385 implemented.  In case of doubt, read the documentation of the former
6386 @code{AC_CHECK_TYPE}, see @ref{Obsolete Macros}.
6389 @node Compilers and Preprocessors
6390 @section Compilers and Preprocessors
6391 @cindex Compilers
6392 @cindex Preprocessors
6394 @ovindex EXEEXT
6395 All the tests for compilers (@code{AC_PROG_CC}, @code{AC_PROG_CXX},
6396 @code{AC_PROG_F77}) define the output variable @code{EXEEXT} based on
6397 the output of the compiler, typically to the empty string if
6398 Posix and @samp{.exe} if a @acronym{DOS} variant.
6400 @ovindex OBJEXT
6401 They also define the output variable @code{OBJEXT} based on the
6402 output of the compiler, after @file{.c} files have been excluded, typically
6403 to @samp{o} if Posix, @samp{obj} if a @acronym{DOS} variant.
6405 If the compiler being used does not produce executables, the tests fail.  If
6406 the executables can't be run, and cross-compilation is not enabled, they
6407 fail too.  @xref{Manual Configuration}, for more on support for cross
6408 compiling.
6410 @menu
6411 * Specific Compiler Characteristics::  Some portability issues
6412 * Generic Compiler Characteristics::  Language independent tests and features
6413 * C Compiler::                  Checking its characteristics
6414 * C++ Compiler::                Likewise
6415 * Objective C Compiler::        Likewise
6416 * Erlang Compiler and Interpreter::  Likewise
6417 * Fortran Compiler::            Likewise
6418 @end menu
6420 @node Specific Compiler Characteristics
6421 @subsection Specific Compiler Characteristics
6423 Some compilers exhibit different behaviors.
6425 @table @asis
6426 @item Static/Dynamic Expressions
6427 Autoconf relies on a trick to extract one bit of information from the C
6428 compiler: using negative array sizes.  For instance the following
6429 excerpt of a C source demonstrates how to test whether @samp{int} objects are 4
6430 bytes wide:
6432 @example
6433 static int test_array[sizeof (int) == 4 ? 1 : -1];
6434 @end example
6436 @noindent
6437 To our knowledge, there is a single compiler that does not support this
6438 trick: the @acronym{HP} C compilers (the real ones, not only the
6439 ``bundled'') on @acronym{HP-UX} 11.00.
6440 They incorrectly reject the above program with the diagnostic
6441 ``Variable-length arrays cannot have static storage.''
6442 This bug comes from @acronym{HP} compilers' mishandling of @code{sizeof (int)},
6443 not from the @code{? 1 : -1}, and
6444 Autoconf works around this problem by casting @code{sizeof (int)} to
6445 @code{long int} before comparing it.
6446 @end table
6448 @node Generic Compiler Characteristics
6449 @subsection Generic Compiler Characteristics
6451 @anchor{AC_CHECK_SIZEOF}
6452 @defmac AC_CHECK_SIZEOF (@var{type-or-expr}, @ovar{unused}, @
6453   @dvar{includes, AC_INCLUDES_DEFAULT})
6454 @acindex{CHECK_SIZEOF}
6455 @cvindex SIZEOF_@var{type-or-expr}
6456 Define @code{SIZEOF_@var{type-or-expr}} (@pxref{Standard Symbols}) to be
6457 the size in bytes of @var{type-or-expr}, which may be either a type or
6458 an expression returning a value that has a size.  If the expression
6459 @samp{sizeof (@var{type-or-expr})} is invalid, the result is 0.
6460 @var{includes} is a series of include directives, defaulting to
6461 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
6462 prior to the expression under test.
6464 This macro now works even when cross-compiling.  The @var{unused}
6465 argument was used when cross-compiling.
6467 For example, the call
6469 @example
6470 AC_CHECK_SIZEOF([int *])
6471 @end example
6473 @noindent
6474 defines @code{SIZEOF_INT_P} to be 8 on DEC Alpha AXP systems.
6475 @end defmac
6477 @defmac AC_CHECK_ALIGNOF (@var{type}, @dvar{includes, AC_INCLUDES_DEFAULT})
6478 @acindex{CHECK_ALIGNOF}
6479 @cvindex ALIGNOF_@var{type}
6480 Define @code{ALIGNOF_@var{type}} (@pxref{Standard Symbols}) to be the
6481 alignment in bytes of @var{type}.  @samp{@var{type} y;} must be valid as
6482 a structure member declaration.  If @samp{type} is unknown, the result
6483 is 0.  If no @var{includes} are specified, the default includes are used
6484 (@pxref{Default Includes}).
6485 @end defmac
6487 @defmac AC_COMPUTE_INT (@var{var}, @var{expression}, @
6488   @dvar{includes, AC_INCLUDES_DEFAULT}, @ovar{action-if-fails})
6489 @acindex{COMPUTE_INT}
6490 Store into the shell variable @var{var} the value of the integer
6491 @var{expression}.  The
6492 value should fit in an initializer in a C variable of type @code{signed
6493 long}.  To support cross compilation (in which case, the macro only works on
6494 hosts that use twos-complement arithmetic), it should be possible to evaluate
6495 the expression at compile-time.  If no @var{includes} are specified, the
6496 default includes are used (@pxref{Default Includes}).
6498 Execute @var{action-if-fails} if the value cannot be determined correctly.
6499 @end defmac
6501 @defmac AC_LANG_WERROR
6502 @acindex{LANG_WERROR}
6503 Normally Autoconf ignores warnings generated by the compiler, linker, and
6504 preprocessor.  If this macro is used, warnings count as fatal
6505 errors for the current language.  This macro is useful when the
6506 results of configuration are used where warnings are unacceptable; for
6507 instance, if parts of a program are built with the @acronym{GCC}
6508 @option{-Werror}
6509 option.  If the whole program is built using @option{-Werror} it is
6510 often simpler to put @option{-Werror} in the compiler flags (@code{CFLAGS},
6511 etc.).
6512 @end defmac
6514 @defmac AC_OPENMP
6515 @acindex{OPENMP}
6516 @cvindex _OPENMP
6517 @ovindex OPENMP_CFLAGS
6518 @ovindex OPENMP_CXXFLAGS
6519 @ovindex OPENMP_FFLAGS
6520 @ovindex OPENMP_FCFLAGS
6521 OpenMP (@url{http://www.openmp.org/}) specifies extensions of C, C++,
6522 and Fortran that simplify optimization of shared memory parallelism,
6523 which is a common problem on multicore CPUs.
6525 If the current language is C, the macro @code{AC_OPENMP} sets the
6526 variable @code{OPENMP_CFLAGS} to the C compiler flags needed for
6527 supporting OpenMP@.  @code{OPENMP_CFLAGS} is set to empty if the
6528 compiler already supports OpenMP, if it has no way to activate OpenMP
6529 support, or if the user rejects OpenMP support by invoking
6530 @samp{configure} with the @samp{--disable-openmp} option.
6532 @code{OPENMP_CFLAGS} needs to be used when compiling programs, when
6533 preprocessing program source, and when linking programs.  Therefore you
6534 need to add @code{$(OPENMP_CFLAGS)} to the @code{CFLAGS} of C programs
6535 that use OpenMP@.  If you preprocess OpenMP-specific C code, you also
6536 need to add @code{$(OPENMP_CFLAGS)} to @code{CPPFLAGS}.  The presence of
6537 OpenMP support is revealed at compile time by the preprocessor macro
6538 @code{_OPENMP}.
6540 Linking a program with @code{OPENMP_CFLAGS} typically adds one more
6541 shared library to the program's dependencies, so its use is recommended
6542 only on programs that actually require OpenMP.
6544 If the current language is C++, @code{AC_OPENMP} sets the variable
6545 @code{OPENMP_CXXFLAGS}, suitably for the C++ compiler.  The same remarks
6546 hold as for C.
6548 If the current language is Fortran 77 or Fortran, @code{AC_OPENMP} sets
6549 the variable @code{OPENMP_FFLAGS} or @code{OPENMP_FCFLAGS},
6550 respectively.  Similar remarks as for C hold, except that
6551 @code{CPPFLAGS} is not used for Fortran, and no preprocessor macro
6552 signals OpenMP support.
6553 @end defmac
6555 @node C Compiler
6556 @subsection C Compiler Characteristics
6558 The following macros provide ways to find and exercise a C Compiler.
6559 There are a few constructs that ought to be avoided, but do not deserve
6560 being checked for, since they can easily be worked around.
6562 @table @asis
6563 @item Don't use lines containing solitary backslashes
6564 They tickle a bug in the @acronym{HP-UX} C compiler (checked on
6565 @acronym{HP-UX} 10.20,
6566 11.00, and 11i).  When given the following source:
6568 @example
6569 #ifdef __STDC__
6571 * A comment with backslash-newlines in it.  %@{ %@} *\
6574 char str[] = "\\
6575 " A string with backslash-newlines in it %@{ %@} \\
6577 char apostrophe = '\\
6581 #endif
6582 @end example
6584 @noindent
6585 the compiler incorrectly fails with the diagnostics ``Non-terminating
6586 comment at end of file'' and ``Missing @samp{#endif} at end of file.''
6587 Removing the lines with solitary backslashes solves the problem.
6589 @item Don't compile several files at once if output matters to you
6590 Some compilers, such as @acronym{HP}'s, report names of files being
6591 compiled when given more than one file operand.  For instance:
6593 @example
6594 $ @kbd{cc a.c b.c}
6595 a.c:
6596 b.c:
6597 @end example
6599 @noindent
6600 This can cause problems if you observe the output of the compiler to
6601 detect failures.  Invoking @samp{cc -c a.c && cc -c b.c && cc -o c a.o
6602 b.o} solves the issue.
6604 @item Don't rely on @code{#error} failing
6605 The @sc{irix} C compiler does not fail when #error is preprocessed; it
6606 simply emits a diagnostic and continues, exiting successfully.  So,
6607 instead of an error directive like @code{#error "Unsupported word size"}
6608 it is more portable to use an invalid directive like @code{#Unsupported
6609 word size} in Autoconf tests.  In ordinary source code, @code{#error} is
6610 OK, since installers with inadequate compilers like @sc{irix} can simply
6611 examine these compilers' diagnostic output.
6613 @item Don't rely on correct @code{#line} support
6614 On Solaris, @command{c89} (at least Sun C 5.3 through 5.8)
6615 diagnoses @code{#line} directives whose line
6616 numbers are greater than 32767.  Nothing in Posix
6617 makes this invalid.  That is why Autoconf stopped issuing
6618 @code{#line} directives.
6619 @end table
6621 @defmac AC_PROG_CC (@ovar{compiler-search-list})
6622 @acindex{PROG_CC}
6623 @ovindex CC
6624 @ovindex CFLAGS
6625 Determine a C compiler to use.  If @code{CC} is not already set in the
6626 environment, check for @code{gcc} and @code{cc}, then for other C
6627 compilers.  Set output variable @code{CC} to the name of the compiler
6628 found.
6630 This macro may, however, be invoked with an optional first argument
6631 which, if specified, must be a blank-separated list of C compilers to
6632 search for.  This just gives the user an opportunity to specify an
6633 alternative search list for the C compiler.  For example, if you didn't
6634 like the default order, then you could invoke @code{AC_PROG_CC} like
6635 this:
6637 @example
6638 AC_PROG_CC([gcc cl cc])
6639 @end example
6641 If the C compiler does not handle function prototypes correctly by
6642 default, try to add an option to output variable @code{CC} to make it
6643 so.  This macro tries various options that select standard-conformance
6644 modes on various systems.
6646 After calling this macro you can check whether the C compiler has been
6647 set to accept @acronym{ANSI} C89 (@acronym{ISO} C90); if not, the shell
6648 variable
6649 @code{ac_cv_prog_cc_c89} is set to @samp{no}.  See also
6650 @code{AC_C_PROTOTYPES} below.
6652 If using the @acronym{GNU} C compiler, set shell variable @code{GCC} to
6653 @samp{yes}.  If output variable @code{CFLAGS} was not already set, set
6654 it to @option{-g -O2} for the @acronym{GNU} C compiler (@option{-O2} on systems
6655 where @acronym{GCC} does not accept @option{-g}), or @option{-g} for
6656 other compilers.
6657 @end defmac
6659 @anchor{AC_PROG_CC_C_O}
6660 @defmac AC_PROG_CC_C_O
6661 @acindex{PROG_CC_C_O}
6662 @cvindex NO_MINUS_C_MINUS_O
6663 If the C compiler does not accept the @option{-c} and @option{-o} options
6664 simultaneously, define @code{NO_MINUS_C_MINUS_O}.  This macro actually
6665 tests both the compiler found by @code{AC_PROG_CC}, and, if different,
6666 the first @code{cc} in the path.  The test fails if one fails.  This
6667 macro was created for @acronym{GNU} Make to choose the default C compilation
6668 rule.
6669 @end defmac
6672 @defmac AC_PROG_CPP
6673 @acindex{PROG_CPP}
6674 @ovindex CPP
6675 Set output variable @code{CPP} to a command that runs the
6676 C preprocessor.  If @samp{$CC -E} doesn't work, @file{/lib/cpp} is used.
6677 It is only portable to run @code{CPP} on files with a @file{.c}
6678 extension.
6680 Some preprocessors don't indicate missing include files by the error
6681 status.  For such preprocessors an internal variable is set that causes
6682 other macros to check the standard error from the preprocessor and
6683 consider the test failed if any warnings have been reported.
6684 For most preprocessors, though, warnings do not cause include-file
6685 tests to fail unless @code{AC_PROG_CPP_WERROR} is also specified.
6686 @end defmac
6688 @defmac AC_PROG_CPP_WERROR
6689 @acindex{PROG_CPP_WERROR}
6690 @ovindex CPP
6691 This acts like @code{AC_PROG_CPP}, except it treats warnings from the
6692 preprocessor as errors even if the preprocessor exit status indicates
6693 success.  This is useful for avoiding headers that generate mandatory
6694 warnings, such as deprecation notices.
6695 @end defmac
6698 The following macros check for C compiler or machine architecture
6699 features.  To check for characteristics not listed here, use
6700 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}) or
6701 @code{AC_RUN_IFELSE} (@pxref{Runtime}).
6703 @defmac AC_PROG_CC_STDC
6704 @acindex{PROG_CC_STDC}
6705 If the C compiler cannot compile @acronym{ISO} Standard C (currently
6706 C99), try to add an option to output variable @code{CC} to make it work.
6707 If the compiler does not support C99, fall back to supporting
6708 @acronym{ANSI} C89 (@acronym{ISO} C90).
6710 After calling this macro you can check whether the C compiler has been
6711 set to accept Standard C; if not, the shell variable
6712 @code{ac_cv_prog_cc_stdc} is set to @samp{no}.
6713 @end defmac
6715 @defmac AC_PROG_CC_C89
6716 @acindex{PROG_CC_C89}
6717 If the C compiler is not in @acronym{ANSI} C89 (@acronym{ISO} C90) mode by
6718 default, try to add an option to output variable @code{CC} to make it
6719 so.  This macro tries various options that select @acronym{ANSI} C89 on
6720 some system or another.  It considers the compiler to be in
6721 @acronym{ANSI} C89 mode if it handles function prototypes correctly.
6723 After calling this macro you can check whether the C compiler has been
6724 set to accept @acronym{ANSI} C89; if not, the shell variable
6725 @code{ac_cv_prog_cc_c89} is set to @samp{no}.
6727 This macro is called automatically by @code{AC_PROG_CC}.
6728 @end defmac
6730 @defmac AC_PROG_CC_C99
6731 @acindex{PROG_CC_C99}
6732 If the C compiler is not in C99 mode by default, try to add an
6733 option to output variable @code{CC} to make it so.  This macro tries
6734 various options that select C99 on some system or another.  It
6735 considers the compiler to be in C99 mode if it handles @code{_Bool},
6736 @code{//} comments, flexible array members, @code{inline}, signed and
6737 unsigned @code{long long int}, mixed code and declarations, named
6738 initialization of structs,
6739 @code{restrict}, @code{va_copy}, varargs macros, variable declarations
6740 in @code{for} loops, and variable length arrays.
6742 After calling this macro you can check whether the C compiler has been
6743 set to accept C99; if not, the shell variable
6744 @code{ac_cv_prog_cc_c99} is set to @samp{no}.
6745 @end defmac
6747 @defmac AC_C_BACKSLASH_A
6748 @acindex{C_BACKSLASH_A}
6749 @cvindex HAVE_C_BACKSLASH_A
6750 Define @samp{HAVE_C_BACKSLASH_A} to 1 if the C compiler understands
6751 @samp{\a}.
6753 This macro is obsolescent, as current C compilers understand @samp{\a}.
6754 New programs need not use this macro.
6755 @end defmac
6757 @anchor{AC_C_BIGENDIAN}
6758 @defmac AC_C_BIGENDIAN (@ovar{action-if-true}, @ovar{action-if-false}, @
6759   @ovar{action-if-unknown}, @ovar{action-if-universal})
6760 @acindex{C_BIGENDIAN}
6761 @cvindex WORDS_BIGENDIAN
6762 @cindex Endianness
6763 If words are stored with the most significant byte first (like Motorola
6764 and SPARC CPUs), execute @var{action-if-true}.  If words are stored with
6765 the least significant byte first (like Intel and VAX CPUs), execute
6766 @var{action-if-false}.
6768 This macro runs a test-case if endianness cannot be determined from the
6769 system header files.  When cross-compiling, the test-case is not run but
6770 grep'ed for some magic values.  @var{action-if-unknown} is executed if
6771 the latter case fails to determine the byte sex of the host system.
6773 In some cases a single run of a compiler can generate code for multiple
6774 architectures.  This can happen, for example, when generating Mac OS X
6775 universal binary files, which work on both PowerPC and Intel
6776 architectures.  In this case, the different variants might be for
6777 different architectures whose endiannesses differ.  If
6778 @command{configure} detects this, it executes @var{action-if-universal}
6779 instead of @var{action-if-unknown}.
6781 The default for @var{action-if-true} is to define
6782 @samp{WORDS_BIGENDIAN}.  The default for @var{action-if-false} is to do
6783 nothing.  The default for @var{action-if-unknown} is to
6784 abort configure and tell the installer how to bypass this test.
6785 And finally, the default for @var{action-if-universal} is to define
6786 @samp{WORDS_BIGENDIAN} or not, depending on the architecture that the
6787 code is being generated for.
6789 If you use this macro without specifying @var{action-if-universal}, you
6790 should also use @code{AC_CONFIG_HEADERS}; otherwise
6791 @samp{WORDS_BIGENDIAN} may be set incorrectly for Mac OS X universal
6792 binary files.
6793 @end defmac
6795 @anchor{AC_C_CONST}
6796 @defmac AC_C_CONST
6797 @acindex{C_CONST}
6798 @cvindex const
6799 If the C compiler does not fully support the @code{const} keyword,
6800 define @code{const} to be empty.  Some C compilers that do
6801 not define @code{__STDC__} do support @code{const}; some compilers that
6802 define @code{__STDC__} do not completely support @code{const}.  Programs
6803 can simply use @code{const} as if every C compiler supported it; for
6804 those that don't, the makefile or configuration header file
6805 defines it as empty.
6807 Occasionally installers use a C++ compiler to compile C code, typically
6808 because they lack a C compiler.  This causes problems with @code{const},
6809 because C and C++ treat @code{const} differently.  For example:
6811 @example
6812 const int foo;
6813 @end example
6815 @noindent
6816 is valid in C but not in C++.  These differences unfortunately cannot be
6817 papered over by defining @code{const} to be empty.
6819 If @command{autoconf} detects this situation, it leaves @code{const} alone,
6820 as this generally yields better results in practice.  However, using a
6821 C++ compiler to compile C code is not recommended or supported, and
6822 installers who run into trouble in this area should get a C compiler
6823 like @acronym{GCC} to compile their C code.
6825 This macro is obsolescent, as current C compilers support @code{const}.
6826 New programs need not use this macro.
6827 @end defmac
6829 @defmac AC_C_RESTRICT
6830 @acindex{C_RESTRICT}
6831 @cvindex restrict
6832 If the C compiler recognizes a variant spelling for the @code{restrict}
6833 keyword (@code{__restrict}, @code{__restrict__}, or @code{_Restrict}),
6834 then define @code{restrict} to that; this is more likely to do the right
6835 thing with compilers that support language variants where plain
6836 @code{restrict} is not a keyword.  Otherwise, if the C compiler
6837 recognizes the @code{restrict} keyword, don't do anything.
6838 Otherwise, define @code{restrict} to be empty.
6839 Thus, programs may simply use @code{restrict} as if every C compiler
6840 supported it; for those that do not, the makefile
6841 or configuration header defines it away.
6843 Although support in C++ for the @code{restrict} keyword is not
6844 required, several C++ compilers do accept the keyword.
6845 This macro works for them, too.
6846 @end defmac
6848 @defmac AC_C_VOLATILE
6849 @acindex{C_VOLATILE}
6850 @cvindex volatile
6851 If the C compiler does not understand the keyword @code{volatile},
6852 define @code{volatile} to be empty.  Programs can simply use
6853 @code{volatile} as if every C compiler supported it; for those that do
6854 not, the makefile or configuration header defines it as
6855 empty.
6857 If the correctness of your program depends on the semantics of
6858 @code{volatile}, simply defining it to be empty does, in a sense, break
6859 your code.  However, given that the compiler does not support
6860 @code{volatile}, you are at its mercy anyway.  At least your
6861 program compiles, when it wouldn't before.
6862 @xref{Volatile Objects}, for more about @code{volatile}.
6864 In general, the @code{volatile} keyword is a standard C feature, so
6865 you might expect that @code{volatile} is available only when
6866 @code{__STDC__} is defined.  However, Ultrix 4.3's native compiler does
6867 support volatile, but does not define @code{__STDC__}.
6869 This macro is obsolescent, as current C compilers support @code{volatile}.
6870 New programs need not use this macro.
6871 @end defmac
6873 @anchor{AC_C_INLINE}
6874 @defmac AC_C_INLINE
6875 @acindex{C_INLINE}
6876 @cvindex inline
6877 If the C compiler supports the keyword @code{inline}, do nothing.
6878 Otherwise define @code{inline} to @code{__inline__} or @code{__inline}
6879 if it accepts one of those, otherwise define @code{inline} to be empty.
6880 @end defmac
6882 @anchor{AC_C_CHAR_UNSIGNED}
6883 @defmac AC_C_CHAR_UNSIGNED
6884 @acindex{C_CHAR_UNSIGNED}
6885 @cvindex __CHAR_UNSIGNED__
6886 If the C type @code{char} is unsigned, define @code{__CHAR_UNSIGNED__},
6887 unless the C compiler predefines it.
6889 These days, using this macro is not necessary.  The same information can
6890 be determined by this portable alternative, thus avoiding the use of
6891 preprocessor macros in the namespace reserved for the implementation.
6893 @example
6894 #include <limits.h>
6895 #if CHAR_MIN == 0
6896 # define CHAR_UNSIGNED 1
6897 #endif
6898 @end example
6899 @end defmac
6901 @defmac AC_C_STRINGIZE
6902 @acindex{C_STRINGIZE}
6903 @cvindex HAVE_STRINGIZE
6904 If the C preprocessor supports the stringizing operator, define
6905 @code{HAVE_STRINGIZE}.  The stringizing operator is @samp{#} and is
6906 found in macros such as this:
6908 @example
6909 #define x(y) #y
6910 @end example
6912 This macro is obsolescent, as current C compilers support the
6913 stringizing operator.  New programs need not use this macro.
6914 @end defmac
6916 @defmac AC_C_FLEXIBLE_ARRAY_MEMBER
6917 @acindex{C_FLEXIBLE_ARRAY_MEMBER}
6918 @cvindex FLEXIBLE_ARRAY_MEMBER
6919 If the C compiler supports flexible array members, define
6920 @code{FLEXIBLE_ARRAY_MEMBER} to nothing; otherwise define it to 1.
6921 That way, a declaration like this:
6923 @example
6924 struct s
6925   @{
6926     size_t n_vals;
6927     double val[FLEXIBLE_ARRAY_MEMBER];
6928   @};
6929 @end example
6931 @noindent
6932 will let applications use the ``struct hack'' even with compilers that
6933 do not support flexible array members.  To allocate and use such an
6934 object, you can use code like this:
6936 @example
6937 size_t i;
6938 size_t n = compute_value_count ();
6939 struct s *p =
6940    malloc (offsetof (struct s, val)
6941            + n * sizeof (double));
6942 p->n_vals = n;
6943 for (i = 0; i < n; i++)
6944   p->val[i] = compute_value (i);
6945 @end example
6946 @end defmac
6948 @defmac AC_C_VARARRAYS
6949 @acindex{C_VARARRAYS}
6950 @cvindex HAVE_C_VARARRAYS
6951 If the C compiler supports variable-length arrays, define
6952 @code{HAVE_C_VARARRAYS}.  A variable-length array is an array of automatic
6953 storage duration whose length is determined at run time, when the array
6954 is declared.
6955 @end defmac
6957 @defmac AC_C_TYPEOF
6958 @acindex{C_TYPEOF}
6959 @cvindex HAVE_TYPEOF
6960 @cvindex typeof
6961 If the C compiler supports @acronym{GCC}'s @code{typeof} syntax either
6962 directly or
6963 through a different spelling of the keyword (e.g., @code{__typeof__}),
6964 define @code{HAVE_TYPEOF}.  If the support is available only through a
6965 different spelling, define @code{typeof} to that spelling.
6966 @end defmac
6968 @defmac AC_C_PROTOTYPES
6969 @acindex{C_PROTOTYPES}
6970 @cvindex PROTOTYPES
6971 @cvindex __PROTOTYPES
6972 @cvindex PARAMS
6973 If function prototypes are understood by the compiler (as determined by
6974 @code{AC_PROG_CC}), define @code{PROTOTYPES} and @code{__PROTOTYPES}.
6975 Defining @code{__PROTOTYPES} is for the benefit of
6976 header files that cannot use macros that infringe on user name space.
6978 This macro is obsolescent, as current C compilers support prototypes.
6979 New programs need not use this macro.
6980 @end defmac
6982 @anchor{AC_PROG_GCC_TRADITIONAL}
6983 @defmac AC_PROG_GCC_TRADITIONAL
6984 @acindex{PROG_GCC_TRADITIONAL}
6985 @ovindex CC
6986 Add @option{-traditional} to output variable @code{CC} if using the
6987 @acronym{GNU} C compiler and @code{ioctl} does not work properly without
6988 @option{-traditional}.  That usually happens when the fixed header files
6989 have not been installed on an old system.
6991 This macro is obsolescent, since current versions of the @acronym{GNU} C
6992 compiler fix the header files automatically when installed.
6993 @end defmac
6996 @node C++ Compiler
6997 @subsection C++ Compiler Characteristics
7000 @defmac AC_PROG_CXX (@ovar{compiler-search-list})
7001 @acindex{PROG_CXX}
7002 @ovindex CXX
7003 @ovindex CXXFLAGS
7004 Determine a C++ compiler to use.  Check whether the environment variable
7005 @code{CXX} or @code{CCC} (in that order) is set; if so, then set output
7006 variable @code{CXX} to its value.
7008 Otherwise, if the macro is invoked without an argument, then search for
7009 a C++ compiler under the likely names (first @code{g++} and @code{c++}
7010 then other names).  If none of those checks succeed, then as a last
7011 resort set @code{CXX} to @code{g++}.
7013 This macro may, however, be invoked with an optional first argument
7014 which, if specified, must be a blank-separated list of C++ compilers to
7015 search for.  This just gives the user an opportunity to specify an
7016 alternative search list for the C++ compiler.  For example, if you
7017 didn't like the default order, then you could invoke @code{AC_PROG_CXX}
7018 like this:
7020 @example
7021 AC_PROG_CXX([gcc cl KCC CC cxx cc++ xlC aCC c++ g++])
7022 @end example
7024 If using the @acronym{GNU} C++ compiler, set shell variable @code{GXX} to
7025 @samp{yes}.  If output variable @code{CXXFLAGS} was not already set, set
7026 it to @option{-g -O2} for the @acronym{GNU} C++ compiler (@option{-O2} on
7027 systems where G++ does not accept @option{-g}), or @option{-g} for other
7028 compilers.
7029 @end defmac
7031 @defmac AC_PROG_CXXCPP
7032 @acindex{PROG_CXXCPP}
7033 @ovindex CXXCPP
7034 Set output variable @code{CXXCPP} to a command that runs the C++
7035 preprocessor.  If @samp{$CXX -E} doesn't work, @file{/lib/cpp} is used.
7036 It is portable to run @code{CXXCPP} only on files with a @file{.c},
7037 @file{.C}, @file{.cc}, or @file{.cpp} extension.
7039 Some preprocessors don't indicate missing include files by the error
7040 status.  For such preprocessors an internal variable is set that causes
7041 other macros to check the standard error from the preprocessor and
7042 consider the test failed if any warnings have been reported.  However,
7043 it is not known whether such broken preprocessors exist for C++.
7044 @end defmac
7046 @defmac AC_PROG_CXX_C_O
7047 @acindex{PROG_CXX_C_O}
7048 @cvindex CXX_NO_MINUS_C_MINUS_O
7049 Test whether the C++ compiler accepts the options @option{-c} and
7050 @option{-o} simultaneously, and define @code{CXX_NO_MINUS_C_MINUS_O},
7051 if it does not.
7052 @end defmac
7055 @node Objective C Compiler
7056 @subsection Objective C Compiler Characteristics
7059 @defmac AC_PROG_OBJC (@ovar{compiler-search-list})
7060 @acindex{PROG_OBJC}
7061 @ovindex OBJC
7062 @ovindex OBJCFLAGS
7063 Determine an Objective C compiler to use.  If @code{OBJC} is not already
7064 set in the environment, check for Objective C compilers.  Set output
7065 variable @code{OBJC} to the name of the compiler found.
7067 This macro may, however, be invoked with an optional first argument
7068 which, if specified, must be a blank-separated list of Objective C compilers to
7069 search for.  This just gives the user an opportunity to specify an
7070 alternative search list for the Objective C compiler.  For example, if you
7071 didn't like the default order, then you could invoke @code{AC_PROG_OBJC}
7072 like this:
7074 @example
7075 AC_PROG_OBJC([gcc objcc objc])
7076 @end example
7078 If using the @acronym{GNU} Objective C compiler, set shell variable
7079 @code{GOBJC} to @samp{yes}.  If output variable @code{OBJCFLAGS} was not
7080 already set, set it to @option{-g -O2} for the @acronym{GNU} Objective C
7081 compiler (@option{-O2} on systems where @command{gcc} does not accept
7082 @option{-g}), or @option{-g} for other compilers.
7083 @end defmac
7085 @defmac AC_PROG_OBJCPP
7086 @acindex{PROG_OBJCPP}
7087 @ovindex OBJCPP
7088 Set output variable @code{OBJCPP} to a command that runs the Objective C
7089 preprocessor.  If @samp{$OBJC -E} doesn't work, @file{/lib/cpp} is used.
7090 @end defmac
7093 @node Erlang Compiler and Interpreter
7094 @subsection Erlang Compiler and Interpreter Characteristics
7095 @cindex Erlang
7097 Autoconf defines the following macros for determining paths to the essential
7098 Erlang/OTP programs:
7100 @defmac AC_ERLANG_PATH_ERLC (@ovar{value-if-not-found}, @dvar{path, $PATH})
7101 @acindex{ERLANG_PATH_ERLC}
7102 @ovindex ERLC
7103 @ovindex ERLCFLAGS
7104 Determine an Erlang compiler to use.  If @code{ERLC} is not already set in the
7105 environment, check for @command{erlc}.  Set output variable @code{ERLC} to the
7106 complete path of the compiler command found.  In addition, if @code{ERLCFLAGS}
7107 is not set in the environment, set it to an empty value.
7109 The two optional arguments have the same meaning as the two last arguments of
7110 macro @code{AC_PROG_PATH} for looking for the @command{erlc} program.  For
7111 example, to look for @command{erlc} only in the @file{/usr/lib/erlang/bin}
7112 directory:
7114 @example
7115 AC_ERLANG_PATH_ERLC([not found], [/usr/lib/erlang/bin])
7116 @end example
7117 @end defmac
7119 @defmac AC_ERLANG_NEED_ERLC (@dvar{path, $PATH})
7120 @acindex{ERLANG_NEED_ERLC}
7121 A simplified variant of the @code{AC_ERLANG_PATH_ERLC} macro, that prints an
7122 error message and exits the @command{configure} script if the @command{erlc}
7123 program is not found.
7124 @end defmac
7126 @defmac AC_ERLANG_PATH_ERL (@ovar{value-if-not-found}, @dvar{path, $PATH})
7127 @acindex{ERLANG_PATH_ERL}
7128 @ovindex ERL
7129 Determine an Erlang interpreter to use.  If @code{ERL} is not already
7130 set in the
7131 environment, check for @command{erl}.  Set output variable @code{ERL} to the
7132 complete path of the interpreter command found.
7134 The two optional arguments have the same meaning as the two last arguments of
7135 macro @code{AC_PROG_PATH} for looking for the @command{erl} program.  For
7136 example, to look for @command{erl} only in the @file{/usr/lib/erlang/bin}
7137 directory:
7139 @example
7140 AC_ERLANG_PATH_ERL([not found], [/usr/lib/erlang/bin])
7141 @end example
7142 @end defmac
7144 @defmac AC_ERLANG_NEED_ERL (@dvar{path, $PATH})
7145 @acindex{ERLANG_NEED_ERL}
7146 A simplified variant of the @code{AC_ERLANG_PATH_ERL} macro, that prints an
7147 error message and exits the @command{configure} script if the @command{erl}
7148 program is not found.
7149 @end defmac
7152 @node Fortran Compiler
7153 @subsection Fortran Compiler Characteristics
7154 @cindex Fortran
7155 @cindex F77
7157 The Autoconf Fortran support is divided into two categories: legacy
7158 Fortran 77 macros (@code{F77}), and modern Fortran macros (@code{FC}).
7159 The former are intended for traditional Fortran 77 code, and have output
7160 variables like @code{F77}, @code{FFLAGS}, and @code{FLIBS}.  The latter
7161 are for newer programs that can (or must) compile under the newer
7162 Fortran standards, and have output variables like @code{FC},
7163 @code{FCFLAGS}, and @code{FCLIBS}.
7165 Except for two new macros @code{AC_FC_SRCEXT} and
7166 @code{AC_FC_FREEFORM} (see below), the @code{FC} and @code{F77} macros
7167 behave almost identically, and so they are documented together in this
7168 section.
7171 @defmac AC_PROG_F77 (@ovar{compiler-search-list})
7172 @acindex{PROG_F77}
7173 @ovindex F77
7174 @ovindex FFLAGS
7175 Determine a Fortran 77 compiler to use.  If @code{F77} is not already
7176 set in the environment, then check for @code{g77} and @code{f77}, and
7177 then some other names.  Set the output variable @code{F77} to the name
7178 of the compiler found.
7180 This macro may, however, be invoked with an optional first argument
7181 which, if specified, must be a blank-separated list of Fortran 77
7182 compilers to search for.  This just gives the user an opportunity to
7183 specify an alternative search list for the Fortran 77 compiler.  For
7184 example, if you didn't like the default order, then you could invoke
7185 @code{AC_PROG_F77} like this:
7187 @example
7188 AC_PROG_F77([fl32 f77 fort77 xlf g77 f90 xlf90])
7189 @end example
7191 If using @code{g77} (the @acronym{GNU} Fortran 77 compiler), then
7192 set the shell variable @code{G77} to @samp{yes}.
7193 If the output variable @code{FFLAGS} was not already set in the
7194 environment, then set it to @option{-g -02} for @code{g77} (or @option{-O2}
7195 where @code{g77} does not accept @option{-g}).  Otherwise, set
7196 @code{FFLAGS} to @option{-g} for all other Fortran 77 compilers.
7197 @end defmac
7199 @defmac AC_PROG_FC (@ovar{compiler-search-list}, @ovar{dialect})
7200 @acindex{PROG_FC}
7201 @ovindex FC
7202 @ovindex FCFLAGS
7203 Determine a Fortran compiler to use.  If @code{FC} is not already set in
7204 the environment, then @code{dialect} is a hint to indicate what Fortran
7205 dialect to search for; the default is to search for the newest available
7206 dialect.  Set the output variable @code{FC} to the name of the compiler
7207 found.
7209 By default, newer dialects are preferred over older dialects, but if
7210 @code{dialect} is specified then older dialects are preferred starting
7211 with the specified dialect.  @code{dialect} can currently be one of
7212 Fortran 77, Fortran 90, or Fortran 95.  However, this is only a hint of
7213 which compiler @emph{name} to prefer (e.g., @code{f90} or @code{f95}),
7214 and no attempt is made to guarantee that a particular language standard
7215 is actually supported.  Thus, it is preferable that you avoid the
7216 @code{dialect} option, and use AC_PROG_FC only for code compatible with
7217 the latest Fortran standard.
7219 This macro may, alternatively, be invoked with an optional first argument
7220 which, if specified, must be a blank-separated list of Fortran
7221 compilers to search for, just as in @code{AC_PROG_F77}.
7223 If the output variable @code{FCFLAGS} was not already set in the
7224 environment, then set it to @option{-g -02} for @acronym{GNU} @code{g77} (or
7225 @option{-O2} where @code{g77} does not accept @option{-g}).  Otherwise,
7226 set @code{FCFLAGS} to @option{-g} for all other Fortran compilers.
7227 @end defmac
7229 @defmac AC_PROG_F77_C_O
7230 @defmacx AC_PROG_FC_C_O
7231 @acindex{PROG_F77_C_O}
7232 @acindex{PROG_FC_C_O}
7233 @cvindex F77_NO_MINUS_C_MINUS_O
7234 @cvindex FC_NO_MINUS_C_MINUS_O
7235 Test whether the Fortran compiler accepts the options @option{-c} and
7236 @option{-o} simultaneously, and define @code{F77_NO_MINUS_C_MINUS_O} or
7237 @code{FC_NO_MINUS_C_MINUS_O}, respectively, if it does not.
7238 @end defmac
7240 The following macros check for Fortran compiler characteristics.
7241 To check for characteristics not listed here, use
7242 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}) or
7243 @code{AC_RUN_IFELSE} (@pxref{Runtime}), making sure to first set the
7244 current language to Fortran 77 or Fortran via @code{AC_LANG([Fortran 77])}
7245 or @code{AC_LANG(Fortran)} (@pxref{Language Choice}).
7248 @defmac AC_F77_LIBRARY_LDFLAGS
7249 @defmacx AC_FC_LIBRARY_LDFLAGS
7250 @acindex{F77_LIBRARY_LDFLAGS}
7251 @ovindex FLIBS
7252 @acindex{FC_LIBRARY_LDFLAGS}
7253 @ovindex FCLIBS
7254 Determine the linker flags (e.g., @option{-L} and @option{-l}) for the
7255 @dfn{Fortran intrinsic and runtime libraries} that are required to
7256 successfully link a Fortran program or shared library.  The output
7257 variable @code{FLIBS} or @code{FCLIBS} is set to these flags (which
7258 should be included after @code{LIBS} when linking).
7260 This macro is intended to be used in those situations when it is
7261 necessary to mix, e.g., C++ and Fortran source code in a single
7262 program or shared library (@pxref{Mixing Fortran 77 With C and C++, , ,
7263 automake, @acronym{GNU} Automake}).
7265 For example, if object files from a C++ and Fortran compiler must be
7266 linked together, then the C++ compiler/linker must be used for linking
7267 (since special C++-ish things need to happen at link time like calling
7268 global constructors, instantiating templates, enabling exception
7269 support, etc.).
7271 However, the Fortran intrinsic and runtime libraries must be linked in
7272 as well, but the C++ compiler/linker doesn't know by default how to add
7273 these Fortran 77 libraries.  Hence, this macro was created to determine
7274 these Fortran libraries.
7276 The macros @code{AC_F77_DUMMY_MAIN} and @code{AC_FC_DUMMY_MAIN} or
7277 @code{AC_F77_MAIN} and @code{AC_FC_MAIN} are probably also necessary to
7278 link C/C++ with Fortran; see below.
7279 @end defmac
7281 @defmac AC_F77_DUMMY_MAIN (@ovar{action-if-found}, @ovar{action-if-not-found})
7282 @defmacx AC_FC_DUMMY_MAIN (@ovar{action-if-found}, @ovar{action-if-not-found})
7283 @acindex{F77_DUMMY_MAIN}
7284 @cvindex F77_DUMMY_MAIN
7285 With many compilers, the Fortran libraries detected by
7286 @code{AC_F77_LIBRARY_LDFLAGS} or @code{AC_FC_LIBRARY_LDFLAGS} provide
7287 their own @code{main} entry function that initializes things like
7288 Fortran I/O, and which then calls a user-provided entry function named
7289 (say) @code{MAIN__} to run the user's program.  The
7290 @code{AC_F77_DUMMY_MAIN} and @code{AC_FC_DUMMY_MAIN} or
7291 @code{AC_F77_MAIN} and @code{AC_FC_MAIN} macros figure out how to deal with
7292 this interaction.
7294 When using Fortran for purely numerical functions (no I/O, etc.)@: often
7295 one prefers to provide one's own @code{main} and skip the Fortran
7296 library initializations.  In this case, however, one may still need to
7297 provide a dummy @code{MAIN__} routine in order to prevent linking errors
7298 on some systems.  @code{AC_F77_DUMMY_MAIN} or @code{AC_FC_DUMMY_MAIN}
7299 detects whether any such routine is @emph{required} for linking, and
7300 what its name is; the shell variable @code{F77_DUMMY_MAIN} or
7301 @code{FC_DUMMY_MAIN} holds this name, @code{unknown} when no solution
7302 was found, and @code{none} when no such dummy main is needed.
7304 By default, @var{action-if-found} defines @code{F77_DUMMY_MAIN} or
7305 @code{FC_DUMMY_MAIN} to the name of this routine (e.g., @code{MAIN__})
7306 @emph{if} it is required.  @var{action-if-not-found} defaults to
7307 exiting with an error.
7309 In order to link with Fortran routines, the user's C/C++ program should
7310 then include the following code to define the dummy main if it is
7311 needed:
7313 @example
7314 #ifdef F77_DUMMY_MAIN
7315 #  ifdef __cplusplus
7316      extern "C"
7317 #  endif
7318    int F77_DUMMY_MAIN() @{ return 1; @}
7319 #endif
7320 @end example
7322 (Replace @code{F77} with @code{FC} for Fortran instead of Fortran 77.)
7324 Note that this macro is called automatically from @code{AC_F77_WRAPPERS}
7325 or @code{AC_FC_WRAPPERS}; there is generally no need to call it
7326 explicitly unless one wants to change the default actions.
7327 @end defmac
7329 @defmac AC_F77_MAIN
7330 @defmacx AC_FC_MAIN
7331 @acindex{F77_MAIN}
7332 @cvindex F77_MAIN
7333 @acindex{FC_MAIN}
7334 @cvindex FC_MAIN
7335 As discussed above, many Fortran libraries allow you to provide an entry
7336 point called (say) @code{MAIN__} instead of the usual @code{main}, which
7337 is then called by a @code{main} function in the Fortran libraries that
7338 initializes things like Fortran I/O@.  The
7339 @code{AC_F77_MAIN} and @code{AC_FC_MAIN} macros detect whether it is
7340 @emph{possible} to utilize such an alternate main function, and defines
7341 @code{F77_MAIN} and @code{FC_MAIN} to the name of the function.  (If no
7342 alternate main function name is found, @code{F77_MAIN} and @code{FC_MAIN} are
7343 simply defined to @code{main}.)
7345 Thus, when calling Fortran routines from C that perform things like I/O,
7346 one should use this macro and declare the "main" function like so:
7348 @example
7349 #ifdef __cplusplus
7350   extern "C"
7351 #endif
7352 int F77_MAIN(int argc, char *argv[]);
7353 @end example
7355 (Again, replace @code{F77} with @code{FC} for Fortran instead of Fortran 77.)
7356 @end defmac
7358 @defmac AC_F77_WRAPPERS
7359 @defmacx AC_FC_WRAPPERS
7360 @acindex{F77_WRAPPERS}
7361 @cvindex F77_FUNC
7362 @cvindex F77_FUNC_
7363 @acindex{FC_WRAPPERS}
7364 @cvindex FC_FUNC
7365 @cvindex FC_FUNC_
7366 Defines C macros @code{F77_FUNC (name, NAME)}, @code{FC_FUNC (name, NAME)},
7367 @code{F77_FUNC_(name, NAME)}, and @code{FC_FUNC_(name, NAME)} to properly
7368 mangle the names of C/C++ identifiers, and identifiers with underscores,
7369 respectively, so that they match the name-mangling scheme used by the
7370 Fortran compiler.
7372 Fortran is case-insensitive, and in order to achieve this the Fortran
7373 compiler converts all identifiers into a canonical case and format.  To
7374 call a Fortran subroutine from C or to write a C function that is
7375 callable from Fortran, the C program must explicitly use identifiers in
7376 the format expected by the Fortran compiler.  In order to do this, one
7377 simply wraps all C identifiers in one of the macros provided by
7378 @code{AC_F77_WRAPPERS} or @code{AC_FC_WRAPPERS}.  For example, suppose
7379 you have the following Fortran 77 subroutine:
7381 @example
7382       subroutine foobar (x, y)
7383       double precision x, y
7384       y = 3.14159 * x
7385       return
7386       end
7387 @end example
7389 You would then declare its prototype in C or C++ as:
7391 @example
7392 #define FOOBAR_F77 F77_FUNC (foobar, FOOBAR)
7393 #ifdef __cplusplus
7394 extern "C"  /* prevent C++ name mangling */
7395 #endif
7396 void FOOBAR_F77(double *x, double *y);
7397 @end example
7399 Note that we pass both the lowercase and uppercase versions of the
7400 function name to @code{F77_FUNC} so that it can select the right one.
7401 Note also that all parameters to Fortran 77 routines are passed as
7402 pointers (@pxref{Mixing Fortran 77 With C and C++, , , automake, @acronym{GNU}
7403 Automake}).
7405 (Replace @code{F77} with @code{FC} for Fortran instead of Fortran 77.)
7407 Although Autoconf tries to be intelligent about detecting the
7408 name-mangling scheme of the Fortran compiler, there may be Fortran
7409 compilers that it doesn't support yet.  In this case, the above code
7410 generates a compile-time error, but some other behavior
7411 (e.g., disabling Fortran-related features) can be induced by checking
7412 whether @code{F77_FUNC} or @code{FC_FUNC} is defined.
7414 Now, to call that routine from a C program, we would do something like:
7416 @example
7418     double x = 2.7183, y;
7419     FOOBAR_F77 (&x, &y);
7421 @end example
7423 If the Fortran identifier contains an underscore (e.g., @code{foo_bar}),
7424 you should use @code{F77_FUNC_} or @code{FC_FUNC_} instead of
7425 @code{F77_FUNC} or @code{FC_FUNC} (with the same arguments).  This is
7426 because some Fortran compilers mangle names differently if they contain
7427 an underscore.
7428 @end defmac
7430 @defmac AC_F77_FUNC (@var{name}, @ovar{shellvar})
7431 @defmacx AC_FC_FUNC (@var{name}, @ovar{shellvar})
7432 @acindex{F77_FUNC}
7433 @acindex{FC_FUNC}
7434 Given an identifier @var{name}, set the shell variable @var{shellvar} to
7435 hold the mangled version @var{name} according to the rules of the
7436 Fortran linker (see also @code{AC_F77_WRAPPERS} or
7437 @code{AC_FC_WRAPPERS}).  @var{shellvar} is optional; if it is not
7438 supplied, the shell variable is simply @var{name}.  The purpose of
7439 this macro is to give the caller a way to access the name-mangling
7440 information other than through the C preprocessor as above, for example,
7441 to call Fortran routines from some language other than C/C++.
7442 @end defmac
7444 @defmac AC_FC_SRCEXT (@var{ext}, @ovar{action-if-success}, @
7445   @ovar{action-if-failure})
7446 @acindex{FC_SRCEXT}
7447 By default, the @code{FC} macros perform their tests using a @file{.f}
7448 extension for source-code files.  Some compilers, however, only enable
7449 newer language features for appropriately named files, e.g., Fortran 90
7450 features only for @file{.f90} files.  On the other hand, some other
7451 compilers expect all source files to end in @file{.f} and require
7452 special flags to support other file name extensions.  The
7453 @code{AC_FC_SRCEXT} macro deals with both of these issues.
7455 The @code{AC_FC_SRCEXT} tries to get the @code{FC} compiler to accept files
7456 ending with the extension .@var{ext} (i.e., @var{ext} does @emph{not}
7457 contain the dot).  If any special compiler flags are needed for this, it
7458 stores them in the output variable @code{FCFLAGS_}@var{ext}.  This
7459 extension and these flags are then used for all subsequent @code{FC} tests
7460 (until @code{AC_FC_SRCEXT} is called again).
7462 For example, you would use @code{AC_FC_SRCEXT(f90)} to employ the
7463 @file{.f90} extension in future tests, and it would set a
7464 @code{FCFLAGS_f90} output variable with any extra flags that are needed
7465 to compile such files.
7467 The @code{FCFLAGS_}@var{ext} can @emph{not} be simply absorbed into
7468 @code{FCFLAGS}, for two reasons based on the limitations of some
7469 compilers.  First, only one @code{FCFLAGS_}@var{ext} can be used at a
7470 time, so files with different extensions must be compiled separately.
7471 Second, @code{FCFLAGS_}@var{ext} must appear @emph{immediately} before
7472 the source-code file name when compiling.  So, continuing the example
7473 above, you might compile a @file{foo.f90} file in your makefile with the
7474 command:
7476 @example
7477 foo.o: foo.f90
7478      $(FC) -c $(FCFLAGS) $(FCFLAGS_f90) '$(srcdir)/foo.f90'
7479 @end example
7481 If @code{AC_FC_SRCEXT} succeeds in compiling files with the @var{ext}
7482 extension, it calls @var{action-if-success} (defaults to nothing).  If
7483 it fails, and cannot find a way to make the @code{FC} compiler accept such
7484 files, it calls @var{action-if-failure} (defaults to exiting with an
7485 error message).
7487 @end defmac
7489 @defmac AC_FC_FREEFORM (@ovar{action-if-success}, @ovar{action-if-failure})
7490 @acindex{FC_FREEFORM}
7492 The @code{AC_FC_FREEFORM} tries to ensure that the Fortran compiler
7493 (@code{$FC}) allows free-format source code (as opposed to the older
7494 fixed-format style from Fortran 77).  If necessary, it may add some
7495 additional flags to @code{FCFLAGS}.
7497 This macro is most important if you are using the default @file{.f}
7498 extension, since many compilers interpret this extension as indicating
7499 fixed-format source unless an additional flag is supplied.  If you
7500 specify a different extension with @code{AC_FC_SRCEXT}, such as
7501 @file{.f90} or @file{.f95}, then @code{AC_FC_FREEFORM} ordinarily
7502 succeeds without modifying @code{FCFLAGS}.
7504 If @code{AC_FC_FREEFORM} succeeds in compiling free-form source, it
7505 calls @var{action-if-success} (defaults to nothing).  If it fails, it
7506 calls @var{action-if-failure} (defaults to exiting with an error
7507 message).
7508 @end defmac
7510 @node System Services
7511 @section System Services
7513 The following macros check for operating system services or capabilities.
7515 @anchor{AC_PATH_X}
7516 @defmac AC_PATH_X
7517 @acindex{PATH_X}
7518 @evindex XMKMF
7519 @cindex X Window System
7520 Try to locate the X Window System include files and libraries.  If the
7521 user gave the command line options @option{--x-includes=@var{dir}} and
7522 @option{--x-libraries=@var{dir}}, use those directories.
7524 If either or both were not given, get the missing values by running
7525 @code{xmkmf} (or an executable pointed to by the @code{XMKMF}
7526 environment variable) on a trivial @file{Imakefile} and examining the
7527 makefile that it produces.  Setting @code{XMKMF} to @samp{false}
7528 disables this method.
7530 If this method fails to find the X Window System, @command{configure}
7531 looks for the files in several directories where they often reside.
7532 If either method is successful, set the shell variables
7533 @code{x_includes} and @code{x_libraries} to their locations, unless they
7534 are in directories the compiler searches by default.
7536 If both methods fail, or the user gave the command line option
7537 @option{--without-x}, set the shell variable @code{no_x} to @samp{yes};
7538 otherwise set it to the empty string.
7539 @end defmac
7541 @anchor{AC_PATH_XTRA}
7542 @defmac AC_PATH_XTRA
7543 @acindex{PATH_XTRA}
7544 @ovindex X_CFLAGS
7545 @ovindex X_LIBS
7546 @ovindex X_EXTRA_LIBS
7547 @ovindex X_PRE_LIBS
7548 @cvindex X_DISPLAY_MISSING
7549 An enhanced version of @code{AC_PATH_X}.  It adds the C compiler flags
7550 that X needs to output variable @code{X_CFLAGS}, and the X linker flags
7551 to @code{X_LIBS}.  Define @code{X_DISPLAY_MISSING} if X is not
7552 available.
7554 This macro also checks for special libraries that some systems need in
7555 order to compile X programs.  It adds any that the system needs to
7556 output variable @code{X_EXTRA_LIBS}.  And it checks for special X11R6
7557 libraries that need to be linked with before @option{-lX11}, and adds
7558 any found to the output variable @code{X_PRE_LIBS}.
7560 @c This is an incomplete kludge.  Make a real way to do it.
7561 @c If you need to check for other X functions or libraries yourself, then
7562 @c after calling this macro, add the contents of @code{X_EXTRA_LIBS} to
7563 @c @code{LIBS} temporarily, like this: (FIXME - add example)
7564 @end defmac
7566 @anchor{AC_SYS_INTERPRETER}
7567 @defmac AC_SYS_INTERPRETER
7568 @acindex{SYS_INTERPRETER}
7569 Check whether the system supports starting scripts with a line of the
7570 form @samp{#!/bin/sh} to select the interpreter to use for the script.
7571 After running this macro, shell code in @file{configure.ac} can check
7572 the shell variable @code{interpval}; it is set to @samp{yes}
7573 if the system supports @samp{#!}, @samp{no} if not.
7574 @end defmac
7576 @defmac AC_SYS_LARGEFILE
7577 @acindex{SYS_LARGEFILE}
7578 @cvindex _FILE_OFFSET_BITS
7579 @cvindex _LARGE_FILES
7580 @ovindex CC
7581 @cindex Large file support
7582 @cindex LFS
7583 Arrange for
7584 @uref{http://www.unix-systems.org/@/version2/@/whatsnew/@/lfs20mar.html,
7585 large-file support}.  On some hosts, one must use special compiler
7586 options to build programs that can access large files.  Append any such
7587 options to the output variable @code{CC}.  Define
7588 @code{_FILE_OFFSET_BITS} and @code{_LARGE_FILES} if necessary.
7590 Large-file support can be disabled by configuring with the
7591 @option{--disable-largefile} option.
7593 If you use this macro, check that your program works even when
7594 @code{off_t} is wider than @code{long int}, since this is common when
7595 large-file support is enabled.  For example, it is not correct to print
7596 an arbitrary @code{off_t} value @code{X} with @code{printf ("%ld",
7597 (long int) X)}.
7599 The LFS introduced the @code{fseeko} and @code{ftello} functions to
7600 replace their C counterparts @code{fseek} and @code{ftell} that do not
7601 use @code{off_t}.  Take care to use @code{AC_FUNC_FSEEKO} to make their
7602 prototypes available when using them and large-file support is
7603 enabled.
7604 @end defmac
7606 @anchor{AC_SYS_LONG_FILE_NAMES}
7607 @defmac AC_SYS_LONG_FILE_NAMES
7608 @acindex{SYS_LONG_FILE_NAMES}
7609 @cvindex HAVE_LONG_FILE_NAMES
7610 If the system supports file names longer than 14 characters, define
7611 @code{HAVE_LONG_FILE_NAMES}.
7612 @end defmac
7614 @defmac AC_SYS_POSIX_TERMIOS
7615 @acindex{SYS_POSIX_TERMIOS}
7616 @cindex Posix termios headers
7617 @cindex termios Posix headers
7618 Check to see if the Posix termios headers and functions are available on the
7619 system.  If so, set the shell variable @code{ac_cv_sys_posix_termios} to
7620 @samp{yes}.  If not, set the variable to @samp{no}.
7621 @end defmac
7623 @node Posix Variants
7624 @section Posix Variants
7626 The following macro makes it possible to use features of Posix that are
7627 extensions to C, as well as platform extensions not defined by Posix.
7629 @anchor{AC_USE_SYSTEM_EXTENSIONS}
7630 @defmac AC_USE_SYSTEM_EXTENSIONS
7631 @acindex{USE_SYSTEM_EXTENSIONS}
7632 @cvindex _ALL_SOURCE
7633 @cvindex _GNU_SOURCE
7634 @cvindex _MINIX
7635 @cvindex _POSIX_1_SOURCE
7636 @cvindex _POSIX_PTHREAD_SEMANTICS
7637 @cvindex _POSIX_SOURCE
7638 @cvindex _TANDEM_SOURCE
7639 @cvindex __EXTENSIONS__
7640 This macro was introduced in Autoconf 2.60.  If possible, enable
7641 extensions to C or Posix on hosts that normally disable the extensions,
7642 typically due to standards-conformance namespace issues.  This should be
7643 called before any macros that run the C compiler.  The following
7644 preprocessor macros are defined where appropriate:
7646 @table @code
7647 @item _GNU_SOURCE
7648 Enable extensions on @acronym{GNU}/Linux.
7649 @item __EXTENSIONS__
7650 Enable general extensions on Solaris.
7651 @item _POSIX_PTHREAD_SEMANTICS
7652 Enable threading extensions on Solaris.
7653 @item _TANDEM_SOURCE
7654 Enable extensions for the @acronym{HP} NonStop platform.
7655 @item _ALL_SOURCE
7656 Enable extensions for @acronym{AIX} 3, and for Interix.
7657 @item _POSIX_SOURCE
7658 Enable Posix functions for Minix.
7659 @item _POSIX_1_SOURCE
7660 Enable additional Posix functions for Minix.
7661 @item _MINIX
7662 Identify Minix platform.  This particular preprocessor macro is
7663 obsolescent, and may be removed in a future release of Autoconf.
7664 @end table
7665 @end defmac
7668 @node Erlang Libraries
7669 @section Erlang Libraries
7670 @cindex Erlang, Library, checking
7672 The following macros check for an installation of Erlang/OTP, and for the
7673 presence of certain Erlang libraries.  All those macros require the
7674 configuration of an Erlang interpreter and an Erlang compiler
7675 (@pxref{Erlang Compiler and Interpreter}).
7677 @defmac AC_ERLANG_SUBST_ROOT_DIR
7678 @acindex{ERLANG_SUBST_ROOT_DIR}
7679 @ovindex ERLANG_ROOT_DIR
7681 Set the output variable @code{ERLANG_ROOT_DIR} to the path to the base
7682 directory in which Erlang/OTP is installed (as returned by Erlang's
7683 @code{code:root_dir/0} function).  The result of this test is cached if
7684 caching is enabled when running @command{configure}.
7685 @end defmac
7687 @defmac AC_ERLANG_SUBST_LIB_DIR
7688 @acindex{ERLANG_SUBST_LIB_DIR}
7689 @ovindex ERLANG_LIB_DIR
7691 Set the output variable @code{ERLANG_LIB_DIR} to the path of the library
7692 directory of Erlang/OTP (as returned by Erlang's
7693 @code{code:lib_dir/0} function), which subdirectories each contain an installed
7694 Erlang/OTP library.  The result of this test is cached if caching is enabled
7695 when running @command{configure}.
7696 @end defmac
7698 @defmac AC_ERLANG_CHECK_LIB (@var{library}, @ovar{action-if-found}, @
7699   @ovar{action-if-not-found})
7700 @acindex{ERLANG_CHECK_LIB}
7701 @ovindex ERLANG_LIB_DIR_@var{library}
7702 @ovindex ERLANG_LIB_VER_@var{library}
7704 Test whether the Erlang/OTP library @var{library} is installed by
7705 calling Erlang's @code{code:lib_dir/1} function.  The result of this
7706 test is cached if caching is enabled when running @command{configure}.
7707 @var{action-if-found} is a list of shell commands to run if the library
7708 is installed; @var{action-if-not-found} is a list of shell commands to
7709 run if it is not.  Additionally, if the library is installed, the output
7710 variable @samp{ERLANG_LIB_DIR_@var{library}} is set to the path to the
7711 library installation directory, and the output variable
7712 @samp{ERLANG_LIB_VER_@var{library}} is set to the version number that is
7713 part of the subdirectory name, if it is in the standard form
7714 (@code{@var{library}-@var{version}}).  If the directory name does not
7715 have a version part, @samp{ERLANG_LIB_VER_@var{library}} is set to the
7716 empty string.  If the library is not installed,
7717 @samp{ERLANG_LIB_DIR_@var{library}} and
7718 @samp{ERLANG_LIB_VER_@var{library}} are set to @code{"not found"}.  For
7719 example, to check if library @code{stdlib} is installed:
7721 @example
7722 AC_ERLANG_CHECK_LIB([stdlib],
7723   [echo "stdlib version \"$ERLANG_LIB_VER_stdlib\""
7724    echo "is installed in \"$ERLANG_LIB_DIR_stdlib\""],
7725   [AC_MSG_ERROR([stdlib was not found!])])
7726 @end example
7727 @end defmac
7729 In addition to the above macros, which test installed Erlang libraries, the
7730 following macros determine the paths to the directories into which newly built
7731 Erlang libraries are to be installed:
7733 @defmac AC_ERLANG_SUBST_INSTALL_LIB_DIR
7734 @acindex{ERLANG_SUBST_INSTALL_LIB_DIR}
7735 @ovindex ERLANG_INSTALL_LIB_DIR
7737 Set the @code{ERLANG_INSTALL_LIB_DIR} output variable to the directory into
7738 which every built Erlang library should be installed in a separate
7739 subdirectory.
7740 If this variable is not set in the environment when @command{configure} runs,
7741 its default value is @code{$ERLANG_LIB_DIR}, which value is set by the
7742 @code{AC_ERLANG_SUBST_LIB_DIR} macro.
7743 @end defmac
7745 @defmac AC_ERLANG_SUBST_INSTALL_LIB_SUBDIR (@var{library}, @var{version})
7746 @acindex{ERLANG_SUBST_INSTALL_LIB_SUBDIR}
7747 @ovindex ERLANG_INSTALL_LIB_DIR_@var{library}
7749 Set the @samp{ERLANG_INSTALL_LIB_DIR_@var{library}} output variable to the
7750 directory into which the built Erlang library @var{library} version
7751 @var{version} should be installed.  If this variable is not set in the
7752 environment when @command{configure} runs, its default value is
7753 @samp{$ERLANG_INSTALL_LIB_DIR/@var{library}-@var{version}}, the value of the
7754 @code{ERLANG_INSTALL_LIB_DIR} variable being set by the
7755 @code{AC_ERLANG_SUBST_INSTALL_LIB_DIR} macro.
7756 @end defmac
7762 @c ========================================================= Writing Tests
7764 @node Writing Tests
7765 @chapter Writing Tests
7767 If the existing feature tests don't do something you need, you have to
7768 write new ones.  These macros are the building blocks.  They provide
7769 ways for other macros to check whether various kinds of features are
7770 available and report the results.
7772 This chapter contains some suggestions and some of the reasons why the
7773 existing tests are written the way they are.  You can also learn a lot
7774 about how to write Autoconf tests by looking at the existing ones.  If
7775 something goes wrong in one or more of the Autoconf tests, this
7776 information can help you understand the assumptions behind them, which
7777 might help you figure out how to best solve the problem.
7779 These macros check the output of the compiler system of the current
7780 language (@pxref{Language Choice}).  They do not cache the results of
7781 their tests for future use (@pxref{Caching Results}), because they don't
7782 know enough about the information they are checking for to generate a
7783 cache variable name.  They also do not print any messages, for the same
7784 reason.  The checks for particular kinds of features call these macros
7785 and do cache their results and print messages about what they're
7786 checking for.
7788 When you write a feature test that could be applicable to more than one
7789 software package, the best thing to do is encapsulate it in a new macro.
7790 @xref{Writing Autoconf Macros}, for how to do that.
7792 @menu
7793 * Language Choice::             Selecting which language to use for testing
7794 * Writing Test Programs::       Forging source files for compilers
7795 * Running the Preprocessor::    Detecting preprocessor symbols
7796 * Running the Compiler::        Detecting language or header features
7797 * Running the Linker::          Detecting library features
7798 * Runtime::                     Testing for runtime features
7799 * Systemology::                 A zoology of operating systems
7800 * Multiple Cases::              Tests for several possible values
7801 @end menu
7803 @node Language Choice
7804 @section Language Choice
7805 @cindex Language
7807 Autoconf-generated @command{configure} scripts check for the C compiler and
7808 its features by default.  Packages that use other programming languages
7809 (maybe more than one, e.g., C and C++) need to test features of the
7810 compilers for the respective languages.  The following macros determine
7811 which programming language is used in the subsequent tests in
7812 @file{configure.ac}.
7814 @anchor{AC_LANG}
7815 @defmac AC_LANG (@var{language})
7816 Do compilation tests using the compiler, preprocessor, and file
7817 extensions for the specified @var{language}.
7819 Supported languages are:
7821 @table @samp
7822 @item C
7823 Do compilation tests using @code{CC} and @code{CPP} and use extension
7824 @file{.c} for test programs.  Use compilation flags: @code{CPPFLAGS} with
7825 @code{CPP}, and both @code{CPPFLAGS} and @code{CFLAGS} with @code{CC}.
7827 @item C++
7828 Do compilation tests using @code{CXX} and @code{CXXCPP} and use
7829 extension @file{.C} for test programs.  Use compilation flags:
7830 @code{CPPFLAGS} with @code{CXXCPP}, and both @code{CPPFLAGS} and
7831 @code{CXXFLAGS} with @code{CXX}.
7833 @item Fortran 77
7834 Do compilation tests using @code{F77} and use extension @file{.f} for
7835 test programs.  Use compilation flags: @code{FFLAGS}.
7837 @item Fortran
7838 Do compilation tests using @code{FC} and use extension @file{.f} (or
7839 whatever has been set by @code{AC_FC_SRCEXT}) for test programs.  Use
7840 compilation flags: @code{FCFLAGS}.
7842 @item Erlang
7843 @ovindex ERLC
7844 @ovindex ERL
7845 @ovindex ERLCFLAGS
7846 Compile and execute tests using @code{ERLC} and @code{ERL} and use extension
7847 @file{.erl} for test Erlang modules.  Use compilation flags: @code{ERLCFLAGS}.
7849 @item Objective C
7850 Do compilation tests using @code{OBJC} and @code{OBJCPP} and use
7851 extension @file{.m} for test programs.  Use compilation flags:
7852 @code{CPPFLAGS} with @code{OBJCPP}, and both @code{CPPFLAGS} and
7853 @code{OBJCFLAGS} with @code{OBJC}.
7854 @end table
7855 @end defmac
7857 @anchor{AC_LANG_PUSH}
7858 @defmac AC_LANG_PUSH (@var{language})
7859 @acindex{LANG_PUSH}
7860 Remember the current language (as set by @code{AC_LANG}) on a stack, and
7861 then select the @var{language}.  Use this macro and @code{AC_LANG_POP}
7862 in macros that need to temporarily switch to a particular language.
7863 @end defmac
7865 @defmac AC_LANG_POP (@ovar{language})
7866 @acindex{LANG_POP}
7867 Select the language that is saved on the top of the stack, as set by
7868 @code{AC_LANG_PUSH}, and remove it from the stack.
7870 If given, @var{language} specifies the language we just @emph{quit}.  It
7871 is a good idea to specify it when it's known (which should be the
7872 case@dots{}), since Autoconf detects inconsistencies.
7874 @example
7875 AC_LANG_PUSH([Fortran 77])
7876 # Perform some tests on Fortran 77.
7877 # @dots{}
7878 AC_LANG_POP([Fortran 77])
7879 @end example
7880 @end defmac
7882 @defmac AC_LANG_ASSERT (@var{language})
7883 @acindex{LANG_ASSERT} Check statically that the current language is
7884 @var{language}.  You should use this in your language specific macros
7885 to avoid that they be called with an inappropriate language.
7887 This macro runs only at @command{autoconf} time, and incurs no cost at
7888 @command{configure} time.  Sadly enough and because Autoconf is a two
7889 layer language @footnote{Because M4 is not aware of Sh code,
7890 especially conditionals, some optimizations that look nice statically
7891 may produce incorrect results at runtime.}, the macros
7892 @code{AC_LANG_PUSH} and @code{AC_LANG_POP} cannot be ``optimizing'',
7893 therefore as much as possible you ought to avoid using them to wrap
7894 your code, rather, require from the user to run the macro with a
7895 correct current language, and check it with @code{AC_LANG_ASSERT}.
7896 And anyway, that may help the user understand she is running a Fortran
7897 macro while expecting a result about her Fortran 77 compiler@dots{}
7898 @end defmac
7901 @defmac AC_REQUIRE_CPP
7902 @acindex{REQUIRE_CPP}
7903 Ensure that whichever preprocessor would currently be used for tests has
7904 been found.  Calls @code{AC_REQUIRE} (@pxref{Prerequisite Macros}) with an
7905 argument of either @code{AC_PROG_CPP} or @code{AC_PROG_CXXCPP},
7906 depending on which language is current.
7907 @end defmac
7910 @node Writing Test Programs
7911 @section Writing Test Programs
7913 Autoconf tests follow a common scheme: feed some program with some
7914 input, and most of the time, feed a compiler with some source file.
7915 This section is dedicated to these source samples.
7917 @menu
7918 * Guidelines::                  General rules for writing test programs
7919 * Test Functions::              Avoiding pitfalls in test programs
7920 * Generating Sources::          Source program boilerplate
7921 @end menu
7923 @node Guidelines
7924 @subsection Guidelines for Test Programs
7926 The most important rule to follow when writing testing samples is:
7928 @center @emph{Look for realism.}
7930 This motto means that testing samples must be written with the same
7931 strictness as real programs are written.  In particular, you should
7932 avoid ``shortcuts'' and simplifications.
7934 Don't just play with the preprocessor if you want to prepare a
7935 compilation.  For instance, using @command{cpp} to check whether a header is
7936 functional might let your @command{configure} accept a header which
7937 causes some @emph{compiler} error.  Do not hesitate to check a header with
7938 other headers included before, especially required headers.
7940 Make sure the symbols you use are properly defined, i.e., refrain for
7941 simply declaring a function yourself instead of including the proper
7942 header.
7944 Test programs should not write to standard output.  They
7945 should exit with status 0 if the test succeeds, and with status 1
7946 otherwise, so that success
7947 can be distinguished easily from a core dump or other failure;
7948 segmentation violations and other failures produce a nonzero exit
7949 status.  Unless you arrange for @code{exit} to be declared, test
7950 programs should @code{return}, not @code{exit}, from @code{main},
7951 because on many systems @code{exit} is not declared by default.
7953 Test programs can use @code{#if} or @code{#ifdef} to check the values of
7954 preprocessor macros defined by tests that have already run.  For
7955 example, if you call @code{AC_HEADER_STDBOOL}, then later on in
7956 @file{configure.ac} you can have a test program that includes
7957 @file{stdbool.h} conditionally:
7959 @example
7960 @group
7961 #ifdef HAVE_STDBOOL_H
7962 # include <stdbool.h>
7963 #endif
7964 @end group
7965 @end example
7967 Both @code{#if HAVE_STDBOOL_H} and @code{#ifdef HAVE_STDBOOL_H} will
7968 work with any standard C compiler.  Some developers prefer @code{#if}
7969 because it is easier to read, while others prefer @code{#ifdef} because
7970 it avoids diagnostics with picky compilers like @acronym{GCC} with the
7971 @option{-Wundef} option.
7973 If a test program needs to use or create a data file, give it a name
7974 that starts with @file{conftest}, such as @file{conftest.data}.  The
7975 @command{configure} script cleans up by running @samp{rm -f -r conftest*}
7976 after running test programs and if the script is interrupted.
7978 @node Test Functions
7979 @subsection Test Functions
7981 These days it's safe to assume support for function prototypes
7982 (introduced in C89).
7984 Functions that test programs declare should also be conditionalized for
7985 C++, which requires @samp{extern "C"} prototypes.  Make sure to not
7986 include any header files containing clashing prototypes.
7988 @example
7989 #ifdef __cplusplus
7990 extern "C"
7991 #endif
7992 void *valloc (size_t);
7993 @end example
7995 If a test program calls a function with invalid parameters (just to see
7996 whether it exists), organize the program to ensure that it never invokes
7997 that function.  You can do this by calling it in another function that is
7998 never invoked.  You can't do it by putting it after a call to
7999 @code{exit}, because @acronym{GCC} version 2 knows that @code{exit}
8000 never returns
8001 and optimizes out any code that follows it in the same block.
8003 If you include any header files, be sure to call the functions
8004 relevant to them with the correct number of arguments, even if they are
8005 just 0, to avoid compilation errors due to prototypes.  @acronym{GCC}
8006 version 2
8007 has internal prototypes for several functions that it automatically
8008 inlines; for example, @code{memcpy}.  To avoid errors when checking for
8009 them, either pass them the correct number of arguments or redeclare them
8010 with a different return type (such as @code{char}).
8013 @node Generating Sources
8014 @subsection Generating Sources
8016 Autoconf provides a set of macros that can be used to generate test
8017 source files.  They are written to be language generic, i.e., they
8018 actually depend on the current language (@pxref{Language Choice}) to
8019 ``format'' the output properly.
8022 @defmac AC_LANG_CONFTEST (@var{source})
8023 @acindex{LANG_CONFTEST}
8024 Save the @var{source} text in the current test source file:
8025 @file{conftest.@var{extension}} where the @var{extension} depends on the
8026 current language.
8028 Note that the @var{source} is evaluated exactly once, like regular
8029 Autoconf macro arguments, and therefore (i) you may pass a macro
8030 invocation, (ii) if not, be sure to double quote if needed.
8031 @end defmac
8033 @defmac AC_LANG_SOURCE (@var{source})
8034 @acindex{LANG_SOURCE}
8035 Expands into the @var{source}, with the definition of
8036 all the @code{AC_DEFINE} performed so far.
8037 @end defmac
8039 For instance executing (observe the double quotation!):
8041 @example
8042 AC_INIT([Hello], [1.0], [bug-hello@@example.org])
8043 AC_DEFINE([HELLO_WORLD], ["Hello, World\n"],
8044   [Greetings string.])
8045 AC_LANG(C)
8046 AC_LANG_CONFTEST(
8047    [AC_LANG_SOURCE([[const char hw[] = "Hello, World\n";]])])
8048 gcc -E -dD -o - conftest.c
8049 @end example
8051 @noindent
8052 results in:
8054 @example
8055 @dots{}
8056 # 1 "conftest.c"
8058 #define PACKAGE_NAME "Hello"
8059 #define PACKAGE_TARNAME "hello"
8060 #define PACKAGE_VERSION "1.0"
8061 #define PACKAGE_STRING "Hello 1.0"
8062 #define PACKAGE_BUGREPORT "bug-hello@@example.org"
8063 #define HELLO_WORLD "Hello, World\n"
8065 const char hw[] = "Hello, World\n";
8066 @end example
8068 When the test language is Fortran or Erlang, the @code{AC_DEFINE} definitions
8069 are not automatically translated into constants in the source code by this
8070 macro.
8072 @defmac AC_LANG_PROGRAM (@var{prologue}, @var{body})
8073 @acindex{LANG_PROGRAM}
8074 Expands into a source file which consists of the @var{prologue}, and
8075 then @var{body} as body of the main function (e.g., @code{main} in
8076 C).  Since it uses @code{AC_LANG_SOURCE}, the features of the latter are
8077 available.
8078 @end defmac
8080 For instance:
8082 @example
8083 AC_INIT([Hello], [1.0], [bug-hello@@example.org])
8084 AC_DEFINE([HELLO_WORLD], ["Hello, World\n"],
8085   [Greetings string.])
8086 AC_LANG_CONFTEST(
8087 [AC_LANG_PROGRAM([[const char hw[] = "Hello, World\n";]],
8088                  [[fputs (hw, stdout);]])])
8089 gcc -E -dD -o - conftest.c
8090 @end example
8092 @noindent
8093 results in:
8095 @example
8096 @dots{}
8097 # 1 "conftest.c"
8099 #define PACKAGE_NAME "Hello"
8100 #define PACKAGE_TARNAME "hello"
8101 #define PACKAGE_VERSION "1.0"
8102 #define PACKAGE_STRING "Hello 1.0"
8103 #define PACKAGE_BUGREPORT "bug-hello@@example.org"
8104 #define HELLO_WORLD "Hello, World\n"
8106 const char hw[] = "Hello, World\n";
8108 main ()
8110 fputs (hw, stdout);
8111   ;
8112   return 0;
8114 @end example
8116 In Erlang tests, the created source file is that of an Erlang module called
8117 @code{conftest} (@file{conftest.erl}).  This module defines and exports
8118 at least
8119 one @code{start/0} function, which is called to perform the test.  The
8120 @var{prologue} is optional code that is inserted between the module header and
8121 the @code{start/0} function definition.  @var{body} is the body of the
8122 @code{start/0} function without the final period (@pxref{Runtime}, about
8123 constraints on this function's behavior).
8125 For instance:
8127 @example
8128 AC_INIT([Hello], [1.0], [bug-hello@@example.org])
8129 AC_LANG(Erlang)
8130 AC_LANG_CONFTEST(
8131 [AC_LANG_PROGRAM([[-define(HELLO_WORLD, "Hello, world!").]],
8132                  [[io:format("~s~n", [?HELLO_WORLD])]])])
8133 cat conftest.erl
8134 @end example
8136 @noindent
8137 results in:
8139 @example
8140 -module(conftest).
8141 -export([start/0]).
8142 -define(HELLO_WORLD, "Hello, world!").
8143 start() ->
8144 io:format("~s~n", [?HELLO_WORLD])
8146 @end example
8148 @defmac AC_LANG_CALL (@var{prologue}, @var{function})
8149 @acindex{LANG_CALL}
8150 Expands into a source file which consists of the @var{prologue}, and
8151 then a call to the @var{function} as body of the main function (e.g.,
8152 @code{main} in C).  Since it uses @code{AC_LANG_PROGRAM}, the feature
8153 of the latter are available.
8155 This function will probably be replaced in the future by a version
8156 which would enable specifying the arguments.  The use of this macro is
8157 not encouraged, as it violates strongly the typing system.
8159 This macro cannot be used for Erlang tests.
8160 @end defmac
8162 @defmac AC_LANG_FUNC_LINK_TRY (@var{function})
8163 @acindex{LANG_FUNC_LINK_TRY}
8164 Expands into a source file which uses the @var{function} in the body of
8165 the main function (e.g., @code{main} in C).  Since it uses
8166 @code{AC_LANG_PROGRAM}, the features of the latter are available.
8168 As @code{AC_LANG_CALL}, this macro is documented only for completeness.
8169 It is considered to be severely broken, and in the future will be
8170 removed in favor of actual function calls (with properly typed
8171 arguments).
8173 This macro cannot be used for Erlang tests.
8174 @end defmac
8176 @node Running the Preprocessor
8177 @section Running the Preprocessor
8179 Sometimes one might need to run the preprocessor on some source file.
8180 @emph{Usually it is a bad idea}, as you typically need to @emph{compile}
8181 your project, not merely run the preprocessor on it; therefore you
8182 certainly want to run the compiler, not the preprocessor.  Resist the
8183 temptation of following the easiest path.
8185 Nevertheless, if you need to run the preprocessor, then use
8186 @code{AC_PREPROC_IFELSE}.
8188 The macros described in this section cannot be used for tests in Erlang or
8189 Fortran, since those languages require no preprocessor.
8191 @anchor{AC_PREPROC_IFELSE}
8192 @defmac AC_PREPROC_IFELSE (@var{input}, @ovar{action-if-true}, @
8193   @ovar{action-if-false})
8194 @acindex{PREPROC_IFELSE}
8195 Run the preprocessor of the current language (@pxref{Language Choice})
8196 on the @var{input}, run the shell commands @var{action-if-true} on
8197 success, @var{action-if-false} otherwise.  The @var{input} can be made
8198 by @code{AC_LANG_PROGRAM} and friends.
8200 This macro uses @code{CPPFLAGS}, but not @code{CFLAGS}, because
8201 @option{-g}, @option{-O}, etc.@: are not valid options to many C
8202 preprocessors.
8204 It is customary to report unexpected failures with
8205 @code{AC_MSG_FAILURE}.
8206 @end defmac
8208 For instance:
8210 @example
8211 AC_INIT([Hello], [1.0], [bug-hello@@example.org])
8212 AC_DEFINE([HELLO_WORLD], ["Hello, World\n"],
8213   [Greetings string.])
8214 AC_PREPROC_IFELSE(
8215    [AC_LANG_PROGRAM([[const char hw[] = "Hello, World\n";]],
8216                     [[fputs (hw, stdout);]])],
8217    [AC_MSG_RESULT([OK])],
8218    [AC_MSG_FAILURE([unexpected preprocessor failure])])
8219 @end example
8221 @noindent
8222 results in:
8224 @example
8225 checking for gcc... gcc
8226 checking for C compiler default output file name... a.out
8227 checking whether the C compiler works... yes
8228 checking whether we are cross compiling... no
8229 checking for suffix of executables...
8230 checking for suffix of object files... o
8231 checking whether we are using the GNU C compiler... yes
8232 checking whether gcc accepts -g... yes
8233 checking for gcc option to accept ISO C89... none needed
8234 checking how to run the C preprocessor... gcc -E
8236 @end example
8238 @sp 1
8240 The macro @code{AC_TRY_CPP} (@pxref{Obsolete Macros}) used to play the
8241 role of @code{AC_PREPROC_IFELSE}, but double quotes its argument, making
8242 it impossible to use it to elaborate sources.  You are encouraged to
8243 get rid of your old use of the macro @code{AC_TRY_CPP} in favor of
8244 @code{AC_PREPROC_IFELSE}, but, in the first place, are you sure you need
8245 to run the @emph{preprocessor} and not the compiler?
8247 @anchor{AC_EGREP_HEADER}
8248 @defmac AC_EGREP_HEADER (@var{pattern}, @var{header-file}, @
8249   @var{action-if-found}, @ovar{action-if-not-found})
8250 @acindex{EGREP_HEADER}
8251 If the output of running the preprocessor on the system header file
8252 @var{header-file} matches the extended regular expression
8253 @var{pattern}, execute shell commands @var{action-if-found}, otherwise
8254 execute @var{action-if-not-found}.
8255 @end defmac
8257 @anchor{AC_EGREP_CPP}
8258 @defmac AC_EGREP_CPP (@var{pattern}, @var{program}, @
8259   @ovar{action-if-found}, @ovar{action-if-not-found})
8260 @acindex{EGREP_CPP}
8261 @var{program} is the text of a C or C++ program, on which shell
8262 variable, back quote, and backslash substitutions are performed.  If the
8263 output of running the preprocessor on @var{program} matches the
8264 extended regular expression @var{pattern}, execute shell commands
8265 @var{action-if-found}, otherwise execute @var{action-if-not-found}.
8266 @end defmac
8270 @node Running the Compiler
8271 @section Running the Compiler
8273 To check for a syntax feature of the current language's (@pxref{Language
8274 Choice}) compiler, such as whether it recognizes a certain keyword, or
8275 simply to try some library feature, use @code{AC_COMPILE_IFELSE} to try
8276 to compile a small program that uses that feature.
8278 @defmac AC_COMPILE_IFELSE (@var{input}, @ovar{action-if-true}, @
8279   @ovar{action-if-false})
8280 @acindex{COMPILE_IFELSE}
8281 Run the compiler and compilation flags of the current language
8282 (@pxref{Language Choice}) on the @var{input}, run the shell commands
8283 @var{action-if-true} on success, @var{action-if-false} otherwise.  The
8284 @var{input} can be made by @code{AC_LANG_PROGRAM} and friends.
8286 It is customary to report unexpected failures with
8287 @code{AC_MSG_FAILURE}.  This macro does not try to link; use
8288 @code{AC_LINK_IFELSE} if you need to do that (@pxref{Running the
8289 Linker}).
8290 @end defmac
8292 @ovindex ERL
8293 For tests in Erlang, the @var{input} must be the source code of a module named
8294 @code{conftest}.  @code{AC_COMPILE_IFELSE} generates a @file{conftest.beam}
8295 file that can be interpreted by the Erlang virtual machine (@code{ERL}).  It is
8296 recommended to use @code{AC_LANG_PROGRAM} to specify the test program,
8297 to ensure that the Erlang module has the right name.
8299 @node Running the Linker
8300 @section Running the Linker
8302 To check for a library, a function, or a global variable, Autoconf
8303 @command{configure} scripts try to compile and link a small program that
8304 uses it.  This is unlike Metaconfig, which by default uses @code{nm} or
8305 @code{ar} on the C library to try to figure out which functions are
8306 available.  Trying to link with the function is usually a more reliable
8307 approach because it avoids dealing with the variations in the options
8308 and output formats of @code{nm} and @code{ar} and in the location of the
8309 standard libraries.  It also allows configuring for cross-compilation or
8310 checking a function's runtime behavior if needed.  On the other hand,
8311 it can be slower than scanning the libraries once, but accuracy is more
8312 important than speed.
8314 @code{AC_LINK_IFELSE} is used to compile test programs to test for
8315 functions and global variables.  It is also used by @code{AC_CHECK_LIB}
8316 to check for libraries (@pxref{Libraries}), by adding the library being
8317 checked for to @code{LIBS} temporarily and trying to link a small
8318 program.
8320 @anchor{AC_LINK_IFELSE}
8321 @defmac AC_LINK_IFELSE (@var{input}, @ovar{action-if-true}, @
8322   @ovar{action-if-false})
8323 @acindex{LINK_IFELSE}
8324 Run the compiler (and compilation flags) and the linker of the current
8325 language (@pxref{Language Choice}) on the @var{input}, run the shell
8326 commands @var{action-if-true} on success, @var{action-if-false}
8327 otherwise.  The @var{input} can be made by @code{AC_LANG_PROGRAM} and
8328 friends.
8330 @code{LDFLAGS} and @code{LIBS} are used for linking, in addition to the
8331 current compilation flags.
8333 It is customary to report unexpected failures with
8334 @code{AC_MSG_FAILURE}.  This macro does not try to execute the program;
8335 use @code{AC_RUN_IFELSE} if you need to do that (@pxref{Runtime}).
8336 @end defmac
8338 The @code{AC_LINK_IFELSE} macro cannot be used for Erlang tests, since Erlang
8339 programs are interpreted and do not require linking.
8343 @node Runtime
8344 @section Checking Runtime Behavior
8346 Sometimes you need to find out how a system performs at runtime, such
8347 as whether a given function has a certain capability or bug.  If you
8348 can, make such checks when your program runs instead of when it is
8349 configured.  You can check for things like the machine's endianness when
8350 your program initializes itself.
8352 If you really need to test for a runtime behavior while configuring,
8353 you can write a test program to determine the result, and compile and
8354 run it using @code{AC_RUN_IFELSE}.  Avoid running test programs if
8355 possible, because this prevents people from configuring your package for
8356 cross-compiling.
8358 @anchor{AC_RUN_IFELSE}
8359 @defmac AC_RUN_IFELSE (@var{input}, @ovar{action-if-true}, @
8360   @ovar{action-if-false}, @ovar{action-if-cross-compiling})
8361 @acindex{RUN_IFELSE}
8362 If @var{program} compiles and links successfully and returns an exit
8363 status of 0 when executed, run shell commands @var{action-if-true}.
8364 Otherwise, run shell commands @var{action-if-false}.
8366 The @var{input} can be made by @code{AC_LANG_PROGRAM} and friends.
8367 @code{LDFLAGS} and @code{LIBS} are used for linking, in addition to the
8368 compilation flags of the current language (@pxref{Language Choice}).
8370 If the compiler being used does not produce executables that run on the
8371 system where @command{configure} is being run, then the test program is
8372 not run.  If the optional shell commands @var{action-if-cross-compiling}
8373 are given, they are run instead.  Otherwise, @command{configure} prints
8374 an error message and exits.
8376 In the @var{action-if-false} section, the failing exit status is
8377 available in the shell variable @samp{$?}.  This exit status might be
8378 that of a failed compilation, or it might be that of a failed program
8379 execution.
8381 It is customary to report unexpected failures with
8382 @code{AC_MSG_FAILURE}.
8383 @end defmac
8385 Try to provide a pessimistic default value to use when cross-compiling
8386 makes runtime tests impossible.  You do this by passing the optional
8387 last argument to @code{AC_RUN_IFELSE}.  @command{autoconf} prints a
8388 warning message when creating @command{configure} each time it
8389 encounters a call to @code{AC_RUN_IFELSE} with no
8390 @var{action-if-cross-compiling} argument given.  You may ignore the
8391 warning, though users cannot configure your package for
8392 cross-compiling.  A few of the macros distributed with Autoconf produce
8393 this warning message.
8395 To configure for cross-compiling you can also choose a value for those
8396 parameters based on the canonical system name (@pxref{Manual
8397 Configuration}).  Alternatively, set up a test results cache file with
8398 the correct values for the host system (@pxref{Caching Results}).
8400 @ovindex cross_compiling
8401 To provide a default for calls of @code{AC_RUN_IFELSE} that are embedded
8402 in other macros, including a few of the ones that come with Autoconf,
8403 you can test whether the shell variable @code{cross_compiling} is set to
8404 @samp{yes}, and then use an alternate method to get the results instead
8405 of calling the macros.
8407 It is also permissible to temporarily assign to @code{cross_compiling}
8408 in order to force tests to behave as though they are in a
8409 cross-compilation environment, particularly since this provides a way to
8410 test your @var{action-if-cross-compiling} even when you are not using a
8411 cross-compiler.
8413 @example
8414 # We temporarily set cross-compile mode to force AC_COMPUTE_INT
8415 # to use the slow link-only method
8416 save_cross_compiling=$cross_compiling
8417 cross_compiling=yes
8418 AC_COMPUTE_INT([@dots{}])
8419 cross_compiling=$save_cross_compiling
8420 @end example
8422 A C or C++ runtime test should be portable.
8423 @xref{Portable C and C++}.
8425 Erlang tests must exit themselves the Erlang VM by calling the @code{halt/1}
8426 function: the given status code is used to determine the success of the test
8427 (status is @code{0}) or its failure (status is different than @code{0}), as
8428 explained above.  It must be noted that data output through the standard output
8429 (e.g., using @code{io:format/2}) may be truncated when halting the VM.
8430 Therefore, if a test must output configuration information, it is recommended
8431 to create and to output data into the temporary file named @file{conftest.out},
8432 using the functions of module @code{file}.  The @code{conftest.out} file is
8433 automatically deleted by the @code{AC_RUN_IFELSE} macro.  For instance, a
8434 simplified implementation of Autoconf's @code{AC_ERLANG_SUBST_LIB_DIR}
8435 macro is:
8437 @example
8438 AC_INIT([LibdirTest], [1.0], [bug-libdirtest@@example.org])
8439 AC_ERLANG_NEED_ERL
8440 AC_LANG(Erlang)
8441 AC_RUN_IFELSE(
8442   [AC_LANG_PROGRAM([], [dnl
8443     file:write_file("conftest.out", code:lib_dir()),
8444     halt(0)])],
8445   [echo "code:lib_dir() returned: `cat conftest.out`"],
8446   [AC_MSG_FAILURE([test Erlang program execution failed])])
8447 @end example
8450 @node Systemology
8451 @section Systemology
8452 @cindex Systemology
8454 This section aims at presenting some systems and pointers to
8455 documentation.  It may help you addressing particular problems reported
8456 by users.
8458 @uref{http://www.opengroup.org/susv3, Posix-conforming systems} are
8459 derived from the @uref{http://www.bell-labs.com/history/unix/, Unix
8460 operating system}.
8462 The @uref{http://bhami.com/rosetta.html, Rosetta Stone for Unix}
8463 contains a table correlating the features of various Posix-conforming
8464 systems.  @uref{http://www.levenez.com/unix/, Unix History} is a
8465 simplified diagram of how many Unix systems were derived from each
8466 other.
8468 @uref{http://heirloom.sourceforge.net/, The Heirloom Project}
8469 provides some variants of traditional implementations of Unix utilities.
8471 @table @asis
8472 @item Darwin
8473 @cindex Darwin
8474 Darwin is also known as Mac OS X@.  Beware that the file system @emph{can} be
8475 case-preserving, but case insensitive.  This can cause nasty problems,
8476 since for instance the installation attempt for a package having an
8477 @file{INSTALL} file can result in @samp{make install} report that
8478 nothing was to be done!
8480 That's all dependent on whether the file system is a UFS (case
8481 sensitive) or HFS+ (case preserving).  By default Apple wants you to
8482 install the OS on HFS+.  Unfortunately, there are some pieces of
8483 software which really need to be built on UFS@.  We may want to rebuild
8484 Darwin to have both UFS and HFS+ available (and put the /local/build
8485 tree on the UFS).
8487 @item @acronym{QNX} 4.25
8488 @cindex @acronym{QNX} 4.25
8489 @c FIXME: Please, if you feel like writing something more precise,
8490 @c it'd be great.  In particular, I can't understand the difference with
8491 @c QNX Neutrino.
8492 @acronym{QNX} is a realtime operating system running on Intel architecture
8493 meant to be scalable from the small embedded systems to the hundred
8494 processor super-computer.  It claims to be Posix certified.  More
8495 information is available on the
8496 @uref{http://www.qnx.com/, @acronym{QNX} home page}.
8498 @item Tru64
8499 @cindex Tru64
8500 @uref{http://h30097.www3.hp.com/@/docs/,
8501 Documentation of several versions of Tru64} is available in different
8502 formats.
8504 @item Unix version 7
8505 @cindex Unix version 7
8506 @cindex V7
8507 Officially this was called the ``Seventh Edition'' of ``the @sc{unix}
8508 time-sharing system'' but we use the more-common name ``Unix version 7''.
8509 Documentation is available in the
8510 @uref{http://plan9.bell-labs.com/@/7thEdMan/, Unix Seventh Edition Manual}.
8511 Previous versions of Unix are called ``Unix version 6'', etc., but
8512 they were not as widely used.
8513 @end table
8516 @node Multiple Cases
8517 @section Multiple Cases
8519 Some operations are accomplished in several possible ways, depending on
8520 the OS variant.  Checking for them essentially requires a ``case
8521 statement''.  Autoconf does not directly provide one; however, it is
8522 easy to simulate by using a shell variable to keep track of whether a
8523 way to perform the operation has been found yet.
8525 Here is an example that uses the shell variable @code{fstype} to keep
8526 track of whether the remaining cases need to be checked.
8528 @example
8529 @group
8530 AC_MSG_CHECKING([how to get file system type])
8531 fstype=no
8532 # The order of these tests is important.
8533 AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <sys/statvfs.h>
8534 #include <sys/fstyp.h>]])],
8535                   [AC_DEFINE([FSTYPE_STATVFS], [1],
8536                      [Define if statvfs exists.])
8537                    fstype=SVR4])
8538 if test $fstype = no; then
8539   AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <sys/statfs.h>
8540 #include <sys/fstyp.h>]])],
8541                   [AC_DEFINE([FSTYPE_USG_STATFS], [1],
8542                      [Define if USG statfs.])
8543                    fstype=SVR3])
8545 if test $fstype = no; then
8546   AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <sys/statfs.h>
8547 #include <sys/vmount.h>]])]),
8548                   [AC_DEFINE([FSTYPE_AIX_STATFS], [1],
8549                      [Define if AIX statfs.])
8550                    fstype=AIX])
8552 # (more cases omitted here)
8553 AC_MSG_RESULT([$fstype])
8554 @end group
8555 @end example
8557 @c ====================================================== Results of Tests.
8559 @node Results
8560 @chapter Results of Tests
8562 Once @command{configure} has determined whether a feature exists, what can
8563 it do to record that information?  There are four sorts of things it can
8564 do: define a C preprocessor symbol, set a variable in the output files,
8565 save the result in a cache file for future @command{configure} runs, and
8566 print a message letting the user know the result of the test.
8568 @menu
8569 * Defining Symbols::            Defining C preprocessor symbols
8570 * Setting Output Variables::    Replacing variables in output files
8571 * Special Chars in Variables::  Characters to beware of in variables
8572 * Caching Results::             Speeding up subsequent @command{configure} runs
8573 * Printing Messages::           Notifying @command{configure} users
8574 @end menu
8576 @node Defining Symbols
8577 @section Defining C Preprocessor Symbols
8579 A common action to take in response to a feature test is to define a C
8580 preprocessor symbol indicating the results of the test.  That is done by
8581 calling @code{AC_DEFINE} or @code{AC_DEFINE_UNQUOTED}.
8583 By default, @code{AC_OUTPUT} places the symbols defined by these macros
8584 into the output variable @code{DEFS}, which contains an option
8585 @option{-D@var{symbol}=@var{value}} for each symbol defined.  Unlike in
8586 Autoconf version 1, there is no variable @code{DEFS} defined while
8587 @command{configure} is running.  To check whether Autoconf macros have
8588 already defined a certain C preprocessor symbol, test the value of the
8589 appropriate cache variable, as in this example:
8591 @example
8592 AC_CHECK_FUNC([vprintf], [AC_DEFINE([HAVE_VPRINTF], [1],
8593                           [Define if vprintf exists.])])
8594 if test "$ac_cv_func_vprintf" != yes; then
8595   AC_CHECK_FUNC([_doprnt], [AC_DEFINE([HAVE_DOPRNT], [1],
8596                             [Define if _doprnt exists.])])
8598 @end example
8600 If @code{AC_CONFIG_HEADERS} has been called, then instead of creating
8601 @code{DEFS}, @code{AC_OUTPUT} creates a header file by substituting the
8602 correct values into @code{#define} statements in a template file.
8603 @xref{Configuration Headers}, for more information about this kind of
8604 output.
8606 @defmac AC_DEFINE (@var{variable}, @var{value}, @ovar{description})
8607 @defmacx AC_DEFINE (@var{variable})
8608 @cvindex @var{variable}
8609 @acindex{DEFINE}
8610 Define @var{variable} to @var{value} (verbatim), by defining a C
8611 preprocessor macro for @var{variable}.  @var{variable} should be a C
8612 identifier, optionally suffixed by a parenthesized argument list to
8613 define a C preprocessor macro with arguments.  The macro argument list,
8614 if present, should be a comma-separated list of C identifiers, possibly
8615 terminated by an ellipsis @samp{...} if C99 syntax is employed.
8616 @var{variable} should not contain comments, white space, trigraphs,
8617 backslash-newlines, universal character names, or non-@acronym{ASCII}
8618 characters.
8620 @var{value} may contain backslash-escaped newlines, which will be
8621 preserved if you use @code{AC_CONFIG_HEADERS} but flattened if passed
8622 via @code{@@DEFS@@} (with no effect on the compilation, since the
8623 preprocessor sees only one line in the first place).  @var{value} should
8624 not contain raw newlines.  If you are not using
8625 @code{AC_CONFIG_HEADERS}, @var{value} should not contain any @samp{#}
8626 characters, as @command{make} tends to eat them.  To use a shell
8627 variable, use @code{AC_DEFINE_UNQUOTED} instead.
8629 @var{description} is only useful if you are using
8630 @code{AC_CONFIG_HEADERS}.  In this case, @var{description} is put into
8631 the generated @file{config.h.in} as the comment before the macro define.
8632 The following example defines the C preprocessor variable
8633 @code{EQUATION} to be the string constant @samp{"$a > $b"}:
8635 @example
8636 AC_DEFINE([EQUATION], ["$a > $b"],
8637   [Equation string.])
8638 @end example
8640 If neither @var{value} nor @var{description} are given, then
8641 @var{value} defaults to 1 instead of to the empty string.  This is for
8642 backwards compatibility with older versions of Autoconf, but this usage
8643 is obsolescent and may be withdrawn in future versions of Autoconf.
8645 If the @var{variable} is a literal string, it is passed to
8646 @code{m4_pattern_allow} (@pxref{Forbidden Patterns}).
8648 If multiple @code{AC_DEFINE} statements are executed for the same
8649 @var{variable} name (not counting any parenthesized argument list),
8650 the last one wins.
8651 @end defmac
8653 @defmac AC_DEFINE_UNQUOTED (@var{variable}, @var{value}, @ovar{description})
8654 @defmacx AC_DEFINE_UNQUOTED (@var{variable})
8655 @acindex{DEFINE_UNQUOTED}
8656 @cvindex @var{variable}
8657 Like @code{AC_DEFINE}, but three shell expansions are
8658 performed---once---on @var{variable} and @var{value}: variable expansion
8659 (@samp{$}), command substitution (@samp{`}), and backslash escaping
8660 (@samp{\}).  Single and double quote characters in the value have no
8661 special meaning.  Use this macro instead of @code{AC_DEFINE} when
8662 @var{variable} or @var{value} is a shell variable.  Examples:
8664 @example
8665 AC_DEFINE_UNQUOTED([config_machfile], ["$machfile"],
8666   [Configuration machine file.])
8667 AC_DEFINE_UNQUOTED([GETGROUPS_T], [$ac_cv_type_getgroups],
8668   [getgroups return type.])
8669 AC_DEFINE_UNQUOTED([$ac_tr_hdr], [1],
8670   [Translated header name.])
8671 @end example
8672 @end defmac
8674 Due to a syntactical bizarreness of the Bourne shell, do not use
8675 semicolons to separate @code{AC_DEFINE} or @code{AC_DEFINE_UNQUOTED}
8676 calls from other macro calls or shell code; that can cause syntax errors
8677 in the resulting @command{configure} script.  Use either blanks or
8678 newlines.  That is, do this:
8680 @example
8681 AC_CHECK_HEADER([elf.h],
8682   [AC_DEFINE([SVR4], [1], [System V Release 4]) LIBS="-lelf $LIBS"])
8683 @end example
8685 @noindent
8686 or this:
8688 @example
8689 AC_CHECK_HEADER([elf.h],
8690   [AC_DEFINE([SVR4], [1], [System V Release 4])
8691    LIBS="-lelf $LIBS"])
8692 @end example
8694 @noindent
8695 instead of this:
8697 @example
8698 AC_CHECK_HEADER([elf.h],
8699   [AC_DEFINE([SVR4], [1], [System V Release 4]); LIBS="-lelf $LIBS"])
8700 @end example
8702 @node Setting Output Variables
8703 @section Setting Output Variables
8704 @cindex Output variables
8706 Another way to record the results of tests is to set @dfn{output
8707 variables}, which are shell variables whose values are substituted into
8708 files that @command{configure} outputs.  The two macros below create new
8709 output variables.  @xref{Preset Output Variables}, for a list of output
8710 variables that are always available.
8712 @defmac AC_SUBST (@var{variable}, @ovar{value})
8713 @acindex{SUBST}
8714 Create an output variable from a shell variable.  Make @code{AC_OUTPUT}
8715 substitute the variable @var{variable} into output files (typically one
8716 or more makefiles).  This means that @code{AC_OUTPUT}
8717 replaces instances of @samp{@@@var{variable}@@} in input files with the
8718 value that the shell variable @var{variable} has when @code{AC_OUTPUT}
8719 is called.  The value can contain any non-@code{NUL} character, including
8720 newline.
8721 Variable occurrences should not overlap: e.g., an input file should
8722 not contain @samp{@@@var{var1}@@@var{var2}@@} if @var{var1} and @var{var2}
8723 are variable names.
8724 The substituted value is not rescanned for more output variables;
8725 occurrences of @samp{@@@var{variable}@@} in the value are inserted
8726 literally into the output file.  (The algorithm uses the special marker
8727 @code{|#_!!_#|} internally, so neither the substituted value nor the
8728 output file may contain @code{|#_!!_#|}.)
8730 If @var{value} is given, in addition assign it to @var{variable}.
8732 The string @var{variable} is passed to @code{m4_pattern_allow}
8733 (@pxref{Forbidden Patterns}).
8734 @end defmac
8736 @defmac AC_SUBST_FILE (@var{variable})
8737 @acindex{SUBST_FILE}
8738 Another way to create an output variable from a shell variable.  Make
8739 @code{AC_OUTPUT} insert (without substitutions) the contents of the file
8740 named by shell variable @var{variable} into output files.  This means
8741 that @code{AC_OUTPUT} replaces instances of
8742 @samp{@@@var{variable}@@} in output files (such as @file{Makefile.in})
8743 with the contents of the file that the shell variable @var{variable}
8744 names when @code{AC_OUTPUT} is called.  Set the variable to
8745 @file{/dev/null} for cases that do not have a file to insert.
8746 This substitution occurs only when the @samp{@@@var{variable}@@} is on a
8747 line by itself, optionally surrounded by spaces and tabs.  The
8748 substitution replaces the whole line, including the spaces, tabs, and
8749 the terminating newline.
8751 This macro is useful for inserting makefile fragments containing
8752 special dependencies or other @command{make} directives for particular host
8753 or target types into makefiles.  For example, @file{configure.ac}
8754 could contain:
8756 @example
8757 AC_SUBST_FILE([host_frag])
8758 host_frag=$srcdir/conf/sun4.mh
8759 @end example
8761 @noindent
8762 and then a @file{Makefile.in} could contain:
8764 @example
8765 @@host_frag@@
8766 @end example
8768 The string @var{variable} is passed to @code{m4_pattern_allow}
8769 (@pxref{Forbidden Patterns}).
8770 @end defmac
8772 @cindex Precious Variable
8773 @cindex Variable, Precious
8774 Running @command{configure} in varying environments can be extremely
8775 dangerous.  If for instance the user runs @samp{CC=bizarre-cc
8776 ./configure}, then the cache, @file{config.h}, and many other output
8777 files depend upon @command{bizarre-cc} being the C compiler.  If
8778 for some reason the user runs @command{./configure} again, or if it is
8779 run via @samp{./config.status --recheck}, (@xref{Automatic Remaking},
8780 and @pxref{config.status Invocation}), then the configuration can be
8781 inconsistent, composed of results depending upon two different
8782 compilers.
8784 Environment variables that affect this situation, such as @samp{CC}
8785 above, are called @dfn{precious variables}, and can be declared as such
8786 by @code{AC_ARG_VAR}.
8788 @defmac AC_ARG_VAR (@var{variable}, @var{description})
8789 @acindex{ARG_VAR}
8790 Declare @var{variable} is a precious variable, and include its
8791 @var{description} in the variable section of @samp{./configure --help}.
8793 Being precious means that
8794 @itemize @minus
8795 @item
8796 @var{variable} is substituted via @code{AC_SUBST}.
8798 @item
8799 The value of @var{variable} when @command{configure} was launched is
8800 saved in the cache, including if it was not specified on the command
8801 line but via the environment.  Indeed, while @command{configure} can
8802 notice the definition of @code{CC} in @samp{./configure CC=bizarre-cc},
8803 it is impossible to notice it in @samp{CC=bizarre-cc ./configure},
8804 which, unfortunately, is what most users do.
8806 We emphasize that it is the @emph{initial} value of @var{variable} which
8807 is saved, not that found during the execution of @command{configure}.
8808 Indeed, specifying @samp{./configure FOO=foo} and letting
8809 @samp{./configure} guess that @code{FOO} is @code{foo} can be two
8810 different things.
8812 @item
8813 @var{variable} is checked for consistency between two
8814 @command{configure} runs.  For instance:
8816 @example
8817 $ @kbd{./configure --silent --config-cache}
8818 $ @kbd{CC=cc ./configure --silent --config-cache}
8819 configure: error: `CC' was not set in the previous run
8820 configure: error: changes in the environment can compromise \
8821 the build
8822 configure: error: run `make distclean' and/or \
8823 `rm config.cache' and start over
8824 @end example
8826 @noindent
8827 and similarly if the variable is unset, or if its content is changed.
8828 If the content has white space changes only, then the error is degraded
8829 to a warning only, but the old value is reused.
8831 @item
8832 @var{variable} is kept during automatic reconfiguration
8833 (@pxref{config.status Invocation}) as if it had been passed as a command
8834 line argument, including when no cache is used:
8836 @example
8837 $ @kbd{CC=/usr/bin/cc ./configure var=raboof --silent}
8838 $ @kbd{./config.status --recheck}
8839 running CONFIG_SHELL=/bin/sh /bin/sh ./configure var=raboof \
8840   CC=/usr/bin/cc  --no-create --no-recursion
8841 @end example
8842 @end itemize
8843 @end defmac
8845 @node Special Chars in Variables
8846 @section Special Characters in Output Variables
8847 @cindex Output variables, special characters in
8849 Many output variables are intended to be evaluated both by
8850 @command{make} and by the shell.  Some characters are expanded
8851 differently in these two contexts, so to avoid confusion these
8852 variables' values should not contain any of the following characters:
8854 @example
8855 " # $ & ' ( ) * ; < > ? [ \ ^ ` |
8856 @end example
8858 Also, these variables' values should neither contain newlines, nor start
8859 with @samp{~}, nor contain white space or @samp{:} immediately followed
8860 by @samp{~}.  The values can contain nonempty sequences of white space
8861 characters like tabs and spaces, but each such sequence might
8862 arbitrarily be replaced by a single space during substitution.
8864 These restrictions apply both to the values that @command{configure}
8865 computes, and to the values set directly by the user.  For example, the
8866 following invocations of @command{configure} are problematic, since they
8867 attempt to use special characters within @code{CPPFLAGS} and white space
8868 within @code{$(srcdir)}:
8870 @example
8871 CPPFLAGS='-DOUCH="&\"#$*?"' '../My Source/ouch-1.0/configure'
8873 '../My Source/ouch-1.0/configure' CPPFLAGS='-DOUCH="&\"#$*?"'
8874 @end example
8876 @node Caching Results
8877 @section Caching Results
8878 @cindex Cache
8880 To avoid checking for the same features repeatedly in various
8881 @command{configure} scripts (or in repeated runs of one script),
8882 @command{configure} can optionally save the results of many checks in a
8883 @dfn{cache file} (@pxref{Cache Files}).  If a @command{configure} script
8884 runs with caching enabled and finds a cache file, it reads the results
8885 of previous runs from the cache and avoids rerunning those checks.  As a
8886 result, @command{configure} can then run much faster than if it had to
8887 perform all of the checks every time.
8889 @defmac AC_CACHE_VAL (@var{cache-id}, @var{commands-to-set-it})
8890 @acindex{CACHE_VAL}
8891 Ensure that the results of the check identified by @var{cache-id} are
8892 available.  If the results of the check were in the cache file that was
8893 read, and @command{configure} was not given the @option{--quiet} or
8894 @option{--silent} option, print a message saying that the result was
8895 cached; otherwise, run the shell commands @var{commands-to-set-it}.  If
8896 the shell commands are run to determine the value, the value is
8897 saved in the cache file just before @command{configure} creates its output
8898 files.  @xref{Cache Variable Names}, for how to choose the name of the
8899 @var{cache-id} variable.
8901 The @var{commands-to-set-it} @emph{must have no side effects} except for
8902 setting the variable @var{cache-id}, see below.
8903 @end defmac
8905 @defmac AC_CACHE_CHECK (@var{message}, @var{cache-id}, @
8906   @var{commands-to-set-it})
8907 @acindex{CACHE_CHECK}
8908 A wrapper for @code{AC_CACHE_VAL} that takes care of printing the
8909 messages.  This macro provides a convenient shorthand for the most
8910 common way to use these macros.  It calls @code{AC_MSG_CHECKING} for
8911 @var{message}, then @code{AC_CACHE_VAL} with the @var{cache-id} and
8912 @var{commands} arguments, and @code{AC_MSG_RESULT} with @var{cache-id}.
8914 The @var{commands-to-set-it} @emph{must have no side effects} except for
8915 setting the variable @var{cache-id}, see below.
8916 @end defmac
8918 It is common to find buggy macros using @code{AC_CACHE_VAL} or
8919 @code{AC_CACHE_CHECK}, because people are tempted to call
8920 @code{AC_DEFINE} in the @var{commands-to-set-it}.  Instead, the code that
8921 @emph{follows} the call to @code{AC_CACHE_VAL} should call
8922 @code{AC_DEFINE}, by examining the value of the cache variable.  For
8923 instance, the following macro is broken:
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 @noindent
8940 This fails if the cache is enabled: the second time this macro is run,
8941 @code{TRUE_WORKS} @emph{will not be defined}.  The proper implementation
8944 @example
8945 @group
8946 AC_DEFUN([AC_SHELL_TRUE],
8947 [AC_CACHE_CHECK([whether true(1) works], [my_cv_shell_true_works],
8948                 [my_cv_shell_true_works=no
8949                  (true) 2>/dev/null && my_cv_shell_true_works=yes])
8950  if test "$my_cv_shell_true_works" = yes; then
8951    AC_DEFINE([TRUE_WORKS], [1],
8952              [Define if `true(1)' works properly.])
8953  fi
8955 @end group
8956 @end example
8958 Also, @var{commands-to-set-it} should not print any messages, for
8959 example with @code{AC_MSG_CHECKING}; do that before calling
8960 @code{AC_CACHE_VAL}, so the messages are printed regardless of whether
8961 the results of the check are retrieved from the cache or determined by
8962 running the shell commands.
8964 @menu
8965 * Cache Variable Names::        Shell variables used in caches
8966 * Cache Files::                 Files @command{configure} uses for caching
8967 * Cache Checkpointing::         Loading and saving the cache file
8968 @end menu
8970 @node Cache Variable Names
8971 @subsection Cache Variable Names
8972 @cindex Cache variable
8974 The names of cache variables should have the following format:
8976 @example
8977 @var{package-prefix}_cv_@var{value-type}_@var{specific-value}_@ovar{additional-options}
8978 @end example
8980 @noindent
8981 for example, @samp{ac_cv_header_stat_broken} or
8982 @samp{ac_cv_prog_gcc_traditional}.  The parts of the variable name are:
8984 @table @asis
8985 @item @var{package-prefix}
8986 An abbreviation for your package or organization; the same prefix you
8987 begin local Autoconf macros with, except lowercase by convention.
8988 For cache values used by the distributed Autoconf macros, this value is
8989 @samp{ac}.
8991 @item @code{_cv_}
8992 Indicates that this shell variable is a cache value.  This string
8993 @emph{must} be present in the variable name, including the leading
8994 underscore.
8996 @item @var{value-type}
8997 A convention for classifying cache values, to produce a rational naming
8998 system.  The values used in Autoconf are listed in @ref{Macro Names}.
9000 @item @var{specific-value}
9001 Which member of the class of cache values this test applies to.
9002 For example, which function (@samp{alloca}), program (@samp{gcc}), or
9003 output variable (@samp{INSTALL}).
9005 @item @var{additional-options}
9006 Any particular behavior of the specific member that this test applies to.
9007 For example, @samp{broken} or @samp{set}.  This part of the name may
9008 be omitted if it does not apply.
9009 @end table
9011 The values assigned to cache variables may not contain newlines.
9012 Usually, their values are Boolean (@samp{yes} or @samp{no}) or the
9013 names of files or functions; so this is not an important restriction.
9015 @node Cache Files
9016 @subsection Cache Files
9018 A cache file is a shell script that caches the results of configure
9019 tests run on one system so they can be shared between configure scripts
9020 and configure runs.  It is not useful on other systems.  If its contents
9021 are invalid for some reason, the user may delete or edit it.
9023 By default, @command{configure} uses no cache file,
9024 to avoid problems caused by accidental
9025 use of stale cache files.
9027 To enable caching, @command{configure} accepts @option{--config-cache} (or
9028 @option{-C}) to cache results in the file @file{config.cache}.
9029 Alternatively, @option{--cache-file=@var{file}} specifies that
9030 @var{file} be the cache file.  The cache file is created if it does not
9031 exist already.  When @command{configure} calls @command{configure} scripts in
9032 subdirectories, it uses the @option{--cache-file} argument so that they
9033 share the same cache.  @xref{Subdirectories}, for information on
9034 configuring subdirectories with the @code{AC_CONFIG_SUBDIRS} macro.
9036 @file{config.status} only pays attention to the cache file if it is
9037 given the @option{--recheck} option, which makes it rerun
9038 @command{configure}.
9040 It is wrong to try to distribute cache files for particular system types.
9041 There is too much room for error in doing that, and too much
9042 administrative overhead in maintaining them.  For any features that
9043 can't be guessed automatically, use the standard method of the canonical
9044 system type and linking files (@pxref{Manual Configuration}).
9046 The site initialization script can specify a site-wide cache file to
9047 use, instead of the usual per-program cache.  In this case, the cache
9048 file gradually accumulates information whenever someone runs a new
9049 @command{configure} script.  (Running @command{configure} merges the new cache
9050 results with the existing cache file.)  This may cause problems,
9051 however, if the system configuration (e.g., the installed libraries or
9052 compilers) changes and the stale cache file is not deleted.
9054 @node Cache Checkpointing
9055 @subsection Cache Checkpointing
9057 If your configure script, or a macro called from @file{configure.ac}, happens
9058 to abort the configure process, it may be useful to checkpoint the cache
9059 a few times at key points using @code{AC_CACHE_SAVE}.  Doing so
9060 reduces the amount of time it takes to rerun the configure script with
9061 (hopefully) the error that caused the previous abort corrected.
9063 @c FIXME: Do we really want to document this guy?
9064 @defmac AC_CACHE_LOAD
9065 @acindex{CACHE_LOAD}
9066 Loads values from existing cache file, or creates a new cache file if a
9067 cache file is not found.  Called automatically from @code{AC_INIT}.
9068 @end defmac
9070 @defmac AC_CACHE_SAVE
9071 @acindex{CACHE_SAVE}
9072 Flushes all cached values to the cache file.  Called automatically from
9073 @code{AC_OUTPUT}, but it can be quite useful to call
9074 @code{AC_CACHE_SAVE} at key points in @file{configure.ac}.
9075 @end defmac
9077 For instance:
9079 @example
9080 @r{ @dots{} AC_INIT, etc. @dots{}}
9081 @group
9082 # Checks for programs.
9083 AC_PROG_CC
9084 AC_PROG_AWK
9085 @r{ @dots{} more program checks @dots{}}
9086 AC_CACHE_SAVE
9087 @end group
9089 @group
9090 # Checks for libraries.
9091 AC_CHECK_LIB([nsl], [gethostbyname])
9092 AC_CHECK_LIB([socket], [connect])
9093 @r{ @dots{} more lib checks @dots{}}
9094 AC_CACHE_SAVE
9095 @end group
9097 @group
9098 # Might abort@dots{}
9099 AM_PATH_GTK([1.0.2], [], [AC_MSG_ERROR([GTK not in path])])
9100 AM_PATH_GTKMM([0.9.5], [], [AC_MSG_ERROR([GTK not in path])])
9101 @end group
9102 @r{ @dots{} AC_OUTPUT, etc. @dots{}}
9103 @end example
9105 @node Printing Messages
9106 @section Printing Messages
9107 @cindex Messages, from @command{configure}
9109 @command{configure} scripts need to give users running them several kinds
9110 of information.  The following macros print messages in ways appropriate
9111 for each kind.  The arguments to all of them get enclosed in shell
9112 double quotes, so the shell performs variable and back-quote
9113 substitution on them.
9115 These macros are all wrappers around the @command{echo} shell command.
9116 They direct output to the appropriate file descriptor (@pxref{File
9117 Descriptor Macros}).
9118 @command{configure} scripts should rarely need to run @command{echo} directly
9119 to print messages for the user.  Using these macros makes it easy to
9120 change how and when each kind of message is printed; such changes need
9121 only be made to the macro definitions and all the callers change
9122 automatically.
9124 To diagnose static issues, i.e., when @command{autoconf} is run, see
9125 @ref{Diagnostic Macros}.
9127 @defmac AC_MSG_CHECKING (@var{feature-description})
9128 @acindex{MSG_CHECKING}
9129 Notify the user that @command{configure} is checking for a particular
9130 feature.  This macro prints a message that starts with @samp{checking }
9131 and ends with @samp{...} and no newline.  It must be followed by a call
9132 to @code{AC_MSG_RESULT} to print the result of the check and the
9133 newline.  The @var{feature-description} should be something like
9134 @samp{whether the Fortran compiler accepts C++ comments} or @samp{for
9135 c89}.
9137 This macro prints nothing if @command{configure} is run with the
9138 @option{--quiet} or @option{--silent} option.
9139 @end defmac
9141 @anchor{AC_MSG_RESULT}
9142 @defmac AC_MSG_RESULT (@var{result-description})
9143 @acindex{MSG_RESULT}
9144 Notify the user of the results of a check.  @var{result-description} is
9145 almost always the value of the cache variable for the check, typically
9146 @samp{yes}, @samp{no}, or a file name.  This macro should follow a call
9147 to @code{AC_MSG_CHECKING}, and the @var{result-description} should be
9148 the completion of the message printed by the call to
9149 @code{AC_MSG_CHECKING}.
9151 This macro prints nothing if @command{configure} is run with the
9152 @option{--quiet} or @option{--silent} option.
9153 @end defmac
9155 @anchor{AC_MSG_NOTICE}
9156 @defmac AC_MSG_NOTICE (@var{message})
9157 @acindex{MSG_NOTICE}
9158 Deliver the @var{message} to the user.  It is useful mainly to print a
9159 general description of the overall purpose of a group of feature checks,
9160 e.g.,
9162 @example
9163 AC_MSG_NOTICE([checking if stack overflow is detectable])
9164 @end example
9166 This macro prints nothing if @command{configure} is run with the
9167 @option{--quiet} or @option{--silent} option.
9168 @end defmac
9170 @anchor{AC_MSG_ERROR}
9171 @defmac AC_MSG_ERROR (@var{error-description}, @ovar{exit-status})
9172 @acindex{MSG_ERROR}
9173 Notify the user of an error that prevents @command{configure} from
9174 completing.  This macro prints an error message to the standard error
9175 output and exits @command{configure} with @var{exit-status} (1 by default).
9176 @var{error-description} should be something like @samp{invalid value
9177 $HOME for \$HOME}.
9179 The @var{error-description} should start with a lower-case letter, and
9180 ``cannot'' is preferred to ``can't''.
9181 @end defmac
9183 @defmac AC_MSG_FAILURE (@var{error-description}, @ovar{exit-status})
9184 @acindex{MSG_FAILURE}
9185 This @code{AC_MSG_ERROR} wrapper notifies the user of an error that
9186 prevents @command{configure} from completing @emph{and} that additional
9187 details are provided in @file{config.log}.  This is typically used when
9188 abnormal results are found during a compilation.
9189 @end defmac
9191 @anchor{AC_MSG_WARN}
9192 @defmac AC_MSG_WARN (@var{problem-description})
9193 @acindex{MSG_WARN}
9194 Notify the @command{configure} user of a possible problem.  This macro
9195 prints the message to the standard error output; @command{configure}
9196 continues running afterward, so macros that call @code{AC_MSG_WARN} should
9197 provide a default (back-up) behavior for the situations they warn about.
9198 @var{problem-description} should be something like @samp{ln -s seems to
9199 make hard links}.
9200 @end defmac
9204 @c ====================================================== Programming in M4.
9206 @node Programming in M4
9207 @chapter Programming in M4
9208 @cindex M4
9210 Autoconf is written on top of two layers: @dfn{M4sugar}, which provides
9211 convenient macros for pure M4 programming, and @dfn{M4sh}, which
9212 provides macros dedicated to shell script generation.
9214 As of this version of Autoconf, these two layers still contain
9215 experimental macros, whose interface might change in the future.  As a
9216 matter of fact, @emph{anything that is not documented must not be used}.
9218 @menu
9219 * M4 Quotation::                Protecting macros from unwanted expansion
9220 * Using autom4te::              The Autoconf executables backbone
9221 * Programming in M4sugar::      Convenient pure M4 macros
9222 * Programming in M4sh::         Common shell Constructs
9223 * File Descriptor Macros::      File descriptor macros for input and output
9224 @end menu
9226 @node M4 Quotation
9227 @section M4 Quotation
9228 @cindex M4 quotation
9229 @cindex quotation
9231 The most common problem with existing macros is an improper quotation.
9232 This section, which users of Autoconf can skip, but which macro writers
9233 @emph{must} read, first justifies the quotation scheme that was chosen
9234 for Autoconf and then ends with a rule of thumb.  Understanding the
9235 former helps one to follow the latter.
9237 @menu
9238 * Active Characters::           Characters that change the behavior of M4
9239 * One Macro Call::              Quotation and one macro call
9240 * Quoting and Parameters::      M4 vs. shell parameters
9241 * Quotation and Nested Macros::  Macros calling macros
9242 * Changequote is Evil::         Worse than INTERCAL: M4 + changequote
9243 * Quadrigraphs::                Another way to escape special characters
9244 * Quotation Rule Of Thumb::     One parenthesis, one quote
9245 @end menu
9247 @node Active Characters
9248 @subsection Active Characters
9250 To fully understand where proper quotation is important, you first need
9251 to know what the special characters are in Autoconf: @samp{#} introduces
9252 a comment inside which no macro expansion is performed, @samp{,}
9253 separates arguments, @samp{[} and @samp{]} are the quotes themselves,
9254 @samp{(} and @samp{)} (which M4 tries to match by pairs), and finally
9255 @samp{$} inside a macro definition.
9257 In order to understand the delicate case of macro calls, we first have
9258 to present some obvious failures.  Below they are ``obvious-ified'',
9259 but when you find them in real life, they are usually in disguise.
9261 Comments, introduced by a hash and running up to the newline, are opaque
9262 tokens to the top level: active characters are turned off, and there is
9263 no macro expansion:
9265 @example
9266 # define([def], ine)
9267 @result{}# define([def], ine)
9268 @end example
9270 Each time there can be a macro expansion, there is a quotation
9271 expansion, i.e., one level of quotes is stripped:
9273 @example
9274 int tab[10];
9275 @result{}int tab10;
9276 [int tab[10];]
9277 @result{}int tab[10];
9278 @end example
9280 Without this in mind, the reader might try hopelessly to use her macro
9281 @code{array}:
9283 @example
9284 define([array], [int tab[10];])
9285 array
9286 @result{}int tab10;
9287 [array]
9288 @result{}array
9289 @end example
9291 @noindent
9292 How can you correctly output the intended results@footnote{Using
9293 @code{defn}.}?
9296 @node One Macro Call
9297 @subsection One Macro Call
9299 Let's proceed on the interaction between active characters and macros
9300 with this small macro, which just returns its first argument:
9302 @example
9303 define([car], [$1])
9304 @end example
9306 @noindent
9307 The two pairs of quotes above are not part of the arguments of
9308 @code{define}; rather, they are understood by the top level when it
9309 tries to find the arguments of @code{define}.  Therefore, assuming
9310 @code{car} is not already defined, it is equivalent to write:
9312 @example
9313 define(car, $1)
9314 @end example
9316 @noindent
9317 But, while it is acceptable for a @file{configure.ac} to avoid unnecessary
9318 quotes, it is bad practice for Autoconf macros which must both be more
9319 robust and also advocate perfect style.
9321 At the top level, there are only two possibilities: either you
9322 quote or you don't:
9324 @example
9325 car(foo, bar, baz)
9326 @result{}foo
9327 [car(foo, bar, baz)]
9328 @result{}car(foo, bar, baz)
9329 @end example
9331 Let's pay attention to the special characters:
9333 @example
9334 car(#)
9335 @error{}EOF in argument list
9336 @end example
9338 The closing parenthesis is hidden in the comment; with a hypothetical
9339 quoting, the top level understood it this way:
9341 @example
9342 car([#)]
9343 @end example
9345 @noindent
9346 Proper quotation, of course, fixes the problem:
9348 @example
9349 car([#])
9350 @result{}#
9351 @end example
9353 Here are more examples:
9355 @example
9356 car(foo, bar)
9357 @result{}foo
9358 car([foo, bar])
9359 @result{}foo, bar
9360 car((foo, bar))
9361 @result{}(foo, bar)
9362 car([(foo], [bar)])
9363 @result{}(foo
9364 define([a], [b])
9365 @result{}
9366 car(a)
9367 @result{}b
9368 car([a])
9369 @result{}b
9370 car([[a]])
9371 @result{}a
9372 car([[[a]]])
9373 @result{}[a]
9374 @end example
9376 @node Quoting and Parameters
9377 @subsection Quoting and Parameters
9379 When M4 encounters @samp{$} within a macro definition, followed
9380 immediately by a character it recognizes (@samp{0}@dots{}@samp{9},
9381 @samp{#}, @samp{@@}, or @samp{*}), it will perform M4 parameter
9382 expansion.  This happens regardless of how many layers of quotes the
9383 parameter expansion is nested within, or even if it occurs in text that
9384 will be rescanned as a comment.
9386 @example
9387 define([none], [$1])
9388 @result{}
9389 define([one], [[$1]])
9390 @result{}
9391 define([two], [[[$1]]])
9392 @result{}
9393 define([comment], [# $1])
9394 @result{}
9395 define([active], [ACTIVE])
9396 @result{}
9397 none([active])
9398 @result{}ACTIVE
9399 one([active])
9400 @result{}active
9401 two([active])
9402 @result{}[active]
9403 comment([active])
9404 @result{}# active
9405 @end example
9407 On the other hand, since autoconf generates shell code, you often want
9408 to output shell variable expansion, rather than performing M4 parameter
9409 expansion.  To do this, you must use M4 quoting to separate the @samp{$}
9410 from the next character in the definition of your macro.  If the macro
9411 definition occurs in single-quoted text, then insert another level of
9412 quoting; if the usage is already inside a double-quoted string, then
9413 split it into concatenated strings.
9415 @example
9416 define([single], [a single-quoted $[]1 definition])
9417 @result{}
9418 define([double], [[a double-quoted $][1 definition]])
9419 @result{}
9420 single
9421 @result{}a single-quoted $1 definition
9422 double
9423 @result{}a double-quoted $1 definition
9424 @end example
9426 Posix states that M4 implementations are free to provide implementation
9427 extensions when @samp{$@{} is encountered in a macro definition.
9428 Autoconf reserves the longer sequence @samp{$@{@{} for use with planned
9429 extensions that will be available in the future @acronym{GNU} M4 2.0,
9430 but guarantees that all other instances of @samp{$@{} will be output
9431 literally.  Therefore, this idiom can also be used to output shell code
9432 parameter references:
9434 @example
9435 define([first], [$@{1@}])first
9436 @result{}$@{1@}
9437 @end example
9439 Posix also states that @samp{$11} should expand to the first parameter
9440 concatenated with a literal @samp{1}, although some versions of
9441 @acronym{GNU} M4 expand the eleventh parameter instead.  For
9442 portability, you should only use single-digit M4 parameter expansion.
9444 With this in mind, we can explore the cases where macros invoke
9445 macros@enddots{}
9447 @node Quotation and Nested Macros
9448 @subsection Quotation and Nested Macros
9450 The examples below use the following macros:
9452 @example
9453 define([car], [$1])
9454 define([active], [ACT, IVE])
9455 define([array], [int tab[10]])
9456 @end example
9458 Each additional embedded macro call introduces other possible
9459 interesting quotations:
9461 @example
9462 car(active)
9463 @result{}ACT
9464 car([active])
9465 @result{}ACT, IVE
9466 car([[active]])
9467 @result{}active
9468 @end example
9470 In the first case, the top level looks for the arguments of @code{car},
9471 and finds @samp{active}.  Because M4 evaluates its arguments
9472 before applying the macro, @samp{active} is expanded, which results in:
9474 @example
9475 car(ACT, IVE)
9476 @result{}ACT
9477 @end example
9479 @noindent
9480 In the second case, the top level gives @samp{active} as first and only
9481 argument of @code{car}, which results in:
9483 @example
9484 active
9485 @result{}ACT, IVE
9486 @end example
9488 @noindent
9489 i.e., the argument is evaluated @emph{after} the macro that invokes it.
9490 In the third case, @code{car} receives @samp{[active]}, which results in:
9492 @example
9493 [active]
9494 @result{}active
9495 @end example
9497 @noindent
9498 exactly as we already saw above.
9500 The example above, applied to a more realistic example, gives:
9502 @example
9503 car(int tab[10];)
9504 @result{}int tab10;
9505 car([int tab[10];])
9506 @result{}int tab10;
9507 car([[int tab[10];]])
9508 @result{}int tab[10];
9509 @end example
9511 @noindent
9512 Huh?  The first case is easily understood, but why is the second wrong,
9513 and the third right?  To understand that, you must know that after
9514 M4 expands a macro, the resulting text is immediately subjected
9515 to macro expansion and quote removal.  This means that the quote removal
9516 occurs twice---first before the argument is passed to the @code{car}
9517 macro, and second after the @code{car} macro expands to the first
9518 argument.
9520 As the author of the Autoconf macro @code{car}, you then consider it to
9521 be incorrect that your users have to double-quote the arguments of
9522 @code{car}, so you ``fix'' your macro.  Let's call it @code{qar} for
9523 quoted car:
9525 @example
9526 define([qar], [[$1]])
9527 @end example
9529 @noindent
9530 and check that @code{qar} is properly fixed:
9532 @example
9533 qar([int tab[10];])
9534 @result{}int tab[10];
9535 @end example
9537 @noindent
9538 Ahhh!  That's much better.
9540 But note what you've done: now that the result of @code{qar} is always
9541 a literal string, the only time a user can use nested macros is if she
9542 relies on an @emph{unquoted} macro call:
9544 @example
9545 qar(active)
9546 @result{}ACT
9547 qar([active])
9548 @result{}active
9549 @end example
9551 @noindent
9552 leaving no way for her to reproduce what she used to do with @code{car}:
9554 @example
9555 car([active])
9556 @result{}ACT, IVE
9557 @end example
9559 @noindent
9560 Worse yet: she wants to use a macro that produces a set of @code{cpp}
9561 macros:
9563 @example
9564 define([my_includes], [#include <stdio.h>])
9565 car([my_includes])
9566 @result{}#include <stdio.h>
9567 qar(my_includes)
9568 @error{}EOF in argument list
9569 @end example
9571 This macro, @code{qar}, because it double quotes its arguments, forces
9572 its users to leave their macro calls unquoted, which is dangerous.
9573 Commas and other active symbols are interpreted by M4 before
9574 they are given to the macro, often not in the way the users expect.
9575 Also, because @code{qar} behaves differently from the other macros,
9576 it's an exception that should be avoided in Autoconf.
9578 @node Changequote is Evil
9579 @subsection @code{changequote} is Evil
9580 @cindex @code{changequote}
9582 The temptation is often high to bypass proper quotation, in particular
9583 when it's late at night.  Then, many experienced Autoconf hackers
9584 finally surrender to the dark side of the force and use the ultimate
9585 weapon: @code{changequote}.
9587 The M4 builtin @code{changequote} belongs to a set of primitives that
9588 allow one to adjust the syntax of the language to adjust it to one's
9589 needs.  For instance, by default M4 uses @samp{`} and @samp{'} as
9590 quotes, but in the context of shell programming (and actually of most
9591 programming languages), that's about the worst choice one can make:
9592 because of strings and back-quoted expressions in shell code (such as
9593 @samp{'this'} and @samp{`that`}), and because of literal characters in usual
9594 programming languages (as in @samp{'0'}), there are many unbalanced
9595 @samp{`} and @samp{'}.  Proper M4 quotation then becomes a nightmare, if
9596 not impossible.  In order to make M4 useful in such a context, its
9597 designers have equipped it with @code{changequote}, which makes it
9598 possible to choose another pair of quotes.  M4sugar, M4sh, Autoconf, and
9599 Autotest all have chosen to use @samp{[} and @samp{]}.  Not especially
9600 because they are unlikely characters, but @emph{because they are
9601 characters unlikely to be unbalanced}.
9603 There are other magic primitives, such as @code{changecom} to specify
9604 what syntactic forms are comments (it is common to see
9605 @samp{changecom(<!--, -->)} when M4 is used to produce HTML pages),
9606 @code{changeword} and @code{changesyntax} to change other syntactic
9607 details (such as the character to denote the @var{n}th argument, @samp{$} by
9608 default, the parentheses around arguments, etc.).
9610 These primitives are really meant to make M4 more useful for specific
9611 domains: they should be considered like command line options:
9612 @option{--quotes}, @option{--comments}, @option{--words}, and
9613 @option{--syntax}.  Nevertheless, they are implemented as M4 builtins, as
9614 it makes M4 libraries self contained (no need for additional options).
9616 There lies the problem@enddots{}
9618 @sp 1
9620 The problem is that it is then tempting to use them in the middle of an
9621 M4 script, as opposed to its initialization.  This, if not carefully
9622 thought out, can lead to disastrous effects: @emph{you are changing the
9623 language in the middle of the execution}.  Changing and restoring the
9624 syntax is often not enough: if you happened to invoke macros in between,
9625 these macros are lost, as the current syntax is probably not
9626 the one they were implemented with.
9628 @c FIXME: I've been looking for a short, real case example, but I
9629 @c lost them all :(
9632 @node Quadrigraphs
9633 @subsection Quadrigraphs
9634 @cindex quadrigraphs
9635 @cindex @samp{@@S|@@}
9636 @cindex @samp{@@&t@@}
9637 @c Info cannot handle `:' in index entries.
9638 @c @cindex @samp{@@<:@@}
9639 @c @cindex @samp{@@:>@@}
9640 @c @cindex @samp{@@%:@@}
9641 @c @cindex @samp{@@@{:@@}
9642 @c @cindex @samp{@@:@}@@}
9644 When writing an Autoconf macro you may occasionally need to generate
9645 special characters that are difficult to express with the standard
9646 Autoconf quoting rules.  For example, you may need to output the regular
9647 expression @samp{[^[]}, which matches any character other than @samp{[}.
9648 This expression contains unbalanced brackets so it cannot be put easily
9649 into an M4 macro.
9651 Additionally, there are a few m4sugar macros (such as @code{m4_split}
9652 and @code{m4_expand}) which internally use special markers in addition
9653 to the regular quoting characters.  If the arguments to these macros
9654 contain the literal strings @samp{-=<@{(} or @samp{)@}>=-}, the macros
9655 might behave incorrectly.
9657 You can work around these problems by using one of the following
9658 @dfn{quadrigraphs}:
9660 @table @samp
9661 @item @@<:@@
9662 @samp{[}
9663 @item @@:>@@
9664 @samp{]}
9665 @item @@S|@@
9666 @samp{$}
9667 @item @@%:@@
9668 @samp{#}
9669 @item @@@{:@@
9670 @samp{(}
9671 @item @@:@}@@
9672 @samp{)}
9673 @item @@&t@@
9674 Expands to nothing.
9675 @end table
9677 Quadrigraphs are replaced at a late stage of the translation process,
9678 after @command{m4} is run, so they do not get in the way of M4 quoting.
9679 For example, the string @samp{^@@<:@@}, independently of its quotation,
9680 appears as @samp{^[} in the output.
9682 The empty quadrigraph can be used:
9684 @itemize @minus
9685 @item to mark trailing spaces explicitly
9687 Trailing spaces are smashed by @command{autom4te}.  This is a feature.
9689 @item to produce quadrigraphs and other strings reserved by m4sugar
9691 For instance @samp{@@<@@&t@@:@@} produces @samp{@@<:@@}.  For a more
9692 contrived example:
9694 @example
9695 m4_define([a], [A])m4_define([b], [B])m4_define([c], [C])dnl
9696 m4_split([a )@}>=- b -=<@{( c])
9697 @result{}[a], [], [B], [], [c]
9698 m4_split([a )@}@@&t@@>=- b -=<@@&t@@@{( c])
9699 @result{}[a], [)@}>=-], [b], [-=<@{(], [c]
9700 @end example
9702 @item to escape @emph{occurrences} of forbidden patterns
9704 For instance you might want to mention @code{AC_FOO} in a comment, while
9705 still being sure that @command{autom4te} still catches unexpanded
9706 @samp{AC_*}.  Then write @samp{AC@@&t@@_FOO}.
9707 @end itemize
9709 The name @samp{@@&t@@} was suggested by Paul Eggert:
9711 @quotation
9712 I should give some credit to the @samp{@@&t@@} pun.  The @samp{&} is my
9713 own invention, but the @samp{t} came from the source code of the
9714 @sc{algol68c} compiler, written by Steve Bourne (of Bourne shell fame),
9715 and which used @samp{mt} to denote the empty string.  In C, it would
9716 have looked like something like:
9718 @example
9719 char const mt[] = "";
9720 @end example
9722 @noindent
9723 but of course the source code was written in Algol 68.
9725 I don't know where he got @samp{mt} from: it could have been his own
9726 invention, and I suppose it could have been a common pun around the
9727 Cambridge University computer lab at the time.
9728 @end quotation
9730 @node Quotation Rule Of Thumb
9731 @subsection Quotation Rule Of Thumb
9733 To conclude, the quotation rule of thumb is:
9735 @center @emph{One pair of quotes per pair of parentheses.}
9737 Never over-quote, never under-quote, in particular in the definition of
9738 macros.  In the few places where the macros need to use brackets
9739 (usually in C program text or regular expressions), properly quote
9740 @emph{the arguments}!
9742 It is common to read Autoconf programs with snippets like:
9744 @example
9745 AC_TRY_LINK(
9746 changequote(<<, >>)dnl
9747 <<#include <time.h>
9748 #ifndef tzname /* For SGI.  */
9749 extern char *tzname[]; /* RS6000 and others reject char **tzname.  */
9750 #endif>>,
9751 changequote([, ])dnl
9752 [atoi (*tzname);], ac_cv_var_tzname=yes, ac_cv_var_tzname=no)
9753 @end example
9755 @noindent
9756 which is incredibly useless since @code{AC_TRY_LINK} is @emph{already}
9757 double quoting, so you just need:
9759 @example
9760 AC_TRY_LINK(
9761 [#include <time.h>
9762 #ifndef tzname /* For SGI.  */
9763 extern char *tzname[]; /* RS6000 and others reject char **tzname.  */
9764 #endif],
9765             [atoi (*tzname);],
9766             [ac_cv_var_tzname=yes],
9767             [ac_cv_var_tzname=no])
9768 @end example
9770 @noindent
9771 The M4-fluent reader might note that these two examples are rigorously
9772 equivalent, since M4 swallows both the @samp{changequote(<<, >>)}
9773 and @samp{<<} @samp{>>} when it @dfn{collects} the arguments: these
9774 quotes are not part of the arguments!
9776 Simplified, the example above is just doing this:
9778 @example
9779 changequote(<<, >>)dnl
9780 <<[]>>
9781 changequote([, ])dnl
9782 @end example
9784 @noindent
9785 instead of simply:
9787 @example
9788 [[]]
9789 @end example
9791 With macros that do not double quote their arguments (which is the
9792 rule), double-quote the (risky) literals:
9794 @example
9795 AC_LINK_IFELSE([AC_LANG_PROGRAM(
9796 [[#include <time.h>
9797 #ifndef tzname /* For SGI.  */
9798 extern char *tzname[]; /* RS6000 and others reject char **tzname.  */
9799 #endif]],
9800                                 [atoi (*tzname);])],
9801                [ac_cv_var_tzname=yes],
9802                [ac_cv_var_tzname=no])
9803 @end example
9805 Please note that the macro @code{AC_TRY_LINK} is obsolete, so you really
9806 should be using @code{AC_LINK_IFELSE} instead.
9808 @xref{Quadrigraphs}, for what to do if you run into a hopeless case
9809 where quoting does not suffice.
9811 When you create a @command{configure} script using newly written macros,
9812 examine it carefully to check whether you need to add more quotes in
9813 your macros.  If one or more words have disappeared in the M4
9814 output, you need more quotes.  When in doubt, quote.
9816 However, it's also possible to put on too many layers of quotes.  If
9817 this happens, the resulting @command{configure} script may contain
9818 unexpanded macros.  The @command{autoconf} program checks for this problem
9819 by looking for the string @samp{AC_} in @file{configure}.  However, this
9820 heuristic does not work in general: for example, it does not catch
9821 overquoting in @code{AC_DEFINE} descriptions.
9824 @c ---------------------------------------- Using autom4te
9826 @node Using autom4te
9827 @section Using @command{autom4te}
9829 The Autoconf suite, including M4sugar, M4sh, and Autotest, in addition
9830 to Autoconf per se, heavily rely on M4.  All these different uses
9831 revealed common needs factored into a layer over M4:
9832 @command{autom4te}@footnote{
9834 Yet another great name from Lars J. Aas.
9838 @command{autom4te} is a preprocessor that is like @command{m4}.
9839 It supports M4 extensions designed for use in tools like Autoconf.
9841 @menu
9842 * autom4te Invocation::         A @acronym{GNU} M4 wrapper
9843 * Customizing autom4te::        Customizing the Autoconf package
9844 @end menu
9846 @node autom4te Invocation
9847 @subsection Invoking @command{autom4te}
9849 The command line arguments are modeled after M4's:
9851 @example
9852 autom4te @var{options} @var{files}
9853 @end example
9855 @noindent
9856 @evindex M4
9857 where the @var{files} are directly passed to @command{m4}.  By default,
9858 @acronym{GNU} M4 is found during configuration, but the environment
9859 variable
9860 @env{M4} can be set to tell @command{autom4te} where to look.  In addition
9861 to the regular expansion, it handles the replacement of the quadrigraphs
9862 (@pxref{Quadrigraphs}), and of @samp{__oline__}, the current line in the
9863 output.  It supports an extended syntax for the @var{files}:
9865 @table @file
9866 @item @var{file}.m4f
9867 This file is an M4 frozen file.  Note that @emph{all the previous files
9868 are ignored}.  See the option @option{--melt} for the rationale.
9870 @item @var{file}?
9871 If found in the library path, the @var{file} is included for expansion,
9872 otherwise it is ignored instead of triggering a failure.
9873 @end table
9875 @sp 1
9877 Of course, it supports the Autoconf common subset of options:
9879 @table @option
9880 @item --help
9881 @itemx -h
9882 Print a summary of the command line options and exit.
9884 @item --version
9885 @itemx -V
9886 Print the version number of Autoconf and exit.
9888 @item --verbose
9889 @itemx -v
9890 Report processing steps.
9892 @item --debug
9893 @itemx -d
9894 Don't remove the temporary files and be even more verbose.
9896 @item --include=@var{dir}
9897 @itemx -I @var{dir}
9898 Also look for input files in @var{dir}.  Multiple invocations
9899 accumulate.
9901 @item --output=@var{file}
9902 @itemx -o @var{file}
9903 Save output (script or trace) to @var{file}.  The file @option{-} stands
9904 for the standard output.
9905 @end table
9907 @sp 1
9909 As an extension of @command{m4}, it includes the following options:
9911 @table @option
9912 @item --warnings=@var{category}
9913 @itemx -W @var{category}
9914 @evindex WARNINGS
9915 @c FIXME: Point to the M4sugar macros, not Autoconf's.
9916 Report the warnings related to @var{category} (which can actually be a
9917 comma separated list).  @xref{Reporting Messages}, macro
9918 @code{AC_DIAGNOSE}, for a comprehensive list of categories.  Special
9919 values include:
9921 @table @samp
9922 @item all
9923 report all the warnings
9925 @item none
9926 report none
9928 @item error
9929 treats warnings as errors
9931 @item no-@var{category}
9932 disable warnings falling into @var{category}
9933 @end table
9935 Warnings about @samp{syntax} are enabled by default, and the environment
9936 variable @env{WARNINGS}, a comma separated list of categories, is
9937 honored.  @samp{autom4te -W @var{category}} actually
9938 behaves as if you had run:
9940 @example
9941 autom4te --warnings=syntax,$WARNINGS,@var{category}
9942 @end example
9944 @noindent
9945 For example, if you want to disable defaults and @env{WARNINGS}
9946 of @command{autom4te}, but enable the warnings about obsolete
9947 constructs, you would use @option{-W none,obsolete}.
9949 @cindex Back trace
9950 @cindex Macro invocation stack
9951 @command{autom4te} displays a back trace for errors, but not for
9952 warnings; if you want them, just pass @option{-W error}.
9954 @item --melt
9955 @itemx -M
9956 Do not use frozen files.  Any argument @code{@var{file}.m4f} is
9957 replaced by @code{@var{file}.m4}.  This helps tracing the macros which
9958 are executed only when the files are frozen, typically
9959 @code{m4_define}.  For instance, running:
9961 @example
9962 autom4te --melt 1.m4 2.m4f 3.m4 4.m4f input.m4
9963 @end example
9965 @noindent
9966 is roughly equivalent to running:
9968 @example
9969 m4 1.m4 2.m4 3.m4 4.m4 input.m4
9970 @end example
9972 @noindent
9973 while
9975 @example
9976 autom4te 1.m4 2.m4f 3.m4 4.m4f input.m4
9977 @end example
9979 @noindent
9980 is equivalent to:
9982 @example
9983 m4 --reload-state=4.m4f input.m4
9984 @end example
9986 @item --freeze
9987 @itemx -f
9988 Produce a frozen state file.  @command{autom4te} freezing is stricter
9989 than M4's: it must produce no warnings, and no output other than empty
9990 lines (a line with white space is @emph{not} empty) and comments
9991 (starting with @samp{#}).  Unlike @command{m4}'s similarly-named option,
9992 this option takes no argument:
9994 @example
9995 autom4te 1.m4 2.m4 3.m4 --freeze --output=3.m4f
9996 @end example
9998 @noindent
9999 corresponds to
10001 @example
10002 m4 1.m4 2.m4 3.m4 --freeze-state=3.m4f
10003 @end example
10005 @item --mode=@var{octal-mode}
10006 @itemx -m @var{octal-mode}
10007 Set the mode of the non-traces output to @var{octal-mode}; by default
10008 @samp{0666}.
10009 @end table
10011 @sp 1
10013 @cindex @file{autom4te.cache}
10014 As another additional feature over @command{m4}, @command{autom4te}
10015 caches its results.  @acronym{GNU} M4 is able to produce a regular
10016 output and traces at the same time.  Traces are heavily used in the
10017 @acronym{GNU} Build System: @command{autoheader} uses them to build
10018 @file{config.h.in}, @command{autoreconf} to determine what
10019 @acronym{GNU} Build System components are used, @command{automake} to
10020 ``parse'' @file{configure.ac} etc.  To avoid recomputation,
10021 traces are cached while performing regular expansion,
10022 and conversely.  This cache is (actually, the caches are) stored in
10023 the directory @file{autom4te.cache}.  @emph{It can safely be removed}
10024 at any moment (especially if for some reason @command{autom4te}
10025 considers it trashed).
10027 @table @option
10028 @item --cache=@var{directory}
10029 @itemx -C @var{directory}
10030 Specify the name of the directory where the result should be cached.
10031 Passing an empty value disables caching.  Be sure to pass a relative
10032 file name, as for the time being, global caches are not supported.
10034 @item --no-cache
10035 Don't cache the results.
10037 @item --force
10038 @itemx -f
10039 If a cache is used, consider it obsolete (but update it anyway).
10040 @end table
10042 @sp 1
10044 Because traces are so important to the @acronym{GNU} Build System,
10045 @command{autom4te} provides high level tracing features as compared to
10046 M4, and helps exploiting the cache:
10048 @table @option
10049 @item --trace=@var{macro}[:@var{format}]
10050 @itemx -t @var{macro}[:@var{format}]
10051 Trace the invocations of @var{macro} according to the @var{format}.
10052 Multiple @option{--trace} arguments can be used to list several macros.
10053 Multiple @option{--trace} arguments for a single macro are not
10054 cumulative; instead, you should just make @var{format} as long as
10055 needed.
10057 The @var{format} is a regular string, with newlines if desired, and
10058 several special escape codes.  It defaults to @samp{$f:$l:$n:$%}.  It can
10059 use the following special escapes:
10061 @table @samp
10062 @item $$
10063 The character @samp{$}.
10065 @item $f
10066 The file name from which @var{macro} is called.
10068 @item $l
10069 The line number from which @var{macro} is called.
10071 @item $d
10072 The depth of the @var{macro} call.  This is an M4 technical detail that
10073 you probably don't want to know about.
10075 @item $n
10076 The name of the @var{macro}.
10078 @item $@var{num}
10079 The @var{num}th argument of the call to @var{macro}.
10081 @item $@@
10082 @itemx $@var{sep}@@
10083 @itemx $@{@var{separator}@}@@
10084 All the arguments passed to @var{macro}, separated by the character
10085 @var{sep} or the string @var{separator} (@samp{,} by default).  Each
10086 argument is quoted, i.e., enclosed in a pair of square brackets.
10088 @item $*
10089 @itemx $@var{sep}*
10090 @itemx $@{@var{separator}@}*
10091 As above, but the arguments are not quoted.
10093 @item $%
10094 @itemx $@var{sep}%
10095 @itemx $@{@var{separator}@}%
10096 As above, but the arguments are not quoted, all new line characters in
10097 the arguments are smashed, and the default separator is @samp{:}.
10099 The escape @samp{$%} produces single-line trace outputs (unless you put
10100 newlines in the @samp{separator}), while @samp{$@@} and @samp{$*} do
10101 not.
10102 @end table
10104 @xref{autoconf Invocation}, for examples of trace uses.
10106 @item --preselect=@var{macro}
10107 @itemx -p @var{macro}
10108 Cache the traces of @var{macro}, but do not enable traces.  This is
10109 especially important to save CPU cycles in the future.  For instance,
10110 when invoked, @command{autoconf} preselects all the macros that
10111 @command{autoheader}, @command{automake}, @command{autoreconf}, etc.,
10112 trace, so that running @command{m4} is not needed to trace them: the
10113 cache suffices.  This results in a huge speed-up.
10114 @end table
10116 @sp 1
10118 @cindex Autom4te Library
10119 Finally, @command{autom4te} introduces the concept of @dfn{Autom4te
10120 libraries}.  They consists in a powerful yet extremely simple feature:
10121 sets of combined command line arguments:
10123 @table @option
10124 @item --language=@var{language}
10125 @itemx -l @var{language}
10126 Use the @var{language} Autom4te library.  Current languages include:
10128 @table @code
10129 @item M4sugar
10130 create M4sugar output.
10132 @item M4sh
10133 create M4sh executable shell scripts.
10135 @item Autotest
10136 create Autotest executable test suites.
10138 @item Autoconf-without-aclocal-m4
10139 create Autoconf executable configure scripts without
10140 reading @file{aclocal.m4}.
10142 @item Autoconf
10143 create Autoconf executable configure scripts.  This language inherits
10144 all the characteristics of @code{Autoconf-without-aclocal-m4} and
10145 additionally reads @file{aclocal.m4}.
10146 @end table
10148 @item --prepend-include=@var{dir}
10149 @itemx -B @var{dir}
10150 Prepend directory @var{dir} to the search path.  This is used to include
10151 the language-specific files before any third-party macros.
10153 @end table
10155 @cindex @file{autom4te.cfg}
10156 As an example, if Autoconf is installed in its default location,
10157 @file{/usr/local}, the command @samp{autom4te -l m4sugar foo.m4} is
10158 strictly equivalent to the command:
10160 @example
10161 autom4te --prepend-include /usr/local/share/autoconf \
10162   m4sugar/m4sugar.m4f --warnings syntax foo.m4
10163 @end example
10165 @noindent
10166 Recursive expansion applies here: the command @samp{autom4te -l m4sh foo.m4}
10167 is the same as @samp{autom4te --language M4sugar m4sugar/m4sh.m4f
10168 foo.m4}, i.e.:
10170 @example
10171 autom4te --prepend-include /usr/local/share/autoconf \
10172   m4sugar/m4sugar.m4f m4sugar/m4sh.m4f --mode 777 foo.m4
10173 @end example
10175 @noindent
10176 The definition of the languages is stored in @file{autom4te.cfg}.
10178 @node Customizing autom4te
10179 @subsection Customizing @command{autom4te}
10181 One can customize @command{autom4te} via @file{~/.autom4te.cfg} (i.e.,
10182 as found in the user home directory), and @file{./.autom4te.cfg} (i.e.,
10183 as found in the directory from which @command{autom4te} is run).  The
10184 order is first reading @file{autom4te.cfg}, then @file{~/.autom4te.cfg},
10185 then @file{./.autom4te.cfg}, and finally the command line arguments.
10187 In these text files, comments are introduced with @code{#}, and empty
10188 lines are ignored.  Customization is performed on a per-language basis,
10189 wrapped in between a @samp{begin-language: "@var{language}"},
10190 @samp{end-language: "@var{language}"} pair.
10192 Customizing a language stands for appending options (@pxref{autom4te
10193 Invocation}) to the current definition of the language.  Options, and
10194 more generally arguments, are introduced by @samp{args:
10195 @var{arguments}}.  You may use the traditional shell syntax to quote the
10196 @var{arguments}.
10198 As an example, to disable Autoconf caches (@file{autom4te.cache})
10199 globally, include the following lines in @file{~/.autom4te.cfg}:
10201 @verbatim
10202 ## ------------------ ##
10203 ## User Preferences.  ##
10204 ## ------------------ ##
10206 begin-language: "Autoconf-without-aclocal-m4"
10207 args: --no-cache
10208 end-language: "Autoconf-without-aclocal-m4"
10209 @end verbatim
10212 @node Programming in M4sugar
10213 @section Programming in M4sugar
10215 @cindex M4sugar
10216 M4 by itself provides only a small, but sufficient, set of all-purpose
10217 macros.  M4sugar introduces additional generic macros.  Its name was
10218 coined by Lars J. Aas: ``Readability And Greater Understanding Stands 4
10219 M4sugar''.
10221 M4sugar reserves the macro namespace @samp{^_m4_} for internal use, and
10222 the macro namespace @samp{^m4_} for M4sugar macros.  You should not
10223 define your own macros into these namespaces.
10225 @menu
10226 * Redefined M4 Macros::         M4 builtins changed in M4sugar
10227 * Diagnostic Macros::           Diagnostic messages from M4sugar
10228 * Diversion support::           Diversions in M4sugar
10229 * Conditional constructs::      Conditions in M4
10230 * Looping constructs::          Iteration in M4
10231 * Evaluation Macros::           More quotation and evaluation control
10232 * Text processing Macros::      String manipulation in M4
10233 * Number processing Macros::    Arithmetic computation in M4
10234 * Set manipulation Macros::     Set manipulation in M4
10235 * Forbidden Patterns::          Catching unexpanded macros
10236 @end menu
10238 @node Redefined M4 Macros
10239 @subsection Redefined M4 Macros
10241 @msindex{builtin}
10242 @msindex{changecom}
10243 @msindex{changequote}
10244 @msindex{debugfile}
10245 @msindex{debugmode}
10246 @msindex{decr}
10247 @msindex{define}
10248 @msindex{divnum}
10249 @msindex{dumpdef}
10250 @msindex{errprint}
10251 @msindex{esyscmd}
10252 @msindex{eval}
10253 @msindex{format}
10254 @msindex{ifdef}
10255 @msindex{incr}
10256 @msindex{index}
10257 @msindex{indir}
10258 @msindex{len}
10259 @msindex{pushdef}
10260 @msindex{shift}
10261 @msindex{substr}
10262 @msindex{syscmd}
10263 @msindex{sysval}
10264 @msindex{traceoff}
10265 @msindex{traceon}
10266 @msindex{translit}
10267 With a few exceptions, all the M4 native macros are moved in the
10268 @samp{m4_} pseudo-namespace, e.g., M4sugar renames @code{define} as
10269 @code{m4_define} etc.
10271 The list of macros unchanged from M4, except for their name, is:
10272 @itemize @minus
10273 @item m4_builtin
10274 @item m4_changecom
10275 @item m4_changequote
10276 @item m4_debugfile
10277 @item m4_debugmode
10278 @item m4_decr
10279 @item m4_define
10280 @item m4_divnum
10281 @item m4_dumpdef
10282 @item m4_errprint
10283 @item m4_esyscmd
10284 @item m4_eval
10285 @item m4_format
10286 @item m4_ifdef
10287 @item m4_incr
10288 @item m4_index
10289 @item m4_indir
10290 @item m4_len
10291 @item m4_pushdef
10292 @item m4_shift
10293 @item m4_substr
10294 @item m4_syscmd
10295 @item m4_sysval
10296 @item m4_traceoff
10297 @item m4_traceon
10298 @item m4_translit
10299 @end itemize
10301 Some M4 macros are redefined, and are slightly incompatible with their
10302 native equivalent.
10304 @defmac __file__
10305 @defmacx __line__
10306 @MSindex __file__
10307 @MSindex __line__
10308 All M4 macros starting with @samp{__} retain their original name: for
10309 example, no @code{m4__file__} is defined.
10310 @end defmac
10312 @defmac __oline__
10313 @MSindex __oline__
10314 This is not technically a macro, but a feature of Autom4te.  The
10315 sequence @code{__oline__} can be used similarly to the other m4sugar
10316 location macros, but rather than expanding to the location of the input
10317 file, it is translated to the line number where it appears in the output
10318 file after all other M4 expansions.
10319 @end defmac
10321 @defmac dnl
10322 @MSindex dnl
10323 This macro kept its original name: no @code{m4_dnl} is defined.
10324 @end defmac
10326 @defmac m4_bpatsubst (@var{string}, @var{regexp}, @ovar{replacement})
10327 @msindex{bpatsubst}
10328 This macro corresponds to @code{patsubst}.  The name @code{m4_patsubst}
10329 is kept for future versions of M4sugar, once @acronym{GNU} M4 2.0 is
10330 released and supports extended regular expression syntax.
10331 @end defmac
10333 @defmac m4_bregexp (@var{string}, @var{regexp}, @ovar{replacement})
10334 @msindex{bregexp}
10335 This macro corresponds to @code{regexp}.  The name @code{m4_regexp}
10336 is kept for future versions of M4sugar, once @acronym{GNU} M4 2.0 is
10337 released and supports extended regular expression syntax.
10338 @end defmac
10340 @defmac m4_defn (@var{macro}@dots{})
10341 @msindex{defn}
10342 This macro fails if @var{macro} is not defined, even when using older
10343 versions of M4 that did not warn.  See @code{m4_undefine}.
10344 Unfortunately, in order to support these older versions of M4, there are
10345 some situations involving unbalanced quotes where concatenating multiple
10346 macros together will work in newer M4 but not in m4sugar; use
10347 quadrigraphs to work around this.
10348 @end defmac
10350 @defmac m4_divert (@var{diversion})
10351 @msindex{divert}
10352 M4sugar relies heavily on diversions, so rather than behaving as a
10353 primitive, @code{m4_divert} behaves like:
10354 @example
10355 m4_divert_pop()m4_divert_push([@var{diversion}])
10356 @end example
10357 @noindent
10358 @xref{Diversion support}, for more details about the use of the
10359 diversion stack.
10360 @end defmac
10362 @defmac m4_exit (@var{exit-status})
10363 @msindex{exit}
10364 This macro corresponds to @code{m4exit}.
10365 @end defmac
10367 @defmac m4_if (@var{comment})
10368 @defmacx m4_if (@var{string-1}, @var{string-2}, @var{equal}, @ovar{not-equal})
10369 @defmacx m4_if (@var{string-1}, @var{string-2}, @var{equal}, @dots{})
10370 @msindex{if}
10371 This macro corresponds to @code{ifelse}.  @var{string-1} and
10372 @var{string-2} are compared literally, so usually one of the two
10373 arguments is passed unquoted.  @xref{Conditional constructs}, for more
10374 conditional idioms.
10375 @end defmac
10377 @defmac m4_include (@var{file})
10378 @defmacx m4_sinclude (@var{file})
10379 @msindex{include}
10380 @msindex{sinclude}
10381 Like the M4 builtins, but warn against multiple inclusions of @var{file}.
10382 @end defmac
10384 @defmac m4_mkstemp (@var{template})
10385 @defmacx m4_maketemp (@var{template})
10386 @msindex{maketemp}
10387 @msindex{mkstemp}
10388 Posix requires @code{maketemp} to replace the trailing @samp{X}
10389 characters in @var{template} with the process id, without regards to the
10390 existence of a file by that name, but this a security hole.  When this
10391 was pointed out to the Posix folks, they agreed to invent a new macro
10392 @code{mkstemp} that always creates a uniquely named file, but not all
10393 versions of @acronym{GNU} M4 support the new macro.  In M4sugar,
10394 @code{m4_maketemp} and @code{m4_mkstemp} are synonyms for each other,
10395 and both have the secure semantics regardless of which macro the
10396 underlying M4 provides.
10397 @end defmac
10399 @defmac m4_popdef (@var{macro}@dots{})
10400 @msindex{popdef}
10401 This macro fails if @var{macro} is not defined, even when using older
10402 versions of M4 that did not warn.  See @code{m4_undefine}.
10403 @end defmac
10405 @defmac m4_undefine (@var{macro}@dots{})
10406 @msindex{undefine}
10407 This macro fails if @var{macro} is not defined, even when using older
10408 versions of M4 that did not warn.  Use
10410 @example
10411 m4_ifdef([@var{macro}], [m4_undefine([@var{macro}])])
10412 @end example
10414 @noindent
10415 if you are not sure whether @var{macro} is defined.
10416 @end defmac
10418 @defmac m4_undivert (@var{diversion})
10419 @msindex{undivert}
10420 Unlike the M4 builtin, only one diversion can be undiverted per
10421 invocation.  Also, since the M4sugar diversion stack prefers named
10422 diversions, the use of @code{m4_undivert} to include files is risky.
10423 @xref{Diversion support}, for more details about the use of the
10424 diversion stack.
10425 @end defmac
10427 @defmac m4_wrap (@var{text})
10428 @defmacx m4_wrap_lifo (@var{text})
10429 @msindex{wrap}
10430 @msindex{wrap_lifo}
10431 These macros correspond to @code{m4wrap}.  Posix requires arguments of
10432 multiple wrap calls to be reprocessed at @acronym{EOF} in the same order
10433 as the original calls (first-in, first-out).  @acronym{GNU} M4 versions
10434 through 1.4.10, however, reprocess them in reverse order (last-in,
10435 first-out).  Both orders are useful, therefore, you can rely on
10436 @code{m4_wrap} to provide FIFO semantics and @code{m4_wrap_lifo} for
10437 LIFO semantics, regardless of the underlying @acronym{GNU} M4 version.
10439 Unlike the @acronym{GNU} M4 builtin, these macros only recognize one
10440 argument, and avoid token pasting between consecutive invocations.  On
10441 the other hand, nested calls to @code{m4_wrap} from within wrapped text
10442 work just as in the builtin.
10443 @end defmac
10446 @node Diagnostic Macros
10447 @subsection Diagnostic messages from M4sugar
10448 @cindex Messages, from @command{M4sugar}
10450 When macros statically diagnose abnormal situations, benign or fatal,
10451 they should report them using these macros.  For issuing dynamic issues,
10452 i.e., when @command{configure} is run, see @ref{Printing Messages}.
10454 @defmac m4_assert (@var{expression}, @dvar{exit-status, 1})
10455 @msindex{assert}
10456 Assert that the arithmetic @var{expression} evaluates to non-zero.
10457 Otherwise, issue a fatal error, and exit @command{autom4te} with
10458 @var{exit-status}.
10459 @end defmac
10461 @defmac m4_errprintn (@var{message})
10462 @msindex{errprintn}
10463 Similar to the builtin @code{m4_errprint}, except that a newline is
10464 guaranteed after @var{message}.
10465 @end defmac
10467 @anchor{m4_fatal}
10468 @defmac m4_fatal (@var{message})
10469 @msindex{fatal}
10470 Report a severe error @var{message} prefixed with the current location,
10471 and have @command{autom4te} die.
10472 @end defmac
10474 @defmac m4_location
10475 @msindex{location}
10476 Useful as a prefix in a message line.  Short for:
10477 @example
10478 __file__:__line__
10479 @end example
10480 @end defmac
10482 @anchor{m4_warn}
10483 @defmac m4_warn (@var{category}, @var{message})
10484 @msindex{warn}
10485 Report @var{message} as a warning (or as an error if requested by the
10486 user) if warnings of the @var{category} are turned on.  If the message
10487 is emitted, it is prefixed with the current location, and followed by a
10488 call trace of all macros defined via @code{AC_DEFUN} used to get to the
10489 current expansion.  You are encouraged to use standard categories, which
10490 currently include:
10492 @table @samp
10493 @item all
10494 messages that don't fall into one of the following categories.  Use of an
10495 empty @var{category} is equivalent.
10497 @item cross
10498 related to cross compilation issues.
10500 @item obsolete
10501 use of an obsolete construct.
10503 @item syntax
10504 dubious syntactic constructs, incorrectly ordered macro calls.
10505 @end table
10506 @end defmac
10509 @node Diversion support
10510 @subsection Diversion support
10512 M4sugar makes heavy use of diversions, because it is often the case that
10513 text that must appear early in the output is not discovered until late
10514 in the input.  Additionally, some of the topological sorting algorithms
10515 used in resolving macro dependencies use diversions.  Therefore, most
10516 macros should not need to change diversions directly, but rather rely on
10517 higher-level M4sugar macros to manage diversions transparently.
10519 To make diversion management easier, M4sugar uses the concept of named
10520 diversions.  Rather than using diversion numbers directly, it is nicer
10521 to associate a name with each diversion; the diversion number associated
10522 with a particular diversion name is an implementation detail, so you
10523 should only use diversion names.  In general, you should not output text
10524 to a named diversion until after calling the appropriate initialization
10525 routine for your language (@code{m4_init}, @code{AS_INIT},
10526 @code{AT_INIT}, @dots{}), although there are some exceptions documented
10527 below.
10529 M4sugar defines two named diversions.
10530 @table @code
10531 @item KILL
10532 Text written to this diversion is discarded.  This is the default
10533 diversion once M4sugar is initialized.
10534 @item GROW
10535 This diversion is used behind the scenes by topological sorting macros,
10536 such as @code{AC_REQUIRE}.
10537 @end table
10539 M4sh adds several more named diversions.
10540 @table @code
10541 @item BINSH
10542 This diversion is reserved for the @samp{#!} interpreter line.
10543 @item HEADER-REVISION
10544 This diversion holds text from @code{AC_REVISION}.
10545 @item HEADER-COMMENT
10546 This diversion holds comments about the purpose of a file.
10547 @item HEADER-COPYRIGHT
10548 This diversion is managed by @code{AC_COPYRIGHT}.
10549 @item M4SH-SANITIZE
10550 This diversion contains M4sh sanitization code, used to ensure M4sh is
10551 executing in a reasonable shell environment.
10552 @item M4SH-INIT
10553 This diversion contains M4sh initialization code, initializing variables
10554 that are required by other M4sh macros.
10555 @item BODY
10556 This diversion contains the body of the shell code, and is the default
10557 diversion once M4sh is initialized.
10558 @end table
10560 Autotest inherits diversions from M4sh, and changes the default
10561 diversion from @code{BODY} back to @code{KILL}.  It also adds several
10562 more named diversions, with the following subset designed for developer
10563 use.
10564 @table @code
10565 @item PREPARE_TESTS
10566 This diversion contains initialization sequences which are executed
10567 after @file{atconfig} and @file{atlocal}, and after all command line
10568 arguments have been parsed, but prior to running any tests.  It can be
10569 used to set up state that is required across all tests.  This diversion
10570 will work even before @code{AT_INIT}.
10571 @end table
10573 For now, the named diversions of Autoconf and Autoheader, and the
10574 remaining diversions of Autotest, are not documented.  In other words,
10575 intentionally outputting text into an undocumented diversion is subject
10576 to breakage in a future release of Autoconf.
10578 @defmac m4_divert_once (@var{diversion}, @ovar{content})
10579 @msindex{divert_once}
10580 Similar to @code{m4_divert_text}, except that @var{content} is only
10581 output to @var{diversion} if this is the first time that
10582 @code{m4_divert_once} has been called with its particular arguments.
10583 @end defmac
10585 @defmac m4_divert_pop (@ovar{diversion})
10586 @msindex{divert_pop}
10587 If provided, check that the current diversion is indeed @var{diversion}.
10588 Then change to the diversion located earlier on the stack, giving an
10589 error if an attempt is made to pop beyond the initial m4sugar diversion
10590 of @code{KILL}.
10591 @end defmac
10593 @defmac m4_divert_push (@var{diversion})
10594 @msindex{divert_push}
10595 Remember the former diversion on the diversion stack, and output
10596 subsequent text into @var{diversion}.  M4sugar maintains a diversion
10597 stack, and issues an error if there is not a matching pop for every
10598 push.
10599 @end defmac
10601 @defmac m4_divert_text (@var{diversion}, @ovar{content})
10602 @msindex{divert_text}
10603 Output @var{content} and a newline into @var{diversion}, without
10604 affecting the current diversion.  Shorthand for:
10605 @example
10606 m4_divert_push([@var{diversion}])@var{content}
10607 m4_divert_pop([@var{diversion}])dnl
10608 @end example
10609 @end defmac
10611 @defmac m4_init
10612 @msindex{init}
10613 Initialize the M4sugar environment, setting up the default named
10614 diversion to be @code{KILL}.
10615 @end defmac
10617 @node Conditional constructs
10618 @subsection Conditional constructs
10620 The following macros provide additional conditional contructs, as
10621 convenience wrappers around @code{m4_if}.
10623 @defmac m4_bmatch (@var{string}, @var{regex-1}, @var{value-1}, @
10624   @ovar{regex-2}, @ovar{value-2}, @dots{}, @ovar{default})
10625 @msindex{bmatch}
10626 The string @var{string} is repeatedly compared against a series of
10627 @var{regex} arguments; if a match is found, the expansion is the
10628 corresponding @var{value}, otherwise, the macro moves on to the next
10629 @var{regex}.  If no @var{regex} match, then the result is the optional
10630 @var{default}, or nothing.
10631 @end defmac
10633 @defmac m4_bpatsubsts (@var{string}, @var{regex-1}, @var{subst-1}, @
10634   @ovar{regex-2}, @ovar{subst-2}, @dots{})
10635 @msindex{bpatsubsts}
10636 The string @var{string} is altered by @var{regex-1} and @var{subst-1},
10637 as if by:
10638 @example
10639 m4_bpatsubst([[@var{string}]], [@var{regex}], [@var{subst}])
10640 @end example
10642 @noindent
10643 The result of the substitution is then passed through the next set of
10644 @var{regex} and @var{subst}, and so forth.  An empty @var{subst} implies
10645 deletion of any matched portions in the current string.  Note that this
10646 macro over-quotes @var{string}; this behavior is intentional, so that
10647 the result of each step of the recursion remains as a quoted string.
10648 However, it means that anchors (@samp{^} and @samp{$} in the @var{regex}
10649 will line up with the extra quotations, and not the characters of the
10650 original string.  The overquoting is removed after the final
10651 substitution.
10652 @end defmac
10654 @defmac m4_case (@var{string}, @var{value-1}, @var{if-value-1}, @
10655   @ovar{value-2}, @ovar{if-value-2}, @dots{}, @ovar{default})
10656 @msindex{case}
10657 Test @var{string} against multiple @var{value} possibilities, resulting
10658 in the first @var{if-value} for a match, or in the optional
10659 @var{default}.  This is shorthand for:
10660 @example
10661 m4_if([@var{string}], [@var{value-1}], [@var{if-value-1}],
10662       [@var{string}], [@var{value-2}], [@var{if-value-2}], @dots{},
10663       [@var{default}])
10664 @end example
10665 @end defmac
10667 @defmac m4_cond (@var{test-1}, @var{value-1}, @var{if-value-1}, @
10668   @ovar{test-2}, @ovar{value-2}, @ovar{if-value-2}, @dots{}, @ovar{default})
10669 @msindex{cond}
10670 This macro was introduced in Autoconf 2.62.  Similar to @code{m4_if},
10671 except that each @var{test} is expanded only when it is encountered.
10672 This is useful for short-circuiting expensive tests; while @code{m4_if}
10673 requires all its strings to be expanded up front before doing
10674 comparisons, @code{m4_cond} only expands a @var{test} when all earlier
10675 tests have failed.
10677 For an example, these two sequences give the same result, but in the
10678 case where @samp{$1} does not contain a backslash, the @code{m4_cond}
10679 version only expands @code{m4_index} once, instead of five times, for
10680 faster computation if this is a common case for @samp{$1}.  Notice that
10681 every third argument is unquoted for @code{m4_if}, and quoted for
10682 @code{m4_cond}:
10684 @example
10685 m4_if(m4_index([$1], [\]), [-1], [$2],
10686       m4_eval(m4_index([$1], [\\]) >= 0), [1], [$2],
10687       m4_eval(m4_index([$1], [\$]) >= 0), [1], [$2],
10688       m4_eval(m4_index([$1], [\`]) >= 0), [1], [$3],
10689       m4_eval(m4_index([$1], [\"]) >= 0), [1], [$3],
10690       [$2])
10691 m4_cond([m4_index([$1], [\])], [-1], [$2],
10692         [m4_eval(m4_index([$1], [\\]) >= 0)], [1], [$2],
10693         [m4_eval(m4_index([$1], [\$]) >= 0)], [1], [$2],
10694         [m4_eval(m4_index([$1], [\`]) >= 0)], [1], [$3],
10695         [m4_eval(m4_index([$1], [\"]) >= 0)], [1], [$3],
10696         [$2])
10697 @end example
10698 @end defmac
10700 @defmac m4_default (@var{expr-1}, @var{expr-2})
10701 @msindex{default}
10702 If @var{expr-1} is not empty, use it.  Otherwise, expand to
10703 @var{expr-2}.  Useful for providing a fixed default if the expression
10704 that results in @var{expr-1} would otherwise be empty.
10705 @end defmac
10707 @defmac m4_ifndef (@var{macro}, @var{if-not-defined}, @ovar{if-defined})
10708 @msindex{ifndef}
10709 This is shorthand for:
10710 @example
10711 m4_ifdef([@var{macro}], [@var{if-defined}], [@var{if-not-defined}])
10712 @end example
10713 @end defmac
10715 @defmac m4_ifset (@var{macro}, @ovar{if-true}, @ovar{if-false})
10716 @msindex{ifset}
10717 If @var{macro} is undefined, or is defined as the empty string, expand
10718 to @var{if-false}.  Otherwise, expands to @var{if-true}.  Similar to:
10719 @example
10720 m4_ifval(m4_defn([@var{macro}]), [@var{if-true}], [@var{if-false}])
10721 @end example
10722 @noindent
10723 except that it is not an error if @var{macro} is undefined.
10724 @end defmac
10726 @defmac m4_ifval (@var{cond}, @ovar{if-true}, @ovar{if-false})
10727 @msindex{ifval}
10728 Expands to @var{if-true} if @var{cond} is not empty, otherwise to
10729 @var{if-false}.  This is shorthand for:
10730 @example
10731 m4_if([@var{cond}], [], [@var{if-true}], [@var{if-false}])
10732 @end example
10733 @end defmac
10735 @defmac m4_ifvaln (@var{cond}, @ovar{if-true}, @ovar{if-false})
10736 @msindex{ifvaln}
10737 Similar to @code{m4_ifval}, except guarantee that a newline is present
10738 after any non-empty expansion.
10739 @end defmac
10741 @defmac m4_n (@var{text})
10742 @msindex{n}
10743 Expand to @var{text}, and add a newline if @var{text} is not empty.
10744 @end defmac
10747 @node Looping constructs
10748 @subsection Looping constructs
10750 The following macros are useful in implementing recursive algorithms in
10751 M4, including loop operations.  An M4 list is formed by quoting a list
10752 of quoted elements; generally the lists are comma-separated, although
10753 @code{m4_foreach_w} is whitespace-separated.  For example, the list
10754 @samp{[[a], [b,c]]} contains two elements: @samp{[a]} and @samp{[b,c]}.
10755 It is common to see lists with unquoted elements when those elements are
10756 not likely to be macro names, as in @samp{[fputc_unlocked,
10757 fgetc_unlocked]}.
10759 Although not generally recommended, it is possible for quoted lists to
10760 have side effects; all side effects are expanded only once, and prior to
10761 visiting any list element.  On the other hand, the fact that unquoted
10762 macros are expanded exactly once means that macros without side effects
10763 can be used to generate lists.  For example,
10765 @example
10766 m4_foreach([i], [[1], [2], [3]m4_errprintn([hi])], [i])
10767 @error{}hi
10768 @result{}123
10769 m4_define([list], [[1], [2], [3]])
10770 @result{}
10771 m4_foreach([i], [list], [i])
10772 @result{}123
10773 @end example
10775 @defmac m4_car (@var{list})
10776 @msindex{car}
10777 Expands to the quoted first element of the comma-separated quoted
10778 @var{list}.  Often used with @code{m4_cdr} to recursively iterate
10779 through a list.  Generally, when using quoted lists of quoted elements,
10780 @code{m4_car} should be called without any extra quotes.
10781 @end defmac
10783 @defmac m4_cdr (@var{list})
10784 @msindex{cdr}
10785 Expands to a quoted list of all but the first element of the
10786 comma-separated quoted @var{list}, or the empty string if @var{list} had
10787 only one element.  Generally, when using quoted lists of quoted
10788 elements, @code{m4_cdr} should be called without any extra quotes.
10790 For example, this is a simple implementation of @code{m4_map}; note how
10791 each iteration checks for the end of recursion, then merely applies the
10792 first argument to the first element of the list, then repeats with the
10793 rest of the list.  (The actual implementation in M4sugar is a bit more
10794 involved, to gain some speed and share code with @code{m4_map_sep}).
10795 @example
10796 m4_define([m4_map], [m4_ifval([$2],
10797   [m4_apply([$1], m4_car($2))[]$0([$1], m4_cdr($2))])])dnl
10798 m4_map([ m4_eval], [[[1]], [[1+1]], [[10],[16]]])
10799 @result{} 1 2 a
10800 @end example
10801 @end defmac
10803 @defmac m4_for (@var{var}, @var{first}, @var{last}, @ovar{step}, @
10804   @var{expression})
10805 @msindex{for}
10806 Loop over the numeric values between @var{first} and @var{last}
10807 including bounds by increments of @var{step}.  For each iteration,
10808 expand @var{expression} with the numeric value assigned to @var{var}.
10809 If @var{step} is omitted, it defaults to @samp{1} or @samp{-1} depending
10810 on the order of the limits.  If given, @var{step} has to match this
10811 order.  The number of iterations is determined independently from
10812 definition of @var{var}; iteration cannot be short-circuited or
10813 lengthened by modifying @var{var} from within @var{expression}.
10814 @end defmac
10816 @defmac m4_foreach (@var{var}, @var{list}, @var{expression})
10817 @msindex{foreach}
10818 Loop over the comma-separated M4 list @var{list}, assigning each value
10819 to @var{var}, and expand @var{expression}.  The following example
10820 outputs two lines:
10822 @example
10823 m4_foreach([myvar], [[foo], [bar, baz]],
10824            [echo myvar
10825 ])dnl
10826 @result{}echo foo
10827 @result{}echo bar, baz
10828 @end example
10829 @end defmac
10831 @anchor{m4_foreach_w}
10832 @defmac m4_foreach_w (@var{var}, @var{list}, @var{expression})
10833 @msindex{foreach_w}
10834 Loop over the white-space-separated list @var{list}, assigning each value
10835 to @var{var}, and expand @var{expression}.
10837 The deprecated macro @code{AC_FOREACH} is an alias of
10838 @code{m4_foreach_w}.
10839 @end defmac
10841 @defmac m4_map (@var{macro}, @var{list})
10842 @defmacx m4_mapall (@var{macro}, @var{list})
10843 @defmacx m4_map_sep (@var{macro}, @var{separator}, @var{list})
10844 @defmacx m4_mapall_sep (@var{macro}, @var{separator}, @var{list})
10845 @msindex{map}
10846 @msindex{mapall}
10847 @msindex{map_sep}
10848 @msindex{mapall_sep}
10849 Loop over the comma separated quoted list of argument descriptions in
10850 @var{list}, and invoke @var{macro} with the arguments.  An argument
10851 description is in turn a comma-separated quoted list of quoted elements,
10852 suitable for @code{m4_apply}.  The macros @code{m4_map} and
10853 @code{m4_map_sep} ignore empty argument descriptions, while
10854 @code{m4_mapall} and @code{m4_mapall_sep} invoke @var{macro} with no
10855 arguments.  The macros @code{m4_map_sep} and @code{m4_mapall_sep}
10856 additionally expand @var{separator} between invocations of @var{macro}.
10858 Note that @var{separator} is expanded, unlike in @code{m4_join}.  When
10859 separating output with commas, this means that the map result can be
10860 used as a series of arguments, by using a single-quoted comma as
10861 @var{separator}, or as a single string, by using a double-quoted comma.
10863 @example
10864 m4_map([m4_count], [])
10865 @result{}
10866 m4_map([ m4_count], [[],
10867                      [[1]],
10868                      [[1], [2]]])
10869 @result{} 1 2
10870 m4_mapall([ m4_count], [[],
10871                         [[1]],
10872                         [[1], [2]]])
10873 @result{} 0 1 2
10874 m4_map_sep([m4_eval], [,], [[[1+2]],
10875                             [[10], [16]]])
10876 @result{}3,a
10877 m4_map_sep([m4_echo], [,], [[[a]], [[b]]])
10878 @result{}a,b
10879 m4_count(m4_map_sep([m4_echo], [,], [[[a]], [[b]]]))
10880 @result{}2
10881 m4_map_sep([m4_echo], [[,]], [[[a]], [[b]]])
10882 @result{}a,b
10883 m4_count(m4_map_sep([m4_echo], [[,]], [[[a]], [[b]]]))
10884 @result{}1
10885 @end example
10886 @end defmac
10888 @defmac m4_shiftn (@var{count}, @dots{})
10889 @defmacx m4_shift2 (@dots{})
10890 @defmacx m4_shift3 (@dots{})
10891 @msindex{shift2}
10892 @msindex{shift3}
10893 @msindex{shiftn}
10894 @code{m4_shiftn} performs @var{count} iterations of @code{m4_shift},
10895 along with validation that enough arguments were passed in to match the
10896 shift count, and that the count is positive.  @code{m4_shift2} and
10897 @code{m4_shift3} are specializations
10898 of @code{m4_shiftn}, introduced in Autoconf 2.62, and are more efficient
10899 for two and three shifts, respectively.
10900 @end defmac
10903 @node Evaluation Macros
10904 @subsection Evaluation Macros
10906 The following macros give some control over the order of the evaluation
10907 by adding or removing levels of quotes.
10909 @defmac m4_apply (@var{macro}, @var{list})
10910 @msindex{apply}
10911 Apply the elements of the quoted, comma-separated @var{list} as the
10912 arguments to @var{macro}.  If @var{list} is empty, invoke @var{macro}
10913 without arguments.  Note the difference between @code{m4_indir}, which
10914 expects its first argument to be a macro name but can use names that are
10915 otherwise invalid, and @code{m4_apply}, where @var{macro} can contain
10916 other text, but must end in a valid macro name.
10917 @example
10918 m4_apply([m4_count], [])
10919 @result{}0
10920 m4_apply([m4_count], [[]])
10921 @result{}1
10922 m4_apply([m4_count], [[1], [2]])
10923 @result{}2
10924 m4_apply([m4_join], [[|], [1], [2]])
10925 @result{}1|2
10926 @end example
10927 @end defmac
10929 @defmac m4_count (@var{arg}, @dots{})
10930 @msindex{count}
10931 This macro returns the decimal count of the number of arguments it was
10932 passed.
10933 @end defmac
10935 @defmac m4_do (@var{arg}, @dots{})
10936 @msindex{do}
10937 This macro loops over its arguments and expands each @var{arg} in
10938 sequence.  Its main use is for readability; it allows the use of
10939 indentation and fewer @code{dnl} to result in the same expansion.  This
10940 macro guarantees that no expansion will be concatenated with subsequent
10941 text; to achieve full concatenation, use @code{m4_unquote(m4_join([],
10942 @var{arg@dots{}}))}.
10944 @example
10945 m4_define([ab],[1])m4_define([bc],[2])m4_define([abc],[3])dnl
10946 m4_do([a],[b])c
10947 @result{}abc
10948 m4_unquote(m4_join([],[a],[b]))c
10949 @result{}3
10950 m4_define([a],[A])m4_define([b],[B])m4_define([c],[C])dnl
10951 m4_define([AB],[4])m4_define([BC],[5])m4_define([ABC],[6])dnl
10952 m4_do([a],[b])c
10953 @result{}ABC
10954 m4_unquote(m4_join([],[a],[b]))c
10955 @result{}3
10956 @end example
10957 @end defmac
10959 @defmac m4_dquote (@var{arg}, @dots{})
10960 @msindex{dquote}
10961 Return the arguments as a quoted list of quoted arguments.
10962 Conveniently, if there is just one @var{arg}, this effectively adds a
10963 level of quoting.
10964 @end defmac
10966 @defmac m4_dquote_elt (@var{arg}, @dots{})
10967 @msindex{dquote_elt}
10968 Return the arguments as a series of double-quoted arguments.  Whereas
10969 @code{m4_dquote} returns a single argument, @code{m4_dquote_elt} returns
10970 as many arguments as it was passed.
10971 @end defmac
10973 @defmac m4_echo (@var{arg}, @dots{})
10974 @msindex{echo}
10975 Return the arguments, with the same level of quoting.  Other than
10976 discarding whitespace after unquoted commas, this macro is a no-op.
10977 @end defmac
10979 @defmac m4_expand (@var{arg})
10980 @msindex{expand}
10981 Return the expansion of @var{arg} as a quoted string.  Whereas
10982 @code{m4_quote} is designed to collect expanded text into a single
10983 argument, @code{m4_expand} is designed to perform one level of expansion
10984 on quoted text.  The distinction is in the treatment of whitespace
10985 following a comma in the original @var{arg}.  Any time multiple
10986 arguments are collected into one with @code{m4_quote}, the M4 argument
10987 collection rules discard the whitespace.  However, with @code{m4_expand},
10988 whitespace is preserved, even after the expansion of macros contained in
10989 @var{arg}.
10991 @example
10992 m4_define([active], [ACT, IVE])dnl
10993 m4_define([active2], [[ACT, IVE]])dnl
10994 m4_quote(active, active)
10995 @result{}ACT,IVE,ACT,IVE
10996 m4_expand([active, active])
10997 @result{}ACT, IVE, ACT, IVE
10998 m4_quote(active2, active2)
10999 @result{}ACT, IVE,ACT, IVE
11000 m4_expand([active2, active2])
11001 @result{}ACT, IVE, ACT, IVE
11002 @end example
11004 Note that @code{m4_expand} cannot handle an @var{arg} that expands to
11005 literal unbalanced quotes, but that quadrigraphs can be used when
11006 unbalanced output is necessary.  Likewise, unbalanced parentheses must
11007 be supplied with double quoting or a quadrigraph.
11009 @example
11010 m4_define([pattern], [[!@@<:@@]])dnl
11011 m4_define([bar], [BAR])dnl
11012 m4_expand([case $foo in
11013   m4_defn([pattern])@@:@}@@ bar ;;
11014   *[)] blah ;;
11015 esac])
11016 @result{}case $foo in
11017 @result{}  [![]) BAR ;;
11018 @result{}  *) blah ;;
11019 @result{}esac
11020 @end example
11021 @end defmac
11023 @defmac m4_ignore (@dots{})
11024 @msindex{ignore}
11025 This macro was introduced in Autoconf 2.62.  Expands to nothing,
11026 ignoring all of its arguments.  By itself, this isn't very useful.
11027 However, it can be used to conditionally ignore an arbitrary number of
11028 arguments, by deciding which macro name to apply to a list of arguments.
11029 @example
11030 dnl foo outputs a message only if [debug] is defined.
11031 m4_define([foo],
11032 [m4_ifdef([debug],[AC_MSG_NOTICE],[m4_ignore])([debug message])])
11033 @end example
11035 Note that for earlier versions of Autoconf, the macro @code{__gnu__} can
11036 serve the same purpose, although it is less readable.
11037 @end defmac
11039 @defmac m4_make_list (@var{arg}, @dots{})
11040 @msindex{make_list}
11041 This macro exists to aid debugging of M4sugar algorithms.  Its net
11042 effect is similar to @code{m4_dquote}---it produces a quoted list of
11043 quoted arguments, for each @var{arg}.  The difference is that this
11044 version uses a comma-newline separator instead of just comma, to improve
11045 readability of the list; with the result that it is less efficient than
11046 @code{m4_dquote}.
11047 @example
11048 m4_define([zero],[0])m4_define([one],[1])m4_define([two],[2])dnl
11049 m4_dquote(zero, [one], [[two]])
11050 @result{}[0],[one],[[two]]
11051 m4_make_list(zero, [one], [[two]])
11052 @result{}[0],
11053 @result{}[one],
11054 @result{}[[two]]
11055 m4_foreach([number], m4_dquote(zero, [one], [[two]]), [ number])
11056 @result{} 0 1 two
11057 m4_foreach([number], m4_make_list(zero, [one], [[two]]), [ number])
11058 @result{} 0 1 two
11059 @end example
11060 @end defmac
11062 @c m4_noquote is too dangerous to document - it invokes macros that
11063 @c probably rely on @samp{[]} nested quoting for proper operation.  The
11064 @c user should generally prefer m4_unquote instead.
11066 @defmac m4_quote (@var{arg}, @dots{})
11067 @msindex{quote}
11068 Return the arguments as a single entity, i.e., wrap them into a pair of
11069 quotes.  This effectively collapses multiple arguments into one,
11070 although it loses whitespace after unquoted commas in the process.
11071 @end defmac
11073 @defmac m4_reverse (@var{arg}, @dots{})
11074 @msindex{reverse}
11075 Outputs each argument with the same level of quoting, but in reverse
11076 order, and with space following each comma for readability.
11078 @example
11079 m4_define([active], [ACT,IVE])
11080 @result{}
11081 m4_reverse(active, [active])
11082 @result{}active, IVE, ACT
11083 @end example
11084 @end defmac
11086 @defmac m4_unquote (@var{arg}, @dots{})
11087 @msindex{unquote}
11088 This macro was introduced in Autoconf 2.62.  Expand each argument,
11089 separated by commas.  For a single @var{arg}, this effectively removes a
11090 layer of quoting, and @code{m4_unquote([@var{arg}])} is more efficient
11091 than the equivalent @code{m4_do([@var{arg}])}.  For multiple arguments,
11092 this results in an unquoted list of expansions.  This is commonly used
11093 with @code{m4_split}, in order to convert a single quoted list into a
11094 series of quoted elements.
11095 @end defmac
11097 The following example aims at emphasizing the difference between several
11098 scenarios: not using these macros, using @code{m4_defn}, using
11099 @code{m4_quote}, using @code{m4_dquote}, and using @code{m4_expand}.
11101 @example
11102 $ @kbd{cat example.m4}
11103 dnl Overquote, so that quotes are visible.
11104 m4_define([show], [$[]1 = [$1], $[]@@ = [$@@]])
11105 m4_define([a], [A])
11106 m4_define([mkargs], [1, 2[,] 3])
11107 m4_define([arg1], [[$1]])
11108 m4_divert([0])dnl
11109 show(a, b)
11110 show([a, b])
11111 show(m4_quote(a, b))
11112 show(m4_dquote(a, b))
11113 show(m4_expand([a, b]))
11115 arg1(mkargs)
11116 arg1([mkargs])
11117 arg1(m4_defn([mkargs]))
11118 arg1(m4_quote(mkargs))
11119 arg1(m4_dquote(mkargs))
11120 arg1(m4_expand([mkargs]))
11121 $ @kbd{autom4te -l m4sugar example.m4}
11122 $1 = A, $@@ = [A],[b]
11123 $1 = a, b, $@@ = [a, b]
11124 $1 = A,b, $@@ = [A,b]
11125 $1 = [A],[b], $@@ = [[A],[b]]
11126 $1 = A, b, $@@ = [A, b]
11129 mkargs
11130 1, 2[,] 3
11131 1,2, 3
11132 [1],[2, 3]
11133 1, 2, 3
11134 @end example
11137 @node Text processing Macros
11138 @subsection String manipulation in M4
11140 The following macros may be used to manipulate strings in M4.  Many of
11141 the macros in this section intentionally result in quoted strings as
11142 output, rather than subjecting the arguments to further expansions.  As
11143 a result, if you are manipulating text that contains active M4
11144 characters, the arguments are passed with single quoting rather than
11145 double.
11147 @defmac m4_append (@var{macro-name}, @var{string}, @ovar{separator})
11148 @defmacx m4_append_uniq (@var{macro-name}, @var{string}, @ovar{separator} @
11149   @ovar{if-uniq}, @ovar{if-duplicate})
11150 @msindex{append}
11151 @msindex{append_uniq}
11152 Redefine @var{macro-name} to its former contents with @var{separator}
11153 and @var{string} added at the end.  If @var{macro-name} was undefined
11154 before (but not if it was defined but empty), then no @var{separator} is
11155 added.  As of Autoconf 2.62, neither @var{string} nor @var{separator}
11156 are expanded during this macro; instead, they are expanded when
11157 @var{macro-name} is invoked.
11159 @code{m4_append} can be used to grow strings, and @code{m4_append_uniq}
11160 to grow strings without duplicating substrings.  Additionally,
11161 @code{m4_append_uniq} takes two optional parameters as of Autoconf 2.62;
11162 @var{if-uniq} is expanded if @var{string} was appended, and
11163 @var{if-duplicate} is expanded if @var{string} was already present.
11164 Also, @code{m4_append_uniq} warns if @var{separator} is not empty, but
11165 occurs within @var{string}, since that can lead to duplicates.
11167 Note that @code{m4_append} can scale linearly in the length of the final
11168 string, depending on the quality of the underlying M4 implementation,
11169 while @code{m4_append_uniq} has an inherent quadratic scaling factor.
11170 If an algorithm can tolerate duplicates in the final string, use the
11171 former for speed.  If duplicates must be avoided, consider using
11172 @code{m4_set_add} instead (@pxref{Set manipulation Macros}).
11174 @example
11175 m4_define([active], [ACTIVE])dnl
11176 m4_append([sentence], [This is an])dnl
11177 m4_append([sentence], [ active ])dnl
11178 m4_append([sentence], [symbol.])dnl
11179 sentence
11180 @result{}This is an ACTIVE symbol.
11181 m4_undefine([active])dnl
11182 @result{}This is an active symbol.
11183 m4_append_uniq([list], [one], [, ], [new], [existing])
11184 @result{}new
11185 m4_append_uniq([list], [one], [, ], [new], [existing])
11186 @result{}existing
11187 m4_append_uniq([list], [two], [, ], [new], [existing])
11188 @result{}new
11189 m4_append_uniq([list], [three], [, ], [new], [existing])
11190 @result{}new
11191 m4_append_uniq([list], [two], [, ], [new], [existing])
11192 @result{}existing
11193 list
11194 @result{}one, two, three
11195 m4_dquote(list)
11196 @result{}[one],[two],[three]
11197 m4_append([list2], [one], [[, ]])dnl
11198 m4_append_uniq([list2], [two], [[, ]])dnl
11199 m4_append([list2], [three], [[, ]])dnl
11200 list2
11201 @result{}one, two, three
11202 m4_dquote(list2)
11203 @result{}[one, two, three]
11204 @end example
11205 @end defmac
11207 @defmac m4_append_uniq_w (@var{macro-name}, @var{strings})
11208 @msindex{append_uniq_w}
11209 This macro was introduced in Autoconf 2.62.  It is similar to
11210 @code{m4_append_uniq}, but treats @var{strings} as a whitespace
11211 separated list of words to append, and only appends unique words.
11212 @var{macro-name} is updated with a single space between new words.
11213 @example
11214 m4_append_uniq_w([numbers], [1 1 2])dnl
11215 m4_append_uniq_w([numbers], [ 2 3 ])dnl
11216 numbers
11217 @result{}1 2 3
11218 @end example
11219 @end defmac
11221 @defmac m4_combine (@ovar{separator}, @var{prefix-list}, @ovar{infix}, @
11222   @var{suffix-1}, @ovar{suffix-2}, @dots{})
11223 @msindex{combine}
11224 This macro produces a quoted string containing the pairwise combination
11225 of every element of the quoted, comma-separated @var{prefix-list}, and
11226 every element from the @var{suffix} arguments.  Each pairwise
11227 combination is joined with @var{infix} in the middle, and successive
11228 pairs are joined by @var{separator}.  No expansion occurs on any of the
11229 arguments.  No output occurs if either the @var{prefix} or @var{suffix}
11230 list is empty, but the lists can contain empty elements.
11231 @example
11232 m4_define([a], [oops])dnl
11233 m4_combine([, ], [[a], [b], [c]], [-], [1], [2], [3])
11234 @result{}a-1, a-2, a-3, b-1, b-2, b-3, c-1, c-2, c-3
11235 m4_combine([, ], [[a], [b]], [-])
11236 @result{}
11237 m4_combine([, ], [[a], [b]], [-], [])
11238 @result{}a-, b-
11239 m4_combine([, ], [], [-], [1], [2])
11240 @result{}
11241 m4_combine([, ], [[]], [-], [1], [2])
11242 @result{}-1, -2
11243 @end example
11244 @end defmac
11246 @defmac m4_flatten (@var{string})
11247 @msindex{flatten}
11248 Flatten @var{string} into a single line.  Delete all backslash-newline
11249 pairs, and replace all remaining newlines with a space.  The result is
11250 still a quoted string.
11251 @end defmac
11253 @defmac m4_join (@ovar{separator}, @var{args}@dots{})
11254 @defmacx m4_joinall (@ovar{separator}, @var{args}@dots{})
11255 @msindex{join}
11256 @msindex{joinall}
11257 Concatenate each @var{arg}, separated by @var{separator}.
11258 @code{joinall} uses every argument, while @code{join} omits empty
11259 arguments so that there are no back-to-back separators in the output.
11260 The result is a quoted string.
11261 @example
11262 m4_define([active], [ACTIVE])dnl
11263 m4_join([|], [one], [], [active], [two])
11264 @result{}one|active|two
11265 m4_joinall([|], [one], [], [active], [two])
11266 @result{}one||active|two
11267 @end example
11269 Note that if all you intend to do is join @var{args} with commas between
11270 them, to form a quoted list suitable for @code{m4_foreach}, it is more
11271 efficient to use @code{m4_dquote}.
11272 @end defmac
11274 @defmac m4_newline
11275 @msindex{newline}
11276 This macro was introduced in Autoconf 2.62, and expands to a newline.
11277 It is primarily useful for maintaining macro formatting, and ensuring
11278 that M4 does not discard leading whitespace during argument collection.
11279 @end defmac
11281 @defmac m4_normalize (@var{string})
11282 @msindex{normalize}
11283 Remove leading and trailing spaces and tabs, sequences of
11284 backslash-then-newline, and replace multiple spaces, tabs, and newlines
11285 with a single space.  This is a combination of @code{m4_flatten} and
11286 @code{m4_strip}.
11287 @end defmac
11289 @defmac m4_re_escape (@var{string})
11290 @msindex{re_escape}
11291 Backslash-escape all characters in @var{string} that are active in
11292 regexps.
11293 @end defmac
11295 @defmac m4_split (@var{string}, @dvar{regexp, [\t ]+})
11296 @msindex{split}
11297 Split @var{string} into an M4 list of elements quoted by @samp{[} and
11298 @samp{]}, while keeping white space at the beginning and at the end.
11299 If @var{regexp} is given, use it instead of @samp{[\t ]+} for splitting.
11300 If @var{string} is empty, the result is an empty list.
11301 @end defmac
11303 @defmac m4_strip (@var{string})
11304 @msindex{strip}
11305 Strip whitespace from @var{string}.  Sequences of spaces and tabs are
11306 reduced to a single space, then leading and trailing spaces are removed.
11307 The result is still a quoted string.  Note that this does not interfere
11308 with newlines; if you want newlines stripped as well, consider
11309 @code{m4_flatten}, or do it all at once with @code{m4_normalize}.
11310 @end defmac
11312 @defmac m4_text_box (@var{message}, @dvar{frame, -})
11313 @msindex{text_box}
11314 Add a text box around @var{message}, using @var{frame} as the border
11315 character above and below the message.  The frame correctly accounts for
11316 the subsequent expansion of @var{message}.  For example:
11317 @example
11318 m4_define([macro], [abc])dnl
11319 m4_text_box([macro])
11320 @result{}## --- ##
11321 @result{}## abc ##
11322 @result{}## --- ##
11323 @end example
11325 The @var{message} must contain balanced quotes and parentheses, although
11326 quadrigraphs can be used to work around this.
11327 @end defmac
11329 @defmac m4_text_wrap (@var{string}, @ovar{prefix}, @
11330   @dvar{prefix1, @var{prefix}}, @dvar{width, 79})
11331 @msindex{text_wrap}
11332 Break @var{string} into a series of whitespace-separated words, then
11333 output those words separated by spaces, and wrapping lines any time the
11334 output would exceed @var{width} columns.  If given, @var{prefix1} begins
11335 the first line, and @var{prefix} begins all wrapped lines.  If
11336 @var{prefix1} is longer than @var{prefix}, then the first line consists
11337 of just @var{prefix1}.  If @var{prefix} is longer than @var{prefix1},
11338 padding is inserted so that the first word of @var{string} begins at the
11339 same indentation as all wrapped lines.  Note that using literal tab
11340 characters in any of the arguments will interfere with the calculation
11341 of width.  No expansions occur on @var{prefix}, @var{prefix1}, or the
11342 words of @var{string}, although quadrigraphs are recognized.
11344 For some examples:
11345 @example
11346 m4_text_wrap([Short string */], [   ], [/* ], [20])
11347 @result{}/* Short string */
11348 m4_text_wrap([Much longer string */], [   ], [/* ], [20])
11349 @result{}/* Much longer
11350 @result{}   string */
11351 m4_text_wrap([Short doc.], [          ], [  --short ], [30])
11352 @result{}  --short Short doc.
11353 m4_text_wrap([Short doc.], [          ], [  --too-wide ], [30])
11354 @result{}  --too-wide
11355 @result{}          Short doc.
11356 m4_text_wrap([Super long documentation.], [     ],
11357              [  --too-wide ], 30)
11358 @result{}  --too-wide
11359 @result{}     Super long
11360 @result{}     documentation.
11361 @end example
11362 @end defmac
11364 @defmac m4_tolower (@var{string})
11365 @defmacx m4_toupper (@var{string})
11366 @msindex{tolower}
11367 @msindex{toupper}
11368 Return @var{string} with letters converted to upper or lower case,
11369 respectively.
11370 @end defmac
11372 @node Number processing Macros
11373 @subsection Arithmetic computation in M4
11375 The following macros facilitate integer arithmetic operations.
11376 Where a parameter is documented as taking an arithmetic expression, you
11377 can use anything that can be parsed by @code{m4_eval}.
11379 @defmac m4_cmp (@var{expr-1}, @var{expr-2})
11380 @msindex{cmp}
11381 Compare the arithmetic expressions @var{expr-1} and @var{expr-2}, and
11382 expand to @samp{-1} if @var{expr-1} is smaller, @samp{0} if they are
11383 equal, and @samp{1} if @var{expr-1} is larger.
11384 @end defmac
11386 @defmac m4_list_cmp (@var{list-1}, @var{list-2})
11387 @msindex{list_cmp}
11388 Compare the two M4 lists consisting of comma-separated arithmetic
11389 expressions, left to right.  Expand to @samp{-1} for the first element
11390 pairing where the value from @var{list-1} is smaller, @samp{1} where the
11391 value from @var{list-2} is smaller, or @samp{0} if both lists have the
11392 same values.  If one list is shorter than the other, the remaining
11393 elements of the longer list are compared against zero.
11394 @example
11395 m4_list_cmp([1, 0],       [1])
11396 @result{}0
11397 m4_list_cmp([1, [1 * 0]], [1, 0])
11398 @result{}0
11399 m4_list_cmp([1, 2],       [1, 0])
11400 @result{}1
11401 m4_list_cmp([1, [1+1], 3],[1, 2])
11402 @result{}1
11403 m4_list_cmp([1, 2, -3],   [1, 2])
11404 @result{}-1
11405 m4_list_cmp([1, 0],       [1, 2])
11406 @result{}-1
11407 m4_list_cmp([1],          [1, 2])
11408 @result{}-1
11409 @end example
11410 @end defmac
11412 @defmac m4_max (@var{arg}, @dots{})
11413 @msindex{max}
11414 This macro was introduced in Autoconf 2.62.  Expand to the decimal value
11415 of the maximum arithmetic expression among all the arguments.
11416 @end defmac
11418 @defmac m4_min (@var{arg}, @dots{})
11419 @msindex{min}
11420 This macro was introduced in Autoconf 2.62.  Expand to the decimal value
11421 of the minimum arithmetic expression among all the arguments.
11422 @end defmac
11424 @defmac m4_sign (@var{expr})
11425 @msindex{sign}
11426 Expand to @samp{-1} if the arithmetic expression @var{expr} is negative,
11427 @samp{1} if it is positive, and @samp{0} if it is zero.
11428 @end defmac
11430 @anchor{m4_version_compare}
11431 @defmac m4_version_compare (@var{version-1}, @var{version-2})
11432 @msindex{version_compare}
11433 This macro was introduced in Autoconf 2.53, but had a number of
11434 usability limitations that were not lifted until Autoconf 2.62.  Compare
11435 the version strings @var{version-1} and @var{version-2}, and expand to
11436 @samp{-1} if @var{version-1} is smaller, @samp{0} if they are the same,
11437 or @samp{1} @var{version-2} is smaller.  Version strings must be a list
11438 of elements separated by @samp{.}, @samp{,} or @samp{-}, where each
11439 element is a number along with optional case-insensitive letters
11440 designating beta releases.  The comparison stops at the leftmost element
11441 that contains a difference, although a 0 element compares equal to a
11442 missing element.
11444 It is permissible to include commit identifiers in @var{version}, such
11445 as an abbreviated SHA1 of the commit, provided there is still a
11446 monotonically increasing prefix to allow for accurate version-based
11447 comparisons.  For example, this paragraph was written when the
11448 development snapshot of autoconf claimed to be at version
11449 @samp{2.61a-248-dc51}, or 248 commits after the 2.61a release, with an
11450 abbreviated commit identification of @samp{dc51}.
11452 @example
11453 m4_version_compare([1.1], [2.0])
11454 @result{}-1
11455 m4_version_compare([2.0b], [2.0a])
11456 @result{}1
11457 m4_version_compare([1.1.1], [1.1.1a])
11458 @result{}-1
11459 m4_version_compare([1.2], [1.1.1a])
11460 @result{}1
11461 m4_version_compare([1.0], [1])
11462 @result{}0
11463 m4_version_compare([1.1pre], [1.1PRE])
11464 @result{}0
11465 m4_version_compare([1.1a], [1,10])
11466 @result{}-1
11467 m4_version_compare([2.61a], [2.61a-248-dc51])
11468 @result{}-1
11469 m4_version_compare([2.61b], [2.61a-248-dc51])
11470 @result{}1
11471 @end example
11472 @end defmac
11475 @node Set manipulation Macros
11476 @subsection Set manipulation in M4
11477 @cindex Set manipulation
11478 @cindex Data structure, set
11479 @cindex Unordered set manipulation
11481 Sometimes, it is necessary to track a set of data, where the order does
11482 not matter and where there are no duplicates in the set.  The following
11483 macros facilitate set manipulations.  Each set is an opaque object,
11484 which can only be accessed via these basic operations.  The underlying
11485 implementation guarantees linear scaling for set creation, which is more
11486 efficient than using the quadratic @code{m4_append_uniq}.  Both set
11487 names and values can be arbitrary strings, except for unbalanced quotes.
11488 This implementation ties up memory for removed elements until the next
11489 operation that must traverse all the elements of a set; and although
11490 that may slow down some operations until the memory for removed elements
11491 is pruned, it still guarantees linear performance.
11493 @defmac m4_set_add (@var{set}, @var{value}, @ovar{if-uniq}, @ovar{if-dup})
11494 @msindex{set_add}
11495 Adds the string @var{value} as a member of set @var{set}.  Expand
11496 @var{if-uniq} if the element was added, or @var{if-dup} if it was
11497 previously in the set.  Operates in amortized constant time, so that set
11498 creation scales linearly.
11499 @end defmac
11501 @defmac m4_set_add_all (@var{set}, @var{value}@dots{})
11502 @msindex{set_add_all}
11503 Adds each @var{value} to the set @var{set}.  This is slightly more
11504 efficient than repeatedly invoking @code{m4_set_add}.
11505 @end defmac
11507 @defmac m4_set_contains (@var{set}, @var{value}, @ovar{if-present}, @
11508  @ovar{if-absent})
11509 @msindex{set_contains}
11510 Expands @var{if-present} if the string @var{value} is a member of
11511 @var{set}, otherwise @var{if-absent}.
11513 @example
11514 m4_set_contains([a], [1], [yes], [no])
11515 @result{}no
11516 m4_set_add([a], [1], [added], [dup])
11517 @result{}added
11518 m4_set_add([a], [1], [added], [dup])
11519 @result{}dup
11520 m4_set_contains([a], [1], [yes], [no])
11521 @result{}yes
11522 m4_set_remove([a], [1], [removed], [missing])
11523 @result{}removed
11524 m4_set_contains([a], [1], [yes], [no])
11525 @result{}no
11526 m4_set_remove([a], [1], [removed], [missing])
11527 @result{}missing
11528 @end example
11529 @end defmac
11531 @defmac m4_set_contents (@var{set}, @ovar{sep})
11532 @defmacx m4_set_dump (@var{set}, @ovar{sep})
11533 @msindex{set_contents}
11534 @msindex{set_dump}
11535 Expands to a single string consisting of all the members of the set
11536 @var{set}, each separated by @var{sep}, which is not expanded.
11537 @code{m4_set_contents} leaves the elements in @var{set} but reclaims any
11538 memory occupied by removed elements, while @code{m4_set_dump} is a
11539 faster one-shot action that also deletes the set.  No provision is made
11540 for disambiguating members that contain a non-empty @var{sep} as a
11541 substring; use @code{m4_set_empty} to distinguish between an empty set
11542 and the set containing only the empty string.  The order of the output
11543 is unspecified; in the current implementation, part of the speed of
11544 @code{m4_set_dump} results from using a different output order than
11545 @code{m4_set_contents}.  These macros scale linearly in the size of the
11546 set before memory pruning, and @code{m4_set_contents([@var{set}],
11547 [@var{sep}])} is faster than
11548 @code{m4_joinall([@var{sep}]m4_set_listc([@var{set}]))}.
11550 @example
11551 m4_set_add_all([a], [1], [2], [3])
11552 @result{}
11553 m4_set_contents([a], [-])
11554 @result{}1-2-3
11555 m4_joinall([-]m4_set_listc([a]))
11556 @result{}1-2-3
11557 m4_set_dump([a], [-])
11558 @result{}3-2-1
11559 m4_set_contents([a])
11560 @result{}
11561 m4_set_add([a], [])
11562 @result{}
11563 m4_set_contents([a], [-])
11564 @result{}
11565 @end example
11566 @end defmac
11568 @defmac m4_set_delete (@var{set})
11569 @msindex{set_delete}
11570 Delete all elements and memory associated with @var{set}.  This is
11571 linear in the set size, and faster than removing one element at a time.
11572 @end defmac
11574 @defmac m4_set_difference (@var{seta}, @var{setb})
11575 @defmacx m4_set_intersection (@var{seta}, @var{setb})
11576 @defmacx m4_set_union (@var{seta}, @var{setb})
11577 @msindex{set_difference}
11578 @msindex{set_intersection}
11579 @msindex{set_union}
11580 Compute the relation between @var{seta} and @var{setb}, and output the
11581 result as a list of quoted arguments without duplicates and with a
11582 leading comma.  Set difference selects the elements in @var{seta} but
11583 not @var{setb}, intersection selects only elements in both sets, and
11584 union selects elements in either set.  These actions are linear in the
11585 sum of the set sizes.  The leading comma is necessary to distinguish
11586 between no elements and the empty string as the only element.
11588 @example
11589 m4_set_add_all([a], [1], [2], [3])
11590 @result{}
11591 m4_set_add_all([b], [3], [], [4])
11592 @result{}
11593 m4_set_difference([a], [b])
11594 @result{},1,2
11595 m4_set_difference([b], [a])
11596 @result{},,4
11597 m4_set_intersection([a], [b])
11598 @result{},3
11599 m4_set_union([a], [b])
11600 @result{},1,2,3,,4
11601 @end example
11602 @end defmac
11604 @defmac m4_set_empty (@var{set}, @ovar{if-empty}, @ovar{if-elements})
11605 @msindex{set_empty}
11606 Expand @var{if-empty} if the set @var{set} has no elements, otherwise
11607 expand @var{if-elements}.  This macro operates in constant time.  Using
11608 this macro can help disambiguate output from @code{m4_set_contents} or
11609 @code{m4_set_list}.
11610 @end defmac
11612 @defmac m4_set_foreach (@var{set}, @var{variable}, @var{action})
11613 @msindex{set_foreach}
11614 For each element in the set @var{set}, expand @var{action} with the
11615 macro @var{variable} defined as the set element.  Behavior is
11616 unspecified if @var{action} recursively lists the contents of @var{set}
11617 (although listing other sets is acceptable), or if it modifies the set
11618 in any way other than removing the element currently contained in
11619 @var{variable}.  This macro is faster than the corresponding
11620 @code{m4_foreach([@var{variable}],
11621 m4_indir([m4_dquote]m4_set_listc([@var{set}])), [@var{action}])}.
11623 @example
11624 m4_set_add_all([a]m4_for([i], [1], [5], [], [,i]))
11625 @result{}
11626 m4_set_contents([a])
11627 @result{}12345
11628 m4_set_foreach([a], [i],
11629   [m4_if(m4_eval(i&1), [0], [m4_set_remove([a], i, [i])])])
11630 @result{}24
11631 m4_set_contents([a])
11632 @result{}135
11633 @end example
11634 @end defmac
11636 @defmac m4_set_list (@var{set})
11637 @defmacx m4_set_listc (@var{set})
11638 @msindex{set_list}
11639 @msindex{set_listc}
11640 Produce a list of arguments, where each argument is a quoted element
11641 from the set @var{set}.  The variant @code{m4_set_listc} is unambiguous,
11642 by adding a leading comma if there are any set elements, whereas the
11643 variant @code{m4_set_list} cannot distinguish between an empty set and a
11644 set containing only the empty string.  These can be directly used in
11645 macros that take multiple arguments, such as @code{m4_join} or
11646 @code{m4_set_add_all}, or wrapped by @code{m4_dquote} for macros that
11647 take a quoted list, such as @code{m4_map} or @code{m4_foreach}.  Any
11648 memory occupied by removed elements is reclaimed during these macros.
11650 @example
11651 m4_set_add_all([a], [1], [2], [3])
11652 @result{}
11653 m4_set_list([a])
11654 @result{}1,2,3
11655 m4_set_list([b])
11656 @result{}
11657 m4_set_listc([b])
11658 @result{}
11659 m4_count(m4_set_list([b]))
11660 @result{}1
11661 m4_set_empty([b], [0], [m4_count(m4_set_list([b]))])
11662 @result{}0
11663 m4_set_add([b], [])
11664 @result{}
11665 m4_set_list([b])
11666 @result{}
11667 m4_set_listc([b])
11668 @result{},
11669 m4_count(m4_set_list([b]))
11670 @result{}1
11671 m4_set_empty([b], [0], [m4_count(m4_set_list([b]))])
11672 @result{}1
11673 @end example
11674 @end defmac
11676 @defmac m4_set_remove (@var{set}, @var{value}, @ovar{if-present}, @
11677  @ovar{if-absent})
11678 @msindex{set_remove}
11679 If @var{value} is an element in the set @var{set}, then remove it and
11680 expand @var{if-present}.  Otherwise expand @var{if-absent}.  This macro
11681 operates in constant time so that multiple removals will scale linearly
11682 rather than quadratically; but when used outside of
11683 @code{m4_set_foreach}, it leaves memory occupied until the set is later
11684 compacted by @code{m4_set_contents} or @code{m4_set_list}.  Several
11685 other set operations are then less efficient between the time of element
11686 removal and subsequent memory compaction, but still maintain their
11687 guaranteed scaling performance.
11688 @end defmac
11690 @defmac m4_set_size (@var{set})
11691 @msindex{set_size}
11692 Expand to the size of the set @var{set}.  This implementation operates
11693 in constant time, and is thus more efficient than
11694 @code{m4_eval(m4_count(m4_set_listc([set])) - 1)}.
11695 @end defmac
11698 @node Forbidden Patterns
11699 @subsection Forbidden Patterns
11700 @cindex Forbidden patterns
11701 @cindex Patterns, forbidden
11703 M4sugar provides a means to define suspicious patterns, patterns
11704 describing tokens which should not be found in the output.  For
11705 instance, if an Autoconf @file{configure} script includes tokens such as
11706 @samp{AC_DEFINE}, or @samp{dnl}, then most probably something went
11707 wrong (typically a macro was not evaluated because of overquotation).
11709 M4sugar forbids all the tokens matching @samp{^_?m4_} and @samp{^dnl$}.
11710 Additional layers, such as M4sh and Autoconf, add additional forbidden
11711 patterns to the list.
11713 @defmac m4_pattern_forbid (@var{pattern})
11714 @msindex{pattern_forbid}
11715 Declare that no token matching @var{pattern} must be found in the output.
11716 Comments are not checked; this can be a problem if, for instance, you
11717 have some macro left unexpanded after an @samp{#include}.  No consensus
11718 is currently found in the Autoconf community, as some people consider it
11719 should be valid to name macros in comments (which doesn't make sense to
11720 the authors of this documentation: input, such as macros, should be
11721 documented by @samp{dnl} comments; reserving @samp{#}-comments to
11722 document the output).
11723 @end defmac
11725 Of course, you might encounter exceptions to these generic rules, for
11726 instance you might have to refer to @samp{$m4_flags}.
11728 @defmac m4_pattern_allow (@var{pattern})
11729 @msindex{pattern_allow}
11730 Any token matching @var{pattern} is allowed, including if it matches an
11731 @code{m4_pattern_forbid} pattern.
11732 @end defmac
11734 @node Programming in M4sh
11735 @section Programming in M4sh
11737 @c FIXME: Eventually will become a chapter, as it is not related to
11738 @c programming in M4 per se.
11740 M4sh, pronounced ``mash'', is aiming at producing portable Bourne shell
11741 scripts.  This name was coined by Lars J. Aas, who notes that,
11742 according to the Webster's Revised Unabridged Dictionary (1913):
11744 @quotation
11745 Mash \Mash\, n.  [Akin to G. meisch, maisch, meische, maische, mash,
11746 wash, and prob.@: to AS. miscian to mix.  See ``Mix''.]
11748 @enumerate 1
11749 @item
11750 A mass of mixed ingredients reduced to a soft pulpy state by beating or
11751 pressure@enddots{}
11753 @item
11754 A mixture of meal or bran and water fed to animals.
11756 @item
11757 A mess; trouble.  [Obs.] --Beau.@: & Fl.
11758 @end enumerate
11759 @end quotation
11762 For the time being, it is not mature enough to be widely used.
11764 M4sh reserves the M4 macro namespace @samp{^_AS_} for internal use, and
11765 the namespace @samp{^AS_} for M4sh macros.  It also reserves the shell
11766 and environment variable namespace @samp{^as_}, and the here-doc
11767 delimiter namespace @samp{^_AS[A-Z]} in the output file.  You should not
11768 define your own macros or output shell code that conflicts with these
11769 namespaces.
11771 M4sh provides portable alternatives for some common shell constructs
11772 that unfortunately are not portable in practice.
11774 @c Deprecated, to be replaced by a better API
11775 @ignore
11776 @defmac AS_BASENAME (@var{file-name})
11777 @asindex{BASENAME}
11778 Output the non-directory portion of @var{file-name}.  For example,
11779 if @code{$file} is @samp{/one/two/three}, the command
11780 @code{base=`AS_BASENAME(["$file"])`} sets @code{base} to @samp{three}.
11781 @end defmac
11782 @end ignore
11784 @defmac AS_BOURNE_COMPATIBLE
11785 @asindex{BOURNE_COMPATIBLE}
11786 Set up the shell to be more compatible with the Bourne shell as
11787 standardized by Posix, if possible.  This may involve setting
11788 environment variables, or setting options, or similar
11789 implementation-specific actions.
11790 @end defmac
11792 @defmac AS_CASE (@var{word}, @ovar{pattern1}, @ovar{if-matched1}, @
11793   @dots{}, @ovar{default})
11794 @asindex{CASE}
11795 Expand into a shell @samp{case} statement, where @var{word} is matched
11796 against one or more patterns.  @var{if-matched} is run if the
11797 corresponding pattern matched @var{word}, else @var{default} is run.
11798 @end defmac
11800 @defmac AS_DIRNAME (@var{file-name})
11801 @asindex{DIRNAME}
11802 Output the directory portion of @var{file-name}.  For example,
11803 if @code{$file} is @samp{/one/two/three}, the command
11804 @code{dir=`AS_DIRNAME(["$file"])`} sets @code{dir} to @samp{/one/two}.
11805 @end defmac
11807 @defmac AS_IF (@var{test1}, @ovar{run-if-true1}, @dots{}, @ovar{run-if-false})
11808 @asindex{IF}
11809 Run shell code @var{test1}.  If @var{test1} exits with a zero status then
11810 run shell code @var{run-if-true1}, else examine further tests.  If no test
11811 exits with a zero status, run shell code @var{run-if-false}, with
11812 simplifications if either @var{run-if-true1} or @var{run-if-false1}
11813 is empty.  For example,
11815 @example
11816 AS_IF([test "$foo" = yes], [HANDLE_FOO([yes])],
11817       [test "$foo" != no], [HANDLE_FOO([maybe])],
11818       [echo foo not specified])
11819 @end example
11821 @noindent
11822 ensures any required macros of @code{HANDLE_FOO}
11823 are expanded before the first test.
11824 @end defmac
11826 @defmac AS_INIT
11827 @asindex{INIT}
11828 Initialize the M4sh environment.  This macro calls @code{m4_init}, then
11829 outputs the @code{#! /bin/sh} line, a notice about where the output was
11830 generated from, and code to sanitize the environment for the rest of the
11831 script.  Finally, it changes the current diversion to @code{BODY}.
11832 @end defmac
11834 @defmac AS_MKDIR_P (@var{file-name})
11835 @asindex{MKDIR_P}
11836 Make the directory @var{file-name}, including intervening directories
11837 as necessary.  This is equivalent to @samp{mkdir -p @var{file-name}},
11838 except that it is portable to older versions of @command{mkdir} that
11839 lack support for the @option{-p} option.  Also, @code{AS_MKDIR_P}
11840 succeeds if @var{file-name} is a symbolic link to an existing directory,
11841 even though Posix is unclear whether @samp{mkdir -p} should
11842 succeed in that case.  If creation of @var{file-name} fails, exit the
11843 script.
11845 Also see the @code{AC_PROG_MKDIR_P} macro (@pxref{Particular Programs}).
11846 @end defmac
11848 @defmac AS_SHELL_SANITIZE
11849 @asindex{SHELL_SANITIZE}
11850 Initialize the shell suitably for @command{configure} scripts.  This has
11851 the effect of @code{AS_BOURNE_COMPATIBLE}, and sets some other
11852 environment variables for predictable results from configuration tests.
11853 For example, it sets @env{LC_ALL} to change to the default C locale.
11854 @xref{Special Shell Variables}.
11855 @end defmac
11857 @defmac AS_TR_CPP (@var{expression})
11858 @asindex{TR_CPP}
11859 Transform @var{expression} into a valid right-hand side for a C @code{#define}.
11860 For example:
11862 @example
11863 # This outputs "#define HAVE_CHAR_P 1".
11864 type="char *"
11865 echo "#define AS_TR_CPP([HAVE_$type]) 1"
11866 @end example
11867 @end defmac
11869 @defmac AS_TR_SH (@var{expression})
11870 @asindex{TR_SH}
11871 Transform @var{expression} into a valid shell variable name.  For example:
11873 @example
11874 # This outputs "Have it!".
11875 header="sys/some file.h"
11876 AS_TR_SH([HAVE_$header])=yes
11877 if test "$HAVE_sys_some_file_h" = yes; then echo "Have it!"; fi
11878 @end example
11879 @end defmac
11881 @defmac AS_SET_CATFILE (@var{var}, @var{dir}, @var{file})
11882 @asindex{SET_CATFILE}
11883 Set the shell variable @var{var} to @var{dir}/@var{file}, but
11884 optimizing the common cases (@var{dir} or @var{file} is @samp{.},
11885 @var{file} is absolute, etc.).
11886 @end defmac
11889 @node File Descriptor Macros
11890 @section File Descriptor Macros
11891 @cindex input
11892 @cindex standard input
11893 @cindex file descriptors
11894 @cindex descriptors
11895 @cindex low-level output
11896 @cindex output, low-level
11898 The following macros define file descriptors used to output messages
11899 (or input values) from @file{configure} scripts.
11900 For example:
11902 @example
11903 echo "$wombats found" >&AS_MESSAGE_LOG_FD
11904 echo 'Enter desired kangaroo count:' >&AS_MESSAGE_FD
11905 read kangaroos <&AS_ORIGINAL_STDIN_FD`
11906 @end example
11908 @noindent
11909 However doing so is seldom needed, because Autoconf provides higher
11910 level macros as described below.
11912 @defmac AS_MESSAGE_FD
11913 @asindex{MESSAGE_FD}
11914 The file descriptor for @samp{checking for...}  messages and results.
11915 Normally this directs messages to the standard output, however when
11916 @command{configure} is run with the @option{-q} option, messages sent to
11917 @code{AS_MESSAGE_FD} are discarded.
11919 If you want to display some messages, consider using one of the printing
11920 macros (@pxref{Printing Messages}) instead.  Copies of messages output
11921 via these macros are also recorded in @file{config.log}.
11922 @end defmac
11924 @defmac AS_MESSAGE_LOG_FD
11925 @asindex{MESSAGE_LOG_FD}
11927 The file descriptor for messages logged to @file{config.log}.  Macros
11928 that run tools, like @code{AC_COMPILE_IFELSE} (@pxref{Running the
11929 Compiler}), redirect all output to this descriptor.  You may want to do
11930 so if you develop such a low-level macro.
11931 @end defmac
11933 @defmac AS_ORIGINAL_STDIN_FD
11934 @asindex{ORIGINAL_STDIN_FD}
11935 The file descriptor for the original standard input.
11937 When @command{configure} runs, it may accidentally execute an
11938 interactive command that has the same name as the non-interactive meant
11939 to be used or checked.  If the standard input was the terminal, such
11940 interactive programs would cause @command{configure} to stop, pending
11941 some user input.  Therefore @command{configure} redirects its standard
11942 input from @file{/dev/null} during its initialization.  This is not
11943 normally a problem, since @command{configure} normally does not need
11944 user input.
11946 In the extreme case where your @file{configure} script really needs to
11947 obtain some values from the original standard input, you can read them
11948 explicitly from @code{AS_ORIGINAL_STDIN_FD}.
11949 @end defmac
11952 @c =================================================== Writing Autoconf Macros.
11954 @node Writing Autoconf Macros
11955 @chapter Writing Autoconf Macros
11957 When you write a feature test that could be applicable to more than one
11958 software package, the best thing to do is encapsulate it in a new macro.
11959 Here are some instructions and guidelines for writing Autoconf macros.
11961 @menu
11962 * Macro Definitions::           Basic format of an Autoconf macro
11963 * Macro Names::                 What to call your new macros
11964 * Reporting Messages::          Notifying @command{autoconf} users
11965 * Dependencies Between Macros::  What to do when macros depend on other macros
11966 * Obsoleting Macros::           Warning about old ways of doing things
11967 * Coding Style::                Writing Autoconf macros @`a la Autoconf
11968 @end menu
11970 @node Macro Definitions
11971 @section Macro Definitions
11973 @acindex{DEFUN}
11974 Autoconf macros are defined using the @code{AC_DEFUN} macro, which is
11975 similar to the M4 builtin @code{m4_define} macro.  In addition to
11976 defining a macro, @code{AC_DEFUN} adds to it some code that is used to
11977 constrain the order in which macros are called (@pxref{Prerequisite
11978 Macros}).
11980 An Autoconf macro definition looks like this:
11982 @example
11983 AC_DEFUN(@var{macro-name}, @var{macro-body})
11984 @end example
11986 You can refer to any arguments passed to the macro as @samp{$1},
11987 @samp{$2}, etc.  @xref{Definitions, , How to define new macros, m4.info,
11988 @acronym{GNU} M4}, for more complete information on writing M4 macros.
11990 Be sure to properly quote both the @var{macro-body} @emph{and} the
11991 @var{macro-name} to avoid any problems if the macro happens to have
11992 been previously defined.
11994 Each macro should have a header comment that gives its prototype, and a
11995 brief description.  When arguments have default values, display them in
11996 the prototype.  For example:
11998 @example
11999 # AC_MSG_ERROR(ERROR, [EXIT-STATUS = 1])
12000 # --------------------------------------
12001 m4_define([AC_MSG_ERROR],
12002   [@{ AS_MESSAGE([error: $1], [2])
12003      exit m4_default([$2], [1]); @}])
12004 @end example
12006 Comments about the macro should be left in the header comment.  Most
12007 other comments make their way into @file{configure}, so just keep
12008 using @samp{#} to introduce comments.
12010 @cindex @code{dnl}
12011 If you have some special comments about pure M4 code, comments
12012 that make no sense in @file{configure} and in the header comment, then
12013 use the builtin @code{dnl}: it causes M4 to discard the text
12014 through the next newline.
12016 Keep in mind that @code{dnl} is rarely needed to introduce comments;
12017 @code{dnl} is more useful to get rid of the newlines following macros
12018 that produce no output, such as @code{AC_REQUIRE}.
12021 @node Macro Names
12022 @section Macro Names
12024 All of the public Autoconf macros have all-uppercase names in the
12025 namespace @samp{^AC_} to prevent them from accidentally conflicting with
12026 other text; Autoconf also reserves the namespace @samp{^_AC_} for
12027 internal macros.  All shell variables that they use for internal
12028 purposes have mostly-lowercase names starting with @samp{ac_}.  Autoconf
12029 also uses here-doc delimiters in the namespace @samp{^_AC[A-Z]}.  During
12030 @command{configure}, files produced by Autoconf make heavy use of the
12031 file system namespace @samp{^conf}.
12033 Since Autoconf is built on top of M4sugar (@pxref{Programming in
12034 M4sugar}) and M4sh (@pxref{Programming in M4sh}), you must also be aware
12035 of those namespaces (@samp{^_?\(m4\|AS\)_}).  And since
12036 @file{configure.ac} is also designed to be scanned by Autoheader,
12037 Autoscan, Autoupdate, and Automake, you should be aware of the
12038 @samp{^_?A[HNUM]_} namespaces.  In general, you @emph{should not use}
12039 the namespace of a package that does not own the macro or shell code you
12040 are writing.
12042 To ensure that your macros don't conflict with present or future
12043 Autoconf macros, you should prefix your own macro names and any shell
12044 variables they use with some other sequence.  Possibilities include your
12045 initials, or an abbreviation for the name of your organization or
12046 software package.  Historically, people have not always followed the
12047 rule of using a namespace appropriate for their package, and this has
12048 made it difficult for determining the origin of a macro (and where to
12049 report bugs about that macro), as well as difficult for the true
12050 namespace owner to add new macros without interference from pre-existing
12051 uses of third-party macros.  Perhaps the best example of this confusion
12052 is the @code{AM_GNU_GETTEXT} macro, which belongs, not to Automake, but
12053 to Gettext.
12055 Most of the Autoconf macros' names follow a structured naming convention
12056 that indicates the kind of feature check by the name.  The macro names
12057 consist of several words, separated by underscores, going from most
12058 general to most specific.  The names of their cache variables use the
12059 same convention (@pxref{Cache Variable Names}, for more information on
12060 them).
12062 The first word of the name after the namepace initials (such as
12063 @samp{AC_}) usually tells the category
12064 of the feature being tested.  Here are the categories used in Autoconf for
12065 specific test macros, the kind of macro that you are more likely to
12066 write.  They are also used for cache variables, in all-lowercase.  Use
12067 them where applicable; where they're not, invent your own categories.
12069 @table @code
12070 @item C
12071 C language builtin features.
12072 @item DECL
12073 Declarations of C variables in header files.
12074 @item FUNC
12075 Functions in libraries.
12076 @item GROUP
12077 Posix group owners of files.
12078 @item HEADER
12079 Header files.
12080 @item LIB
12081 C libraries.
12082 @item PROG
12083 The base names of programs.
12084 @item MEMBER
12085 Members of aggregates.
12086 @item SYS
12087 Operating system features.
12088 @item TYPE
12089 C builtin or declared types.
12090 @item VAR
12091 C variables in libraries.
12092 @end table
12094 After the category comes the name of the particular feature being
12095 tested.  Any further words in the macro name indicate particular aspects
12096 of the feature.  For example, @code{AC_PROG_CC_STDC} checks whether the
12097 C compiler supports @acronym{ISO} Standard C.
12099 An internal macro should have a name that starts with an underscore;
12100 Autoconf internals should therefore start with @samp{_AC_}.
12101 Additionally, a macro that is an internal subroutine of another macro
12102 should have a name that starts with an underscore and the name of that
12103 other macro, followed by one or more words saying what the internal
12104 macro does.  For example, @code{AC_PATH_X} has internal macros
12105 @code{_AC_PATH_X_XMKMF} and @code{_AC_PATH_X_DIRECT}.
12107 @node Reporting Messages
12108 @section Reporting Messages
12109 @cindex Messages, from @command{autoconf}
12111 When macros statically diagnose abnormal situations, benign or fatal, it
12112 is possible to make @command{autoconf} detect the problem, and refuse to
12113 create @file{configure} in the case of an error.  The macros in this
12114 section are considered obsolescent, and new code should use M4sugar
12115 macros for this purpose, see @ref{Diagnostic Macros}.
12117 On the other hand, it is possible to want to detect errors when
12118 @command{configure} is run, which are dependent on the environment of
12119 the user rather than the maintainer.  For dynamic diagnostics, see
12120 @ref{Printing Messages}.
12122 @defmac AC_DIAGNOSE (@var{category}, @var{message})
12123 @acindex{DIAGNOSE}
12124 Report @var{message} as a warning (or as an error if requested by the
12125 user) if warnings of the @var{category} are turned on.  This macro is
12126 obsolescent; you are encouraged to use:
12127 @example
12128 m4_warn([@var{category}], [@var{message}])
12129 @end example
12130 @noindent
12131 instead.  @xref{m4_warn}, for more details, including valid
12132 @var{category} names.
12133 @end defmac
12135 @defmac AC_WARNING (@var{message})
12136 @acindex{WARNING}
12137 Report @var{message} as a syntax warning.  This macro is obsolescent;
12138 you are encouraged to use:
12139 @example
12140 m4_warn([syntax], [@var{message}])
12141 @end example
12142 @noindent
12143 instead.  @xref{m4_warn}, for more details, as well as better
12144 finer-grained categories of warnings (not all problems have to do with
12145 syntax).
12146 @end defmac
12148 @defmac AC_FATAL (@var{message})
12149 @acindex{FATAL}
12150 Report a severe error @var{message}, and have @command{autoconf} die.
12151 This macro is obsolescent; you are encouraged to use:
12152 @example
12153 m4_fatal([@var{message}])
12154 @end example
12155 @noindent
12156 instead.  @xref{m4_fatal}, for more details.
12157 @end defmac
12159 When the user runs @samp{autoconf -W error}, warnings from
12160 @code{m4_warn} (including those issued through @code{AC_DIAGNOSE} and
12161 @code{AC_WARNING}) are reported as errors, see @ref{autoconf Invocation}.
12163 @node Dependencies Between Macros
12164 @section Dependencies Between Macros
12165 @cindex Dependencies between macros
12167 Some Autoconf macros depend on other macros having been called first in
12168 order to work correctly.  Autoconf provides a way to ensure that certain
12169 macros are called if needed and a way to warn the user if macros are
12170 called in an order that might cause incorrect operation.
12172 @menu
12173 * Prerequisite Macros::         Ensuring required information
12174 * Suggested Ordering::          Warning about possible ordering problems
12175 * One-Shot Macros::             Ensuring a macro is called only once
12176 @end menu
12178 @node Prerequisite Macros
12179 @subsection Prerequisite Macros
12180 @cindex Prerequisite macros
12181 @cindex Macros, prerequisites
12183 A macro that you write might need to use values that have previously
12184 been computed by other macros.  For example, @code{AC_DECL_YYTEXT}
12185 examines the output of @code{flex} or @code{lex}, so it depends on
12186 @code{AC_PROG_LEX} having been called first to set the shell variable
12187 @code{LEX}.
12189 Rather than forcing the user of the macros to keep track of the
12190 dependencies between them, you can use the @code{AC_REQUIRE} macro to do
12191 it automatically.  @code{AC_REQUIRE} can ensure that a macro is only
12192 called if it is needed, and only called once.
12194 @defmac AC_REQUIRE (@var{macro-name})
12195 @acindex{REQUIRE}
12196 If the M4 macro @var{macro-name} has not already been called, call it
12197 (without any arguments).  Make sure to quote @var{macro-name} with
12198 square brackets.  @var{macro-name} must have been defined using
12199 @code{AC_DEFUN} or else contain a call to @code{AC_PROVIDE} to indicate
12200 that it has been called.
12202 @code{AC_REQUIRE} must be used inside a macro defined by @code{AC_DEFUN}; it
12203 must not be called from the top level.
12204 @end defmac
12206 @code{AC_REQUIRE} is often misunderstood.  It really implements
12207 dependencies between macros in the sense that if one macro depends upon
12208 another, the latter is expanded @emph{before} the body of the
12209 former.  To be more precise, the required macro is expanded before
12210 the outermost defined macro in the current expansion stack.
12211 In particular, @samp{AC_REQUIRE([FOO])} is not replaced with the body of
12212 @code{FOO}.  For instance, this definition of macros:
12214 @example
12215 @group
12216 AC_DEFUN([TRAVOLTA],
12217 [test "$body_temperature_in_celsius" -gt "38" &&
12218   dance_floor=occupied])
12219 AC_DEFUN([NEWTON_JOHN],
12220 [test "$hair_style" = "curly" &&
12221   dance_floor=occupied])
12222 @end group
12224 @group
12225 AC_DEFUN([RESERVE_DANCE_FLOOR],
12226 [if date | grep '^Sat.*pm' >/dev/null 2>&1; then
12227   AC_REQUIRE([TRAVOLTA])
12228   AC_REQUIRE([NEWTON_JOHN])
12229 fi])
12230 @end group
12231 @end example
12233 @noindent
12234 with this @file{configure.ac}
12236 @example
12237 AC_INIT([Dance Manager], [1.0], [bug-dance@@example.org])
12238 RESERVE_DANCE_FLOOR
12239 if test "$dance_floor" = occupied; then
12240   AC_MSG_ERROR([cannot pick up here, let's move])
12242 @end example
12244 @noindent
12245 does not leave you with a better chance to meet a kindred soul at
12246 other times than Saturday night since it expands into:
12248 @example
12249 @group
12250 test "$body_temperature_in_Celsius" -gt "38" &&
12251   dance_floor=occupied
12252 test "$hair_style" = "curly" &&
12253   dance_floor=occupied
12255 if date | grep '^Sat.*pm' >/dev/null 2>&1; then
12259 @end group
12260 @end example
12262 This behavior was chosen on purpose: (i) it prevents messages in
12263 required macros from interrupting the messages in the requiring macros;
12264 (ii) it avoids bad surprises when shell conditionals are used, as in:
12266 @example
12267 @group
12268 if @dots{}; then
12269   AC_REQUIRE([SOME_CHECK])
12271 @dots{}
12272 SOME_CHECK
12273 @end group
12274 @end example
12276 The helper macros @code{AS_IF} and @code{AS_CASE} may be used to
12277 enforce expansion of required macros outside of shell conditional
12278 constructs.  You are furthermore encouraged to put all @code{AC_REQUIRE} calls
12279 at the beginning of a macro.  You can use @code{dnl} to avoid the empty
12280 lines they leave.
12282 @node Suggested Ordering
12283 @subsection Suggested Ordering
12284 @cindex Macros, ordering
12285 @cindex Ordering macros
12287 Some macros should be run before another macro if both are called, but
12288 neither @emph{requires} that the other be called.  For example, a macro
12289 that changes the behavior of the C compiler should be called before any
12290 macros that run the C compiler.  Many of these dependencies are noted in
12291 the documentation.
12293 Autoconf provides the @code{AC_BEFORE} macro to warn users when macros
12294 with this kind of dependency appear out of order in a
12295 @file{configure.ac} file.  The warning occurs when creating
12296 @command{configure} from @file{configure.ac}, not when running
12297 @command{configure}.
12299 For example, @code{AC_PROG_CPP} checks whether the C compiler
12300 can run the C preprocessor when given the @option{-E} option.  It should
12301 therefore be called after any macros that change which C compiler is
12302 being used, such as @code{AC_PROG_CC}.  So @code{AC_PROG_CC} contains:
12304 @example
12305 AC_BEFORE([$0], [AC_PROG_CPP])dnl
12306 @end example
12308 @noindent
12309 This warns the user if a call to @code{AC_PROG_CPP} has already occurred
12310 when @code{AC_PROG_CC} is called.
12312 @defmac AC_BEFORE (@var{this-macro-name}, @var{called-macro-name})
12313 @acindex{BEFORE}
12314 Make M4 print a warning message to the standard error output if
12315 @var{called-macro-name} has already been called.  @var{this-macro-name}
12316 should be the name of the macro that is calling @code{AC_BEFORE}.  The
12317 macro @var{called-macro-name} must have been defined using
12318 @code{AC_DEFUN} or else contain a call to @code{AC_PROVIDE} to indicate
12319 that it has been called.
12320 @end defmac
12322 @node One-Shot Macros
12323 @subsection One-Shot Macros
12324 @cindex One-shot macros
12325 @cindex Macros, called once
12327 Some macros should be called only once, either because calling them
12328 multiple time is unsafe, or because it is bad style.  For instance
12329 Autoconf ensures that @code{AC_CANONICAL_BUILD} and cousins
12330 (@pxref{Canonicalizing}) are evaluated only once, because it makes no
12331 sense to run these expensive checks more than once.  Such one-shot
12332 macros can be defined using @code{AC_DEFUN_ONCE}.
12334 @defmac AC_DEFUN_ONCE (@var{macro-name}, @var{macro-body})
12335 @acindex{DEFUN_ONCE}
12337 Declare macro @var{macro-name} like @code{AC_DEFUN} would (@pxref{Macro
12338 Definitions}), and emit a warning any time the macro is called more than
12339 once.
12340 @end defmac
12342 Obviously it is not sensible to evaluate a macro defined by
12343 @code{AC_DEFUN_ONCE} in a macro defined by @code{AC_DEFUN}.
12344 Most of the time you want to use @code{AC_REQUIRE} (@pxref{Prerequisite
12345 Macros}).
12347 @node Obsoleting Macros
12348 @section Obsoleting Macros
12349 @cindex Obsoleting macros
12350 @cindex Macros, obsoleting
12352 Configuration and portability technology has evolved over the years.
12353 Often better ways of solving a particular problem are developed, or
12354 ad-hoc approaches are systematized.  This process has occurred in many
12355 parts of Autoconf.  One result is that some of the macros are now
12356 considered @dfn{obsolete}; they still work, but are no longer considered
12357 the best thing to do, hence they should be replaced with more modern
12358 macros.  Ideally, @command{autoupdate} should replace the old macro calls
12359 with their modern implementation.
12361 Autoconf provides a simple means to obsolete a macro.
12363 @anchor{AU_DEFUN}
12364 @defmac AU_DEFUN (@var{old-macro}, @var{implementation}, @ovar{message})
12365 @auindex{DEFUN}
12366 Define @var{old-macro} as @var{implementation}.  The only difference
12367 with @code{AC_DEFUN} is that the user is warned that
12368 @var{old-macro} is now obsolete.
12370 If she then uses @command{autoupdate}, the call to @var{old-macro} is
12371 replaced by the modern @var{implementation}.  @var{message} should
12372 include information on what to do after running @command{autoupdate};
12373 @command{autoupdate} prints it as a warning, and includes it
12374 in the updated @file{configure.ac} file.
12376 The details of this macro are hairy: if @command{autoconf} encounters an
12377 @code{AU_DEFUN}ed macro, all macros inside its second argument are expanded
12378 as usual.  However, when @command{autoupdate} is run, only M4 and M4sugar
12379 macros are expanded here, while all other macros are disabled and
12380 appear literally in the updated @file{configure.ac}.
12381 @end defmac
12383 @defmac AU_ALIAS (@var{old-name}, @var{new-name})
12384 @auindex{ALIAS}
12385 Used if the @var{old-name} is to be replaced by a call to @var{new-macro}
12386 with the same parameters.  This happens for example if the macro was renamed.
12387 @end defmac
12389 @node Coding Style
12390 @section Coding Style
12391 @cindex Coding style
12393 The Autoconf macros follow a strict coding style.  You are encouraged to
12394 follow this style, especially if you intend to distribute your macro,
12395 either by contributing it to Autoconf itself, or via other means.
12397 The first requirement is to pay great attention to the quotation.  For
12398 more details, see @ref{Autoconf Language}, and @ref{M4 Quotation}.
12400 Do not try to invent new interfaces.  It is likely that there is a macro
12401 in Autoconf that resembles the macro you are defining: try to stick to
12402 this existing interface (order of arguments, default values, etc.).  We
12403 @emph{are} conscious that some of these interfaces are not perfect;
12404 nevertheless, when harmless, homogeneity should be preferred over
12405 creativity.
12407 Be careful about clashes both between M4 symbols and between shell
12408 variables.
12410 If you stick to the suggested M4 naming scheme (@pxref{Macro Names}),
12411 you are unlikely to generate conflicts.  Nevertheless, when you need to
12412 set a special value, @emph{avoid using a regular macro name}; rather,
12413 use an ``impossible'' name.  For instance, up to version 2.13, the macro
12414 @code{AC_SUBST} used to remember what @var{symbol} macros were already defined
12415 by setting @code{AC_SUBST_@var{symbol}}, which is a regular macro name.
12416 But since there is a macro named @code{AC_SUBST_FILE}, it was just
12417 impossible to @samp{AC_SUBST(FILE)}!  In this case,
12418 @code{AC_SUBST(@var{symbol})} or @code{_AC_SUBST(@var{symbol})} should
12419 have been used (yes, with the parentheses).
12420 @c or better yet, high-level macros such as @code{m4_expand_once}
12422 No Autoconf macro should ever enter the user-variable name space; i.e.,
12423 except for the variables that are the actual result of running the
12424 macro, all shell variables should start with @code{ac_}.  In
12425 addition, small macros or any macro that is likely to be embedded in
12426 other macros should be careful not to use obvious names.
12428 @cindex @code{dnl}
12429 Do not use @code{dnl} to introduce comments: most of the comments you
12430 are likely to write are either header comments which are not output
12431 anyway, or comments that should make their way into @file{configure}.
12432 There are exceptional cases where you do want to comment special M4
12433 constructs, in which case @code{dnl} is right, but keep in mind that it
12434 is unlikely.
12436 M4 ignores the leading blanks and newlines before each argument.
12437 Use this feature to
12438 indent in such a way that arguments are (more or less) aligned with the
12439 opening parenthesis of the macro being called.  For instance, instead of
12441 @example
12442 AC_CACHE_CHECK(for EMX OS/2 environment,
12443 ac_cv_emxos2,
12444 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM(, [return __EMX__;])],
12445 [ac_cv_emxos2=yes], [ac_cv_emxos2=no])])
12446 @end example
12448 @noindent
12449 write
12451 @example
12452 AC_CACHE_CHECK([for EMX OS/2 environment], [ac_cv_emxos2],
12453 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([], [return __EMX__;])],
12454                    [ac_cv_emxos2=yes],
12455                    [ac_cv_emxos2=no])])
12456 @end example
12458 @noindent
12459 or even
12461 @example
12462 AC_CACHE_CHECK([for EMX OS/2 environment],
12463                [ac_cv_emxos2],
12464                [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([],
12465                                                    [return __EMX__;])],
12466                                   [ac_cv_emxos2=yes],
12467                                   [ac_cv_emxos2=no])])
12468 @end example
12470 When using @code{AC_RUN_IFELSE} or any macro that cannot work when
12471 cross-compiling, provide a pessimistic value (typically @samp{no}).
12473 Feel free to use various tricks to prevent auxiliary tools, such as
12474 syntax-highlighting editors, from behaving improperly.  For instance,
12475 instead of:
12477 @example
12478 m4_bpatsubst([$1], [$"])
12479 @end example
12481 @noindent
12484 @example
12485 m4_bpatsubst([$1], [$""])
12486 @end example
12488 @noindent
12489 so that Emacsen do not open an endless ``string'' at the first quote.
12490 For the same reasons, avoid:
12492 @example
12493 test $[#] != 0
12494 @end example
12496 @noindent
12497 and use:
12499 @example
12500 test $[@@%:@@] != 0
12501 @end example
12503 @noindent
12504 Otherwise, the closing bracket would be hidden inside a @samp{#}-comment,
12505 breaking the bracket-matching highlighting from Emacsen.  Note the
12506 preferred style to escape from M4: @samp{$[1]}, @samp{$[@@]}, etc.  Do
12507 not escape when it is unnecessary.  Common examples of useless quotation
12508 are @samp{[$]$1} (write @samp{$$1}), @samp{[$]var} (use @samp{$var}),
12509 etc.  If you add portability issues to the picture, you'll prefer
12510 @samp{$@{1+"$[@@]"@}} to @samp{"[$]@@"}, and you'll prefer do something
12511 better than hacking Autoconf @code{:-)}.
12513 When using @command{sed}, don't use @option{-e} except for indenting
12514 purposes.  With the @code{s} and @code{y} commands, the preferred
12515 separator is @samp{/} unless @samp{/} itself might appear in the pattern
12516 or replacement, in which case you should use @samp{|}, or optionally
12517 @samp{,} if you know the pattern and replacement cannot contain a file
12518 name.  If none of these characters will do, choose a printable character
12519 that cannot appear in the pattern or replacement.  Characters from the
12520 set @samp{"#$&'()*;<=>?`|~} are good choices if the pattern or
12521 replacement might contain a file name, since they have special meaning
12522 to the shell and are less likely to occur in file names.
12524 @xref{Macro Definitions}, for details on how to define a macro.  If a
12525 macro doesn't use @code{AC_REQUIRE}, is expected to never be the object
12526 of an @code{AC_REQUIRE} directive, and macros required by other macros
12527 inside arguments do not need to be expanded before this macro, then
12528 use @code{m4_define}.  In case of doubt, use @code{AC_DEFUN}.
12529 All the @code{AC_REQUIRE} statements should be at the beginning of the
12530 macro, and each statement should be followed by @code{dnl}.
12532 You should not rely on the number of arguments: instead of checking
12533 whether an argument is missing, test that it is not empty.  It provides
12534 both a simpler and a more predictable interface to the user, and saves
12535 room for further arguments.
12537 Unless the macro is short, try to leave the closing @samp{])} at the
12538 beginning of a line, followed by a comment that repeats the name of the
12539 macro being defined.  This introduces an additional newline in
12540 @command{configure}; normally, that is not a problem, but if you want to
12541 remove it you can use @samp{[]dnl} on the last line.  You can similarly
12542 use @samp{[]dnl} after a macro call to remove its newline.  @samp{[]dnl}
12543 is recommended instead of @samp{dnl} to ensure that M4 does not
12544 interpret the @samp{dnl} as being attached to the preceding text or
12545 macro output.  For example, instead of:
12547 @example
12548 AC_DEFUN([AC_PATH_X],
12549 [AC_MSG_CHECKING([for X])
12550 AC_REQUIRE_CPP()
12551 @r{# @dots{}omitted@dots{}}
12552   AC_MSG_RESULT([libraries $x_libraries, headers $x_includes])
12553 fi])
12554 @end example
12556 @noindent
12557 you would write:
12559 @example
12560 AC_DEFUN([AC_PATH_X],
12561 [AC_REQUIRE_CPP()[]dnl
12562 AC_MSG_CHECKING([for X])
12563 @r{# @dots{}omitted@dots{}}
12564   AC_MSG_RESULT([libraries $x_libraries, headers $x_includes])
12565 fi[]dnl
12566 ])# AC_PATH_X
12567 @end example
12569 If the macro is long, try to split it into logical chunks.  Typically,
12570 macros that check for a bug in a function and prepare its
12571 @code{AC_LIBOBJ} replacement should have an auxiliary macro to perform
12572 this setup.  Do not hesitate to introduce auxiliary macros to factor
12573 your code.
12575 In order to highlight the recommended coding style, here is a macro
12576 written the old way:
12578 @example
12579 dnl Check for EMX on OS/2.
12580 dnl _AC_EMXOS2
12581 AC_DEFUN(_AC_EMXOS2,
12582 [AC_CACHE_CHECK(for EMX OS/2 environment, ac_cv_emxos2,
12583 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM(, return __EMX__;)],
12584 ac_cv_emxos2=yes, ac_cv_emxos2=no)])
12585 test "$ac_cv_emxos2" = yes && EMXOS2=yes])
12586 @end example
12588 @noindent
12589 and the new way:
12591 @example
12592 # _AC_EMXOS2
12593 # ----------
12594 # Check for EMX on OS/2.
12595 m4_define([_AC_EMXOS2],
12596 [AC_CACHE_CHECK([for EMX OS/2 environment], [ac_cv_emxos2],
12597 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([], [return __EMX__;])],
12598                    [ac_cv_emxos2=yes],
12599                    [ac_cv_emxos2=no])])
12600 test "$ac_cv_emxos2" = yes && EMXOS2=yes[]dnl
12601 ])# _AC_EMXOS2
12602 @end example
12607 @c ============================================= Portable Shell Programming
12609 @node Portable Shell
12610 @chapter Portable Shell Programming
12611 @cindex Portable shell programming
12613 When writing your own checks, there are some shell-script programming
12614 techniques you should avoid in order to make your code portable.  The
12615 Bourne shell and upward-compatible shells like the Korn shell and Bash
12616 have evolved over the years, but to prevent trouble, do not take
12617 advantage of features that were added after Unix version 7, circa
12618 1977 (@pxref{Systemology}).
12620 You should not use aliases, negated character classes, or other features
12621 that are not found in all Bourne-compatible shells; restrict yourself
12622 to the lowest common denominator.  Even @code{unset} is not supported
12623 by all shells!
12625 Shell functions are considered portable nowadays, though Autoconf still
12626 does not use them (Autotest does).  However, some pitfalls have to be
12627 avoided for portable use of shell functions (@pxref{Shell Functions}).
12629 Some ancient systems have quite
12630 small limits on the length of the @samp{#!} line; for instance, 32
12631 bytes (not including the newline) on SunOS 4.
12632 A few ancient 4.2@acronym{BSD} based systems (such as Dynix circa 1984)
12633 required a single space between the @samp{#!} and the @samp{/}.
12634 However, these ancient systems are no longer of practical concern.
12636 The set of external programs you should run in a @command{configure} script
12637 is fairly small.  @xref{Utilities in Makefiles, , Utilities in
12638 Makefiles, standards, @acronym{GNU} Coding Standards}, for the list.  This
12639 restriction allows users to start out with a fairly small set of
12640 programs and build the rest, avoiding too many interdependencies between
12641 packages.
12643 Some of these external utilities have a portable subset of features; see
12644 @ref{Limitations of Usual Tools}.
12646 There are other sources of documentation about shells.  The
12647 specification for the Posix
12648 @uref{http://www.opengroup.org/@/susv3/@/utilities/@/xcu_chap02.html, Shell
12649 Command Language}, though more generous than the restrictive shell
12650 subset described above, is fairly portable nowadays.  Also please see
12651 @uref{http://www.faqs.org/@/faqs/@/unix-faq/@/shell/, the Shell FAQs}.
12653 @menu
12654 * Shellology::                  A zoology of shells
12655 * Here-Documents::              Quirks and tricks
12656 * File Descriptors::            FDs and redirections
12657 * File System Conventions::     File names
12658 * Shell Pattern Matching::      Pattern matching
12659 * Shell Substitutions::         Variable and command expansions
12660 * Assignments::                 Varying side effects of assignments
12661 * Parentheses::                 Parentheses in shell scripts
12662 * Slashes::                     Slashes in shell scripts
12663 * Special Shell Variables::     Variables you should not change
12664 * Shell Functions::             What to look out for if you use them
12665 * Limitations of Builtins::     Portable use of not so portable /bin/sh
12666 * Limitations of Usual Tools::  Portable use of portable tools
12667 @end menu
12669 @node Shellology
12670 @section Shellology
12671 @cindex Shellology
12673 There are several families of shells, most prominently the Bourne family
12674 and the C shell family which are deeply incompatible.  If you want to
12675 write portable shell scripts, avoid members of the C shell family.  The
12676 @uref{http://www.faqs.org/@/faqs/@/unix-faq/@/shell/@/shell-differences/, the
12677 Shell difference FAQ} includes a small history of Posix shells, and a
12678 comparison between several of them.
12680 Below we describe some of the members of the Bourne shell family.
12682 @table @asis
12683 @item Ash
12684 @cindex Ash
12685 Ash is often used on @acronym{GNU}/Linux and @acronym{BSD}
12686 systems as a light-weight Bourne-compatible shell.  Ash 0.2 has some
12687 bugs that are fixed in the 0.3.x series, but portable shell scripts
12688 should work around them, since version 0.2 is still shipped with many
12689 @acronym{GNU}/Linux distributions.
12691 To be compatible with Ash 0.2:
12693 @itemize @minus
12694 @item
12695 don't use @samp{$?} after expanding empty or unset variables,
12696 or at the start of an @command{eval}:
12698 @example
12699 foo=
12700 false
12701 $foo
12702 echo "Do not use it: $?"
12703 false
12704 eval 'echo "Do not use it: $?"'
12705 @end example
12707 @item
12708 don't use command substitution within variable expansion:
12710 @example
12711 cat $@{FOO=`bar`@}
12712 @end example
12714 @item
12715 beware that single builtin substitutions are not performed by a
12716 subshell, hence their effect applies to the current shell!  @xref{Shell
12717 Substitutions}, item ``Command Substitution''.
12718 @end itemize
12720 @item Bash
12721 @cindex Bash
12722 To detect whether you are running Bash, test whether
12723 @code{BASH_VERSION} is set.  To require
12724 Posix compatibility, run @samp{set -o posix}.  @xref{Bash POSIX
12725 Mode, , Bash Posix Mode, bash, The @acronym{GNU} Bash Reference
12726 Manual}, for details.
12728 @item Bash 2.05 and later
12729 @cindex Bash 2.05 and later
12730 Versions 2.05 and later of Bash use a different format for the
12731 output of the @command{set} builtin, designed to make evaluating its
12732 output easier.  However, this output is not compatible with earlier
12733 versions of Bash (or with many other shells, probably).  So if
12734 you use Bash 2.05 or higher to execute @command{configure},
12735 you'll need to use Bash 2.05 for all other build tasks as well.
12737 @item Ksh
12738 @cindex Ksh
12739 @cindex Korn shell
12740 @prindex @samp{ksh}
12741 @prindex @samp{ksh88}
12742 @prindex @samp{ksh93}
12743 The Korn shell is compatible with the Bourne family and it mostly
12744 conforms to Posix.  It has two major variants commonly
12745 called @samp{ksh88} and @samp{ksh93}, named after the years of initial
12746 release.  It is usually called @command{ksh}, but is called @command{sh}
12747 on some hosts if you set your path appropriately.
12749 Solaris systems have three variants:
12750 @prindex @command{/usr/bin/ksh} on Solaris
12751 @command{/usr/bin/ksh} is @samp{ksh88}; it is
12752 standard on Solaris 2.0 and later.
12753 @prindex @command{/usr/xpg4/bin/sh} on Solaris
12754 @command{/usr/xpg4/bin/sh} is a Posix-compliant variant of
12755 @samp{ksh88}; it is standard on Solaris 9 and later.
12756 @prindex @command{/usr/dt/bin/dtksh} on Solaris
12757 @command{/usr/dt/bin/dtksh} is @samp{ksh93}.
12758 Variants that are not standard may be parts of optional
12759 packages.  There is no extra charge for these packages, but they are
12760 not part of a minimal OS install and therefore some installations may
12761 not have it.
12763 Starting with Tru64 Version 4.0, the Korn shell @command{/usr/bin/ksh}
12764 is also available as @command{/usr/bin/posix/sh}.  If the environment
12765 variable @env{BIN_SH} is set to @code{xpg4}, subsidiary invocations of
12766 the standard shell conform to Posix.
12768 @item Pdksh
12769 @prindex @samp{pdksh}
12770 A public-domain clone of the Korn shell called @command{pdksh} is widely
12771 available: it has most of the @samp{ksh88} features along with a few of
12772 its own.  It usually sets @code{KSH_VERSION}, except if invoked as
12773 @command{/bin/sh} on Open@acronym{BSD}, and similarly to Bash you can require
12774 Posix compatibility by running @samp{set -o posix}.  Unfortunately, with
12775 @command{pdksh} 5.2.14 (the latest stable version as of January 2007)
12776 Posix mode is buggy and causes @command{pdksh} to depart from Posix in
12777 at least one respect:
12779 @example
12780 $ @kbd{echo "`echo \"hello\"`"}
12781 hello
12782 $ @kbd{set -o posix}
12783 $ @kbd{echo "`echo \"hello\"`"}
12784 "hello"
12785 @end example
12787 The last line of output contains spurious quotes.  This is yet another
12788 reason why portable shell code should not contain
12789 @code{"`@dots{}\"@dots{}\"@dots{}`"} constructs (@pxref{Shell
12790 Substitutions}).
12792 @item Zsh
12793 @cindex Zsh
12794 To detect whether you are running @command{zsh}, test whether
12795 @code{ZSH_VERSION} is set.  By default @command{zsh} is @emph{not}
12796 compatible with the Bourne shell: you must execute @samp{emulate sh},
12797 and for @command{zsh} versions before 3.1.6-dev-18 you must also
12798 set @code{NULLCMD} to @samp{:}.  @xref{Compatibility, , Compatibility,
12799 zsh, The Z Shell Manual}, for details.
12801 The default Mac OS X @command{sh} was originally Zsh; it was changed to
12802 Bash in Mac OS X 10.2.
12803 @end table
12805 The following discussion between Russ Allbery and Robert Lipe is worth
12806 reading:
12808 @noindent
12809 Russ Allbery:
12811 @quotation
12812 The @acronym{GNU} assumption that @command{/bin/sh} is the one and only shell
12813 leads to a permanent deadlock.  Vendors don't want to break users'
12814 existing shell scripts, and there are some corner cases in the Bourne
12815 shell that are not completely compatible with a Posix shell.  Thus,
12816 vendors who have taken this route will @emph{never} (OK@dots{}``never say
12817 never'') replace the Bourne shell (as @command{/bin/sh}) with a
12818 Posix shell.
12819 @end quotation
12821 @noindent
12822 Robert Lipe:
12824 @quotation
12825 This is exactly the problem.  While most (at least most System V's) do
12826 have a Bourne shell that accepts shell functions most vendor
12827 @command{/bin/sh} programs are not the Posix shell.
12829 So while most modern systems do have a shell @emph{somewhere} that meets the
12830 Posix standard, the challenge is to find it.
12831 @end quotation
12833 @node Here-Documents
12834 @section Here-Documents
12835 @cindex Here-documents
12836 @cindex Shell here-documents
12838 Don't rely on @samp{\} being preserved just because it has no special
12839 meaning together with the next symbol.  In the native @command{sh}
12840 on Open@acronym{BSD} 2.7 @samp{\"} expands to @samp{"} in here-documents with
12841 unquoted delimiter.  As a general rule, if @samp{\\} expands to @samp{\}
12842 use @samp{\\} to get @samp{\}.
12844 With Open@acronym{BSD} 2.7's @command{sh}
12846 @example
12847 @group
12848 $ @kbd{cat <<EOF
12849 > \" \\
12850 > EOF}
12851 " \
12852 @end group
12853 @end example
12855 @noindent
12856 and with Bash:
12858 @example
12859 @group
12860 bash-2.04$ @kbd{cat <<EOF
12861 > \" \\
12862 > EOF}
12863 \" \
12864 @end group
12865 @end example
12867 Some shells mishandle large here-documents: for example,
12868 Solaris 10 @command{dtksh} and the UnixWare 7.1.1 Posix shell, which are
12869 derived from Korn shell version M-12/28/93d, mishandle braced variable
12870 expansion that crosses a 1024- or 4096-byte buffer boundary
12871 within a here-document.  Only the part of the variable name after the boundary
12872 is used.  For example, @code{$@{variable@}} could be replaced by the expansion
12873 of @code{$@{ble@}}.  If the end of the variable name is aligned with the block
12874 boundary, the shell reports an error, as if you used @code{$@{@}}.
12875 Instead of @code{$@{variable-default@}}, the shell may expand
12876 @code{$@{riable-default@}}, or even @code{$@{fault@}}.  This bug can often
12877 be worked around by omitting the braces: @code{$variable}.  The bug was
12878 fixed in
12879 @samp{ksh93g} (1998-04-30) but as of 2006 many operating systems were
12880 still shipping older versions with the bug.
12882 Many shells (including the Bourne shell) implement here-documents
12883 inefficiently.  In particular, some shells can be extremely inefficient when
12884 a single statement contains many here-documents.  For instance if your
12885 @file{configure.ac} includes something like:
12887 @example
12888 @group
12889 if <cross_compiling>; then
12890   assume this and that
12891 else
12892   check this
12893   check that
12894   check something else
12895   @dots{}
12896   on and on forever
12897   @dots{}
12899 @end group
12900 @end example
12902 A shell parses the whole @code{if}/@code{fi} construct, creating
12903 temporary files for each here-document in it.  Some shells create links
12904 for such here-documents on every @code{fork}, so that the clean-up code
12905 they had installed correctly removes them.  It is creating the links
12906 that can take the shell forever.
12908 Moving the tests out of the @code{if}/@code{fi}, or creating multiple
12909 @code{if}/@code{fi} constructs, would improve the performance
12910 significantly.  Anyway, this kind of construct is not exactly the
12911 typical use of Autoconf.  In fact, it's even not recommended, because M4
12912 macros can't look into shell conditionals, so we may fail to expand a
12913 macro when it was expanded before in a conditional path, and the
12914 condition turned out to be false at runtime, and we end up not
12915 executing the macro at all.
12917 @node File Descriptors
12918 @section File Descriptors
12919 @cindex Descriptors
12920 @cindex File descriptors
12921 @cindex Shell file descriptors
12923 Most shells, if not all (including Bash, Zsh, Ash), output traces on
12924 stderr, even for subshells.  This might result in undesirable content
12925 if you meant to capture the standard-error output of the inner command:
12927 @example
12928 $ @kbd{ash -x -c '(eval "echo foo >&2") 2>stderr'}
12929 $ @kbd{cat stderr}
12930 + eval echo foo >&2
12931 + echo foo
12933 $ @kbd{bash -x -c '(eval "echo foo >&2") 2>stderr'}
12934 $ @kbd{cat stderr}
12935 + eval 'echo foo >&2'
12936 ++ echo foo
12938 $ @kbd{zsh -x -c '(eval "echo foo >&2") 2>stderr'}
12939 @i{# Traces on startup files deleted here.}
12940 $ @kbd{cat stderr}
12941 +zsh:1> eval echo foo >&2
12942 +zsh:1> echo foo
12944 @end example
12946 @noindent
12947 One workaround is to grep out uninteresting lines, hoping not to remove
12948 good ones.
12950 If you intend to redirect both standard error and standard output,
12951 redirect standard output first.  This works better with @acronym{HP-UX},
12952 since its shell mishandles tracing if standard error is redirected
12953 first:
12955 @example
12956 $ @kbd{sh -x -c ': 2>err >out'}
12957 + :
12958 + 2> err $ @kbd{cat err}
12959 1> out
12960 @end example
12962 Don't try to redirect the standard error of a command substitution.  It
12963 must be done @emph{inside} the command substitution.  When running
12964 @samp{: `cd /zorglub` 2>/dev/null} expect the error message to
12965 escape, while @samp{: `cd /zorglub 2>/dev/null`} works properly.
12967 It is worth noting that Zsh (but not Ash nor Bash) makes it possible
12968 in assignments though: @samp{foo=`cd /zorglub` 2>/dev/null}.
12970 When catering to old systems, don't redirect the same file descriptor
12971 several times, as you are doomed to failure under Ultrix.
12973 @example
12974 ULTRIX V4.4 (Rev. 69) System #31: Thu Aug 10 19:42:23 GMT 1995
12975 UWS V4.4 (Rev. 11)
12976 $ @kbd{eval 'echo matter >fullness' >void}
12977 illegal io
12978 $ @kbd{eval '(echo matter >fullness)' >void}
12979 illegal io
12980 $ @kbd{(eval '(echo matter >fullness)') >void}
12981 Ambiguous output redirect.
12982 @end example
12984 @noindent
12985 In each case the expected result is of course @file{fullness} containing
12986 @samp{matter} and @file{void} being empty.  However, this bug is
12987 probably not of practical concern to modern platforms.
12989 Don't rely on file descriptors 0, 1, and 2 remaining closed in a
12990 subsidiary program.  If any of these descriptors is closed, the
12991 operating system may open an unspecified file for the descriptor in the
12992 new process image.  Posix says this may be done only if the subsidiary
12993 program is set-user-ID or set-group-ID, but @acronym{HP-UX} 11.23 does
12994 it even for ordinary programs.
12996 Don't rely on open file descriptors being open in child processes.  In
12997 @command{ksh}, file descriptors above 2 which are opened using
12998 @samp{exec @var{n}>file} are closed by a subsequent @samp{exec} (such as
12999 that involved in the fork-and-exec which runs a program or script).
13000 Thus, using @command{sh}, we have:
13002 @example
13003 $ @kbd{cat ./descrips}
13004 #!/bin/sh -
13005 echo hello >&5
13006 $ @kbd{exec 5>t}
13007 $ @kbd{./descrips}
13008 $ @kbd{cat t}
13009 hello
13011 @end example
13013 @noindent
13014 But using ksh:
13016 @example
13017 $ @kbd{exec 5>t}
13018 $ @kbd{./descrips}
13019 hello
13020 $ @kbd{cat t}
13022 @end example
13024 @noindent
13025 Within the process which runs the @samp{descrips} script, file
13026 descriptor 5 is closed.
13028 Don't rely on redirection to a closed file descriptor to cause an
13029 error.  With Solaris @command{/bin/sh}, when the redirection fails, the
13030 output goes to the original file descriptor.
13032 @example
13033 $ @kbd{bash -c 'echo hi >&3' 3>&-; echo $?}
13034 bash: 3: Bad file descriptor
13036 $ @kbd{/bin/sh -c 'echo hi >&3' 3>&-; echo $?}
13039 @end example
13041 @acronym{DOS} variants cannot rename or remove open files, such as in
13042 @samp{mv foo bar >foo} or @samp{rm foo >foo}, even though this is
13043 perfectly portable among Posix hosts.
13045 A few ancient systems reserved some file descriptors.  By convention,
13046 file descriptor 3 was opened to @file{/dev/tty} when you logged into
13047 Eighth Edition (1985) through Tenth Edition Unix (1989).  File
13048 descriptor 4 had a special use on the Stardent/Kubota Titan (circa
13049 1990), though we don't now remember what it was.  Both these systems are
13050 obsolete, so it's now safe to treat file descriptors 3 and 4 like any
13051 other file descriptors.
13053 @node File System Conventions
13054 @section File System Conventions
13055 @cindex File system conventions
13057 Autoconf uses shell-script processing extensively, so the file names
13058 that it processes should not contain characters that are special to the
13059 shell.  Special characters include space, tab, newline, @sc{nul}, and
13060 the following:
13062 @example
13063 " # $ & ' ( ) * ; < = > ? [ \ ` |
13064 @end example
13066 Also, file names should not begin with @samp{~} or @samp{-}, and should
13067 contain neither @samp{-} immediately after @samp{/} nor @samp{~}
13068 immediately after @samp{:}.  On Posix-like platforms, directory names
13069 should not contain @samp{:}, as this runs afoul of @samp{:} used as the
13070 path separator.
13072 These restrictions apply not only to the files that you distribute, but
13073 also to the absolute file names of your source, build, and destination
13074 directories.
13076 On some Posix-like platforms, @samp{!} and @samp{^} are special too, so
13077 they should be avoided.
13079 Posix lets implementations treat leading @file{//} specially, but
13080 requires leading @file{///} and beyond to be equivalent to @file{/}.
13081 Most Unix variants treat @file{//} like @file{/}.  However, some treat
13082 @file{//} as a ``super-root'' that can provide access to files that are
13083 not otherwise reachable from @file{/}.  The super-root tradition began
13084 with Apollo Domain/OS, which died out long ago, but unfortunately Cygwin
13085 has revived it.
13087 While @command{autoconf} and friends are usually run on some Posix
13088 variety, they can be used on other systems, most notably @acronym{DOS}
13089 variants.  This impacts several assumptions regarding file names.
13091 @noindent
13092 For example, the following code:
13094 @example
13095 case $foo_dir in
13096   /*) # Absolute
13097      ;;
13098   *)
13099      foo_dir=$dots$foo_dir ;;
13100 esac
13101 @end example
13103 @noindent
13104 fails to properly detect absolute file names on those systems, because
13105 they can use a drivespec, and usually use a backslash as directory
13106 separator.  If you want to be portable to @acronym{DOS} variants (at the
13107 price of rejecting valid but oddball Posix file names like @file{a:\b}),
13108 you can check for absolute file names like this:
13110 @cindex absolute file names, detect
13111 @example
13112 case $foo_dir in
13113   [\\/]* | ?:[\\/]* ) # Absolute
13114      ;;
13115   *)
13116      foo_dir=$dots$foo_dir ;;
13117 esac
13118 @end example
13120 @noindent
13121 Make sure you quote the brackets if appropriate and keep the backslash as
13122 first character (@pxref{Limitations of Builtins}).
13124 Also, because the colon is used as part of a drivespec, these systems don't
13125 use it as path separator.  When creating or accessing paths, you can use the
13126 @code{PATH_SEPARATOR} output variable instead.  @command{configure} sets this
13127 to the appropriate value for the build system (@samp{:} or @samp{;}) when it
13128 starts up.
13130 File names need extra care as well.  While @acronym{DOS} variants
13131 that are Posixy enough to run @command{autoconf} (such as @acronym{DJGPP})
13132 are usually able to handle long file names properly, there are still
13133 limitations that can seriously break packages.  Several of these issues
13134 can be easily detected by the
13135 @uref{ftp://ftp.gnu.org/gnu/non-gnu/doschk/doschk-1.1.tar.gz, doschk}
13136 package.
13138 A short overview follows; problems are marked with @sc{sfn}/@sc{lfn} to
13139 indicate where they apply: @sc{sfn} means the issues are only relevant to
13140 plain @acronym{DOS}, not to @acronym{DOS} under Microsoft Windows
13141 variants, while @sc{lfn} identifies problems that exist even under
13142 Microsoft Windows variants.
13144 @table @asis
13145 @item No multiple dots (@sc{sfn})
13146 @acronym{DOS} cannot handle multiple dots in file names.  This is an especially
13147 important thing to remember when building a portable configure script,
13148 as @command{autoconf} uses a .in suffix for template files.
13150 This is perfectly OK on Posix variants:
13152 @example
13153 AC_CONFIG_HEADERS([config.h])
13154 AC_CONFIG_FILES([source.c foo.bar])
13155 AC_OUTPUT
13156 @end example
13158 @noindent
13159 but it causes problems on @acronym{DOS}, as it requires @samp{config.h.in},
13160 @samp{source.c.in} and @samp{foo.bar.in}.  To make your package more portable
13161 to @acronym{DOS}-based environments, you should use this instead:
13163 @example
13164 AC_CONFIG_HEADERS([config.h:config.hin])
13165 AC_CONFIG_FILES([source.c:source.cin foo.bar:foobar.in])
13166 AC_OUTPUT
13167 @end example
13169 @item No leading dot (@sc{sfn})
13170 @acronym{DOS} cannot handle file names that start with a dot.  This is usually
13171 not important for @command{autoconf}.
13173 @item Case insensitivity (@sc{lfn})
13174 @acronym{DOS} is case insensitive, so you cannot, for example, have both a
13175 file called @samp{INSTALL} and a directory called @samp{install}.  This
13176 also affects @command{make}; if there's a file called @samp{INSTALL} in
13177 the directory, @samp{make install} does nothing (unless the
13178 @samp{install} target is marked as PHONY).
13180 @item The 8+3 limit (@sc{sfn})
13181 Because the @acronym{DOS} file system only stores the first 8 characters of
13182 the file name and the first 3 of the extension, those must be unique.
13183 That means that @file{foobar-part1.c}, @file{foobar-part2.c} and
13184 @file{foobar-prettybird.c} all resolve to the same file name
13185 (@file{FOOBAR-P.C}).  The same goes for @file{foo.bar} and
13186 @file{foo.bartender}.
13188 The 8+3 limit is not usually a problem under Microsoft Windows, as it
13189 uses numeric
13190 tails in the short version of file names to make them unique.  However, a
13191 registry setting can turn this behavior off.  While this makes it
13192 possible to share file trees containing long file names between @sc{sfn}
13193 and @sc{lfn} environments, it also means the above problem applies there
13194 as well.
13196 @item Invalid characters (@sc{lfn})
13197 Some characters are invalid in @acronym{DOS} file names, and should therefore
13198 be avoided.  In a @sc{lfn} environment, these are @samp{/}, @samp{\},
13199 @samp{?}, @samp{*}, @samp{:}, @samp{<}, @samp{>}, @samp{|} and @samp{"}.
13200 In a @sc{sfn} environment, other characters are also invalid.  These
13201 include @samp{+}, @samp{,}, @samp{[} and @samp{]}.
13203 @item Invalid names (@sc{lfn})
13204 Some @acronym{DOS} file names are reserved, and cause problems if you
13205 try to use files with those names.  These names include @file{CON},
13206 @file{AUX}, @file{COM1}, @file{COM2}, @file{COM3}, @file{COM4},
13207 @file{LPT1}, @file{LPT2}, @file{LPT3}, @file{NUL}, and @file{PRN}.
13208 File names are case insensitive, so even names like
13209 @file{aux/config.guess} are disallowed.
13211 @end table
13213 @node Shell Pattern Matching
13214 @section Shell Pattern Matching
13215 @cindex Shell pattern matching
13217 Nowadays portable patterns can use negated character classes like
13218 @samp{[!-aeiou]}.  The older syntax @samp{[^-aeiou]} is supported by
13219 some shells but not others; hence portable scripts should never use
13220 @samp{^} as the first character of a bracket pattern.
13222 Outside the C locale, patterns like @samp{[a-z]} are problematic since
13223 they may match characters that are not lower-case letters.
13225 @node Shell Substitutions
13226 @section Shell Substitutions
13227 @cindex Shell substitutions
13229 Contrary to a persistent urban legend, the Bourne shell does not
13230 systematically split variables and back-quoted expressions, in particular
13231 on the right-hand side of assignments and in the argument of @code{case}.
13232 For instance, the following code:
13234 @example
13235 case "$given_srcdir" in
13236 .)  top_srcdir="`echo "$dots" | sed 's|/$||'`" ;;
13237 *)  top_srcdir="$dots$given_srcdir" ;;
13238 esac
13239 @end example
13241 @noindent
13242 is more readable when written as:
13244 @example
13245 case $given_srcdir in
13246 .)  top_srcdir=`echo "$dots" | sed 's|/$||'` ;;
13247 *)  top_srcdir=$dots$given_srcdir ;;
13248 esac
13249 @end example
13251 @noindent
13252 and in fact it is even @emph{more} portable: in the first case of the
13253 first attempt, the computation of @code{top_srcdir} is not portable,
13254 since not all shells properly understand @code{"`@dots{}"@dots{}"@dots{}`"}.
13255 Worse yet, not all shells understand @code{"`@dots{}\"@dots{}\"@dots{}`"}
13256 the same way.  There is just no portable way to use double-quoted
13257 strings inside double-quoted back-quoted expressions (pfew!).
13259 @table @code
13260 @item $@@
13261 @cindex @samp{"$@@"}
13262 One of the most famous shell-portability issues is related to
13263 @samp{"$@@"}.  When there are no positional arguments, Posix says
13264 that @samp{"$@@"} is supposed to be equivalent to nothing, but the
13265 original Unix version 7 Bourne shell treated it as equivalent to
13266 @samp{""} instead, and this behavior survives in later implementations
13267 like Digital Unix 5.0.
13269 The traditional way to work around this portability problem is to use
13270 @samp{$@{1+"$@@"@}}.  Unfortunately this method does not work with
13271 Zsh (3.x and 4.x), which is used on Mac OS X@.  When emulating
13272 the Bourne shell, Zsh performs word splitting on @samp{$@{1+"$@@"@}}:
13274 @example
13275 zsh $ @kbd{emulate sh}
13276 zsh $ @kbd{for i in "$@@"; do echo $i; done}
13277 Hello World
13279 zsh $ @kbd{for i in $@{1+"$@@"@}; do echo $i; done}
13280 Hello
13281 World
13283 @end example
13285 @noindent
13286 Zsh handles plain @samp{"$@@"} properly, but we can't use plain
13287 @samp{"$@@"} because of the portability problems mentioned above.
13288 One workaround relies on Zsh's ``global aliases'' to convert
13289 @samp{$@{1+"$@@"@}} into @samp{"$@@"} by itself:
13291 @example
13292 test "$@{ZSH_VERSION+set@}" = set && alias -g '$@{1+"$@@"@}'='"$@@"'
13293 @end example
13295 Zsh only recognizes this alias when a shell word matches it exactly;
13296 @samp{"foo"$@{1+"$@@"@}} remains subject to word splitting.  Since this
13297 case always yields at least one shell word, use plain @samp{"$@@"}.
13299 A more conservative workaround is to avoid @samp{"$@@"} if it is
13300 possible that there may be no positional arguments.  For example,
13301 instead of:
13303 @example
13304 cat conftest.c "$@@"
13305 @end example
13307 you can use this instead:
13309 @example
13310 case $# in
13311 0) cat conftest.c;;
13312 *) cat conftest.c "$@@";;
13313 esac
13314 @end example
13316 Autoconf macros often use the @command{set} command to update
13317 @samp{$@@}, so if you are writing shell code intended for
13318 @command{configure} you should not assume that the value of @samp{$@@}
13319 persists for any length of time.
13322 @item $@{10@}
13323 @cindex positional parameters
13324 The 10th, 11th, @dots{} positional parameters can be accessed only after
13325 a @code{shift}.  The 7th Edition shell reported an error if given
13326 @code{$@{10@}}, and
13327 Solaris 10 @command{/bin/sh} still acts that way:
13329 @example
13330 $ @kbd{set 1 2 3 4 5 6 7 8 9 10}
13331 $ @kbd{echo $@{10@}}
13332 bad substitution
13333 @end example
13335 @item $@{@var{var}:-@var{value}@}
13336 @c Info cannot handle `:' in index entries.
13337 @c @cindex $@{@var{var}:-@var{value}@}
13338 Old @acronym{BSD} shells, including the Ultrix @code{sh}, don't accept the
13339 colon for any shell substitution, and complain and die.
13340 Similarly for $@{@var{var}:=@var{value}@}, $@{@var{var}:?@var{value}@}, etc.
13342 @item $@{@var{var}=@var{literal}@}
13343 @cindex $@{@var{var}=@var{literal}@}
13344 Be sure to quote:
13346 @example
13347 : $@{var='Some words'@}
13348 @end example
13350 @noindent
13351 otherwise some shells, such as on Digital Unix V 5.0, die because
13352 of a ``bad substitution''.
13354 @sp 1
13356 Solaris @command{/bin/sh} has a frightening bug in its interpretation
13357 of this.  Imagine you need set a variable to a string containing
13358 @samp{@}}.  This @samp{@}} character confuses Solaris @command{/bin/sh}
13359 when the affected variable was already set.  This bug can be exercised
13360 by running:
13362 @example
13363 $ @kbd{unset foo}
13364 $ @kbd{foo=$@{foo='@}'@}}
13365 $ @kbd{echo $foo}
13367 $ @kbd{foo=$@{foo='@}'   # no error; this hints to what the bug is}
13368 $ @kbd{echo $foo}
13370 $ @kbd{foo=$@{foo='@}'@}}
13371 $ @kbd{echo $foo}
13372 @}@}
13373  ^ ugh!
13374 @end example
13376 It seems that @samp{@}} is interpreted as matching @samp{$@{}, even
13377 though it is enclosed in single quotes.  The problem doesn't happen
13378 using double quotes.
13380 @item $@{@var{var}=@var{expanded-value}@}
13381 @cindex $@{@var{var}=@var{expanded-value}@}
13382 On Ultrix,
13383 running
13385 @example
13386 default="yu,yaa"
13387 : $@{var="$default"@}
13388 @end example
13390 @noindent
13391 sets @var{var} to @samp{M-yM-uM-,M-yM-aM-a}, i.e., the 8th bit of
13392 each char is set.  You don't observe the phenomenon using a simple
13393 @samp{echo $var} since apparently the shell resets the 8th bit when it
13394 expands $var.  Here are two means to make this shell confess its sins:
13396 @example
13397 $ @kbd{cat -v <<EOF
13398 $var
13399 EOF}
13400 @end example
13402 @noindent
13405 @example
13406 $ @kbd{set | grep '^var=' | cat -v}
13407 @end example
13409 One classic incarnation of this bug is:
13411 @example
13412 default="a b c"
13413 : $@{list="$default"@}
13414 for c in $list; do
13415   echo $c
13416 done
13417 @end example
13419 @noindent
13420 You'll get @samp{a b c} on a single line.  Why?  Because there are no
13421 spaces in @samp{$list}: there are @samp{M- }, i.e., spaces with the 8th
13422 bit set, hence no IFS splitting is performed!!!
13424 One piece of good news is that Ultrix works fine with @samp{:
13425 $@{list=$default@}}; i.e., if you @emph{don't} quote.  The bad news is
13426 then that @acronym{QNX} 4.25 then sets @var{list} to the @emph{last} item of
13427 @var{default}!
13429 The portable way out consists in using a double assignment, to switch
13430 the 8th bit twice on Ultrix:
13432 @example
13433 list=$@{list="$default"@}
13434 @end example
13436 @noindent
13437 @dots{}but beware of the @samp{@}} bug from Solaris (see above).  For safety,
13438 use:
13440 @example
13441 test "$@{var+set@}" = set || var=@var{@{value@}}
13442 @end example
13444 @item $@{#@var{var}@}
13445 @itemx $@{@var{var}%@var{word}@}
13446 @itemx $@{@var{var}%%@var{word}@}
13447 @itemx $@{@var{var}#@var{word}@}
13448 @itemx $@{@var{var}##@var{word}@}
13449 @cindex $@{#@var{var}@}
13450 @cindex $@{@var{var}%@var{word}@}
13451 @cindex $@{@var{var}%%@var{word}@}
13452 @cindex $@{@var{var}#@var{word}@}
13453 @cindex $@{@var{var}##@var{word}@}
13454 Posix requires support for these usages, but they do not work with many
13455 traditional shells, e.g., Solaris 10 @command{/bin/sh}.
13457 Also, @command{pdksh} 5.2.14 mishandles some @var{word} forms.  For
13458 example if @samp{$1} is @samp{a/b} and @samp{$2} is @samp{a}, then
13459 @samp{$@{1#$2@}} should yield @samp{/b}, but with @command{pdksh} it
13460 yields the empty string.
13463 @item `@var{commands}`
13464 @cindex `@var{commands}`
13465 @cindex Command Substitution
13466 Posix requires shells to trim all trailing newlines from command
13467 output before substituting it, so assignments like
13468 @samp{dir=`echo "$file" | tr a A`} do not work as expected if
13469 @samp{$file} ends in a newline.
13471 While in general it makes no sense, do not substitute a single builtin
13472 with side effects, because Ash 0.2, trying to optimize, does not fork a
13473 subshell to perform the command.
13475 For instance, if you wanted to check that @command{cd} is silent, do not
13476 use @samp{test -z "`cd /`"} because the following can happen:
13478 @example
13479 $ @kbd{pwd}
13480 /tmp
13481 $ @kbd{test -z "`cd /`" && pwd}
13483 @end example
13485 @noindent
13486 The result of @samp{foo=`exit 1`} is left as an exercise to the reader.
13488 The MSYS shell leaves a stray byte in the expansion of a double-quoted
13489 command substitution of a native program, if the end of the substitution
13490 is not aligned with the end of the double quote.  This may be worked
13491 around by inserting another pair of quotes:
13493 @example
13494 $ @kbd{echo "`printf 'foo\r\n'` bar" > broken}
13495 $ @kbd{echo "`printf 'foo\r\n'`"" bar" | cmp - broken}
13496 - broken differ: char 4, line 1
13497 @end example
13499 Upon interrupt or SIGTERM, some shells may abort a command substitution,
13500 replace it with a null string, and wrongly evaluate the enclosing
13501 command before entering the trap or ending the script.  This can lead to
13502 spurious errors:
13504 @example
13505 $ @kbd{sh -c 'if test `sleep 5; echo hi` = hi; then echo yes; fi'}
13506 $ @kbd{^C}
13507 sh: test: hi: unexpected operator/operand
13508 @end example
13510 @noindent
13511 You can avoid this by assigning the command substitution to a temporary
13512 variable:
13514 @example
13515 $ @kbd{sh -c 'res=`sleep 5; echo hi`
13516          if test "x$res" = xhi; then echo yes; fi'}
13517 $ @kbd{^C}
13518 @end example
13520 @item $(@var{commands})
13521 @cindex $(@var{commands})
13522 This construct is meant to replace @samp{`@var{commands}`},
13523 and it has most of the problems listed under @code{`@var{commands}`}.
13525 This construct can be
13526 nested while this is impossible to do portably with back quotes.
13527 Unfortunately it is not yet universally supported.  Most notably, even recent
13528 releases of Solaris don't support it:
13530 @example
13531 $ @kbd{showrev -c /bin/sh | grep version}
13532 Command version: SunOS 5.10 Generic 121005-03 Oct 2006
13533 $ @kbd{echo $(echo blah)}
13534 syntax error: `(' unexpected
13535 @end example
13537 @noindent
13538 nor does @sc{irix} 6.5's Bourne shell:
13539 @example
13540 $ @kbd{uname -a}
13541 IRIX firebird-image 6.5 07151432 IP22
13542 $ @kbd{echo $(echo blah)}
13543 $(echo blah)
13544 @end example
13546 If you do use @samp{$(@var{commands})}, make sure that the commands
13547 do not start with a parenthesis, as that would cause confusion with
13548 a different notation @samp{$((@var{expression}))} that in modern
13549 shells is an arithmetic expression not a command.  To avoid the
13550 confusion, insert a space between the two opening parentheses.
13552 Avoid @var{commands} that contain unbalanced parentheses in
13553 here-documents, comments, or case statement patterns, as many shells
13554 mishandle them.  For example, Bash 3.1, @samp{ksh88}, @command{pdksh}
13555 5.2.14, and Zsh 4.2.6 all mishandle the following valid command:
13557 @example
13558 echo $(case x in x) echo hello;; esac)
13559 @end example
13562 @item $((@var{expression}))
13563 @cindex $((@var{expression}))
13564 Arithmetic expansion is not portable as some shells (most
13565 notably Solaris 10 @command{/bin/sh}) don't support it.
13567 Among shells that do support @samp{$(( ))}, not all of them obey the
13568 Posix rule that octal and hexadecimal constants must be recognized:
13570 @example
13571 $ @kbd{bash -c 'echo $(( 010 + 0x10 ))'}
13573 $ @kbd{zsh -c 'echo $(( 010 + 0x10 ))'}
13575 $ @kbd{zsh -c 'emulate sh; echo $(( 010 + 0x10 ))'}
13577 $ @kbd{pdksh -c 'echo $(( 010 + 0x10 ))'}
13578 pdksh:  010 + 0x10 : bad number `0x10'
13579 $ @kbd{pdksh -c 'echo $(( 010 ))'}
13581 @end example
13583 When it is available, using arithmetic expansion provides a noticeable
13584 speedup in script execution; but testing for support requires
13585 @command{eval} to avoid syntax errors.  If shell function support has
13586 also been detected, then this construct can be used to assign @samp{foo}
13587 to an arithmetic result, provided all numeric arguments are provided in
13588 decimal and without a leading zero:
13590 @example
13591 if ( eval 'test $(( 1 + 1 )) = 2' ) 2>/dev/null; then
13592   eval 'func_arith ()
13593   @{
13594     func_arith_result=$(( $* ))
13595   @}'
13596 else
13597   func_arith ()
13598   @{
13599     func_arith_result=`expr "$@@"`
13600   @}
13602 func_arith 1 + 1
13603 foo=$func_arith_result
13604 @end example
13607 @item ^
13608 @cindex ^ quoting
13609 Always quote @samp{^}, otherwise traditional shells such as
13610 @command{/bin/sh} on Solaris 10 treat this like @samp{|}.
13612 @end table
13615 @node Assignments
13616 @section Assignments
13617 @cindex Shell assignments
13619 When setting several variables in a row, be aware that the order of the
13620 evaluation is undefined.  For instance @samp{foo=1 foo=2; echo $foo}
13621 gives @samp{1} with Solaris @command{/bin/sh}, but @samp{2} with Bash.
13622 You must use
13623 @samp{;} to enforce the order: @samp{foo=1; foo=2; echo $foo}.
13625 Don't rely on the following to find @file{subdir/program}:
13627 @example
13628 PATH=subdir$PATH_SEPARATOR$PATH program
13629 @end example
13631 @noindent
13632 as this does not work with Zsh 3.0.6.  Use something like this
13633 instead:
13635 @example
13636 (PATH=subdir$PATH_SEPARATOR$PATH; export PATH; exec program)
13637 @end example
13639 Don't rely on the exit status of an assignment: Ash 0.2 does not change
13640 the status and propagates that of the last statement:
13642 @example
13643 $ @kbd{false || foo=bar; echo $?}
13645 $ @kbd{false || foo=`:`; echo $?}
13647 @end example
13649 @noindent
13650 and to make things even worse, @acronym{QNX} 4.25 just sets the exit status
13651 to 0 in any case:
13653 @example
13654 $ @kbd{foo=`exit 1`; echo $?}
13656 @end example
13658 To assign default values, follow this algorithm:
13660 @enumerate
13661 @item
13662 If the default value is a literal and does not contain any closing
13663 brace, use:
13665 @example
13666 : $@{var='my literal'@}
13667 @end example
13669 @item
13670 If the default value contains no closing brace, has to be expanded, and
13671 the variable being initialized is not intended to be IFS-split
13672 (i.e., it's not a list), then use:
13674 @example
13675 : $@{var="$default"@}
13676 @end example
13678 @item
13679 If the default value contains no closing brace, has to be expanded, and
13680 the variable being initialized is intended to be IFS-split (i.e., it's a list),
13681 then use:
13683 @example
13684 var=$@{var="$default"@}
13685 @end example
13687 @item
13688 If the default value contains a closing brace, then use:
13690 @example
13691 test "$@{var+set@}" = set || var="has a '@}'"
13692 @end example
13693 @end enumerate
13695 In most cases @samp{var=$@{var="$default"@}} is fine, but in case of
13696 doubt, just use the last form.  @xref{Shell Substitutions}, items
13697 @samp{$@{@var{var}:-@var{value}@}} and @samp{$@{@var{var}=@var{value}@}}
13698 for the rationale.
13700 @node Parentheses
13701 @section Parentheses in Shell Scripts
13702 @cindex Shell parentheses
13704 Beware of two opening parentheses in a row, as many shell
13705 implementations treat them specially.  Posix requires that the command
13706 @samp{((cat))} must behave like @samp{(cat)}, but many shells, including
13707 Bash and the Korn shell, treat @samp{((cat))} as an arithmetic
13708 expression equivalent to @samp{let "cat"}, and may or may not report an
13709 error when they detect that @samp{cat} is not a number.  As another
13710 example, @samp{pdksh} 5.2.14 misparses the following code:
13712 @example
13713 if ((true) || false); then
13714   echo ok
13716 @end example
13718 @noindent
13719 To work around this problem, insert a space between the two opening
13720 parentheses.  There is a similar problem and workaround with
13721 @samp{$((}; see @ref{Shell Substitutions}.
13723 @node Slashes
13724 @section Slashes in Shell Scripts
13725 @cindex Shell slashes
13727 Unpatched Tru64 5.1 @command{sh} omits the last slash of command-line
13728 arguments that contain two trailing slashes:
13730 @example
13731 $ @kbd{echo / // /// //// .// //.}
13732 / / // /// ./ //.
13733 $ @kbd{x=//}
13734 $ @kbd{eval "echo \$x"}
13736 $ @kbd{set -x}
13737 $ @kbd{echo abc | tr -t ab //}
13738 + echo abc
13739 + tr -t ab /
13741 @end example
13743 Unpatched Tru64 4.0 @command{sh} adds a slash after @samp{"$var"} if the
13744 variable is empty and the second double-quote is followed by a word that
13745 begins and ends with slash:
13747 @example
13748 $ @kbd{sh -xc 'p=; echo "$p"/ouch/'}
13750 + echo //ouch/
13751 //ouch/
13752 @end example
13754 However, our understanding is that patches are available, so perhaps
13755 it's not worth worrying about working around these horrendous bugs.
13757 @node Special Shell Variables
13758 @section Special Shell Variables
13759 @cindex Shell variables
13760 @cindex Special shell variables
13762 Some shell variables should not be used, since they can have a deep
13763 influence on the behavior of the shell.  In order to recover a sane
13764 behavior from the shell, some variables should be unset, but
13765 @command{unset} is not portable (@pxref{Limitations of Builtins}) and a
13766 fallback value is needed.
13768 As a general rule, shell variable names containing a lower-case letter
13769 are safe; you can define and use these variables without worrying about
13770 their effect on the underlying system, and without worrying about
13771 whether the shell changes them unexpectedly.  (The exception is the
13772 shell variable @code{status}, as described below.)
13774 Here is a list of names that are known to cause trouble.  This list is
13775 not exhaustive, but you should be safe if you avoid the name
13776 @code{status} and names containing only upper-case letters and
13777 underscores.
13779 @c Alphabetical order, case insensitive, `A' before `a'.
13780 @table @code
13781 @item _
13782 Many shells reserve @samp{$_} for various purposes, e.g., the name of
13783 the last command executed.
13785 @item BIN_SH
13786 @evindex BIN_SH
13787 In Tru64, if @env{BIN_SH} is set to @code{xpg4}, subsidiary invocations of
13788 the standard shell conform to Posix.
13790 @item CDPATH
13791 @evindex CDPATH
13792 When this variable is set it specifies a list of directories to search
13793 when invoking @code{cd} with a relative file name that did not start
13794 with @samp{./} or @samp{../}.  Posix
13795 1003.1-2001 says that if a nonempty directory name from @env{CDPATH}
13796 is used successfully, @code{cd} prints the resulting absolute
13797 file name.  Unfortunately this output can break idioms like
13798 @samp{abs=`cd src && pwd`} because @code{abs} receives the name twice.
13799 Also, many shells do not conform to this part of Posix; for
13800 example, @command{zsh} prints the result only if a directory name
13801 other than @file{.} was chosen from @env{CDPATH}.
13803 In practice the shells that have this problem also support
13804 @command{unset}, so you can work around the problem as follows:
13806 @example
13807 (unset CDPATH) >/dev/null 2>&1 && unset CDPATH
13808 @end example
13810 You can also avoid output by ensuring that your directory name is
13811 absolute or anchored at @samp{./}, as in @samp{abs=`cd ./src && pwd`}.
13813 Autoconf-generated scripts automatically unset @env{CDPATH} if
13814 possible, so you need not worry about this problem in those scripts.
13816 @item DUALCASE
13817 @evindex DUALCASE
13818 In the MKS shell, case statements and file name generation are
13819 case-insensitive unless @env{DUALCASE} is nonzero.
13820 Autoconf-generated scripts export this variable when they start up.
13822 @item ENV
13823 @itemx MAIL
13824 @itemx MAILPATH
13825 @itemx PS1
13826 @itemx PS2
13827 @itemx PS4
13828 @evindex ENV
13829 @evindex MAIL
13830 @evindex MAILPATH
13831 @evindex PS1
13832 @evindex PS2
13833 @evindex PS4
13834 These variables should not matter for shell scripts, since they are
13835 supposed to affect only interactive shells.  However, at least one
13836 shell (the pre-3.0 @sc{uwin} Korn shell) gets confused about
13837 whether it is interactive, which means that (for example) a @env{PS1}
13838 with a side effect can unexpectedly modify @samp{$?}.  To work around
13839 this bug, Autoconf-generated scripts do something like this:
13841 @example
13842 (unset ENV) >/dev/null 2>&1 && unset ENV MAIL MAILPATH
13843 PS1='$ '
13844 PS2='> '
13845 PS4='+ '
13846 @end example
13848 @item FPATH
13849 The Korn shell uses @env{FPATH} to find shell functions, so avoid
13850 @env{FPATH} in portable scripts.  @env{FPATH} is consulted after
13851 @env{PATH}, but you still need to be wary of tests that use @env{PATH}
13852 to find whether a command exists, since they might report the wrong
13853 result if @env{FPATH} is also set.
13855 @item IFS
13856 @evindex IFS
13857 Long ago, shell scripts inherited @env{IFS} from the environment,
13858 but this caused many problems so modern shells ignore any environment
13859 settings for @env{IFS}.
13861 Don't set the first character of @code{IFS} to backslash.  Indeed,
13862 Bourne shells use the first character (backslash) when joining the
13863 components in @samp{"$@@"} and some shells then reinterpret (!)@: the
13864 backslash escapes, so you can end up with backspace and other strange
13865 characters.
13867 The proper value for @code{IFS} (in regular code, not when performing
13868 splits) is @samp{@key{SPC}@key{TAB}@key{RET}}.  The first character is
13869 especially important, as it is used to join the arguments in @samp{$*};
13870 however, note that traditional shells, but also bash-2.04, fail to adhere
13871 to this and join with a space anyway.
13873 @item LANG
13874 @itemx LC_ALL
13875 @itemx LC_COLLATE
13876 @itemx LC_CTYPE
13877 @itemx LC_MESSAGES
13878 @itemx LC_MONETARY
13879 @itemx LC_NUMERIC
13880 @itemx LC_TIME
13881 @evindex LANG
13882 @evindex LC_ALL
13883 @evindex LC_COLLATE
13884 @evindex LC_CTYPE
13885 @evindex LC_MESSAGES
13886 @evindex LC_MONETARY
13887 @evindex LC_NUMERIC
13888 @evindex LC_TIME
13890 Autoconf-generated scripts normally set all these variables to
13891 @samp{C} because so much configuration code assumes the C locale and
13892 Posix requires that locale environment variables be set to
13893 @samp{C} if the C locale is desired.  However, some older, nonstandard
13894 systems (notably @acronym{SCO}) break if locale environment variables
13895 are set to @samp{C}, so when running on these systems
13896 Autoconf-generated scripts unset the variables instead.
13898 @item LANGUAGE
13899 @evindex LANGUAGE
13901 @env{LANGUAGE} is not specified by Posix, but it is a @acronym{GNU}
13902 extension that overrides @env{LC_ALL} in some cases, so
13903 Autoconf-generated scripts set it too.
13905 @item LC_ADDRESS
13906 @itemx LC_IDENTIFICATION
13907 @itemx LC_MEASUREMENT
13908 @itemx LC_NAME
13909 @itemx LC_PAPER
13910 @itemx LC_TELEPHONE
13911 @evindex LC_ADDRESS
13912 @evindex LC_IDENTIFICATION
13913 @evindex LC_MEASUREMENT
13914 @evindex LC_NAME
13915 @evindex LC_PAPER
13916 @evindex LC_TELEPHONE
13918 These locale environment variables are @acronym{GNU} extensions.  They
13919 are treated like their Posix brethren (@env{LC_COLLATE},
13920 etc.)@: as described above.
13922 @item LINENO
13923 Most modern shells provide the current line number in @code{LINENO}.
13924 Its value is the line number of the beginning of the current command.
13925 Autoconf attempts to execute @command{configure} with a shell that
13926 supports @code{LINENO}.
13927 If no such shell is available, it attempts to implement @code{LINENO}
13928 with a Sed prepass that replaces each instance of the string
13929 @code{$LINENO} (not followed by an alphanumeric character) with the
13930 line's number.
13932 You should not rely on @code{LINENO} within @command{eval}, as the
13933 behavior differs in practice.  Also, the possibility of the Sed
13934 prepass means that you should not rely on @code{$LINENO} when quoted,
13935 when in here-documents, or when in long commands that cross line
13936 boundaries.  Subshells should be OK, though.  In the following
13937 example, lines 1, 6, and 9 are portable, but the other instances of
13938 @code{LINENO} are not:
13940 @example
13941 @group
13942 $ @kbd{cat lineno}
13943 echo 1. $LINENO
13944 cat <<EOF
13945 3. $LINENO
13946 4. $LINENO
13948 ( echo 6. $LINENO )
13949 eval 'echo 7. $LINENO'
13950 echo 8. '$LINENO'
13951 echo 9. $LINENO '
13952 10.' $LINENO
13953 @end group
13954 @group
13955 $ @kbd{bash-2.05 lineno}
13956 1. 1
13957 3. 2
13958 4. 2
13959 6. 6
13960 7. 1
13961 8. $LINENO
13962 9. 9
13963 10. 9
13964 @end group
13965 @group
13966 $ @kbd{zsh-3.0.6 lineno}
13967 1. 1
13968 3. 2
13969 4. 2
13970 6. 6
13971 7. 7
13972 8. $LINENO
13973 9. 9
13974 10. 9
13975 @end group
13976 @group
13977 $ @kbd{pdksh-5.2.14 lineno}
13978 1. 1
13979 3. 2
13980 4. 2
13981 6. 6
13982 7. 0
13983 8. $LINENO
13984 9. 9
13985 10. 9
13986 @end group
13987 @group
13988 $ @kbd{sed '=' <lineno |}
13989 > @kbd{  sed '}
13990 > @kbd{    N}
13991 > @kbd{    s,$,-,}
13992 > @kbd{    t loop}
13993 > @kbd{    :loop}
13994 > @kbd{    s,^\([0-9]*\)\(.*\)[$]LINENO\([^a-zA-Z0-9_]\),\1\2\1\3,}
13995 > @kbd{    t loop}
13996 > @kbd{    s,-$,,}
13997 > @kbd{    s,^[0-9]*\n,,}
13998 > @kbd{  ' |}
13999 > @kbd{  sh}
14000 1. 1
14001 3. 3
14002 4. 4
14003 6. 6
14004 7. 7
14005 8. 8
14006 9. 9
14007 10. 10
14008 @end group
14009 @end example
14011 @item NULLCMD
14012 @evindex NULLCMD
14013 When executing the command @samp{>foo}, @command{zsh} executes
14014 @samp{$NULLCMD >foo} unless it is operating in Bourne shell
14015 compatibility mode and the @command{zsh} version is newer
14016 than 3.1.6-dev-18.  If you are using an older @command{zsh}
14017 and forget to set @env{NULLCMD},
14018 your script might be suspended waiting for data on its standard input.
14020 @item PATH_SEPARATOR
14021 @evindex PATH_SEPARATOR
14022 On @acronym{DJGPP} systems, the @env{PATH_SEPARATOR} environment
14023 variable can be set to either @samp{:} or @samp{;} to control the path
14024 separator Bash uses to set up certain environment variables (such as
14025 @env{PATH}).  You can set this variable to @samp{;} if you want
14026 @command{configure} to use @samp{;} as a separator; this might be useful
14027 if you plan to use non-Posix shells to execute files.  @xref{File System
14028 Conventions}, for more information about @code{PATH_SEPARATOR}.
14030 @item PWD
14031 @evindex PWD
14032 Posix 1003.1-2001 requires that @command{cd} and
14033 @command{pwd} must update the @env{PWD} environment variable to point
14034 to the logical name of the current directory, but traditional shells
14035 do not support this.  This can cause confusion if one shell instance
14036 maintains @env{PWD} but a subsidiary and different shell does not know
14037 about @env{PWD} and executes @command{cd}; in this case @env{PWD}
14038 points to the wrong directory.  Use @samp{`pwd`} rather than
14039 @samp{$PWD}.
14041 @item RANDOM
14042 Many shells provide @code{RANDOM}, a variable that returns a different
14043 integer each time it is used.  Most of the time, its value does not
14044 change when it is not used, but on @sc{irix} 6.5 the value changes all
14045 the time.  This can be observed by using @command{set}.  It is common
14046 practice to use @code{$RANDOM} as part of a file name, but code
14047 shouldn't rely on @code{$RANDOM} expanding to a nonempty string.
14049 @item status
14050 This variable is an alias to @samp{$?} for @code{zsh} (at least 3.1.6),
14051 hence read-only.  Do not use it.
14052 @end table
14054 @node Shell Functions
14055 @section Shell Functions
14056 @cindex Shell Functions
14058 Nowadays, it is difficult to find a shell that does not support
14059 shell functions at all.  However, some differences should be expected:
14061 Inside a shell function, you should not rely on the error status of a
14062 subshell if the last command of that subshell was @code{exit} or
14063 @code{trap}, as this triggers bugs in zsh 4.x; while Autoconf tries to
14064 find a shell that does not exhibit the bug, zsh might be the only shell
14065 present on the user's machine.
14067 Likewise, the state of @samp{$?} is not reliable when entering a shell
14068 function.  This has the effect that using a function as the first
14069 command in a @command{trap} handler can cause problems.
14071 @example
14072 $ @kbd{bash -c 'foo()@{ echo $?; @}; trap foo 0; (exit 2); exit 2'; echo $?}
14075 $ @kbd{ash -c 'foo()@{ echo $?; @}; trap foo 0; (exit 2); exit 2'; echo $?}
14078 @end example
14080 Shell variables and functions may share the same namespace, for example
14081 with Solaris 10 @command{/bin/sh}:
14083 @example
14084 $ @kbd{f () @{ :; @}; f=; f}
14085 f: not found
14086 @end example
14088 @noindent
14089 For this reason, Autotest uses the prefix @samp{at_func_} for its
14090 functions.
14092 Handling of positional parameters and shell options varies among shells.
14093 For example, Korn shells reset and restore trace output (@samp{set -x})
14094 and other options upon function entry and exit.  Inside a function,
14095 @acronym{IRIX} sh sets @samp{$0} to the function name.
14097 Some ancient Bourne shell variants with function support did not reset
14098 @samp{$@var{i}, @var{i} >= 0}, upon function exit, so effectively the
14099 arguments of the script were lost after the first function invocation.
14100 It is probably not worth worrying about these shells any more.
14102 With @acronym{AIX} sh, a @command{trap} on 0 installed in a shell function
14103 triggers at function exit rather than at script exit, see @xref{Limitations
14104 of Builtins}.
14106 @node Limitations of Builtins
14107 @section Limitations of Shell Builtins
14108 @cindex Shell builtins
14109 @cindex Limitations of shell builtins
14111 No, no, we are serious: some shells do have limitations!  :)
14113 You should always keep in mind that any builtin or command may support
14114 options, and therefore differ in behavior with arguments
14115 starting with a dash.  For instance, the innocent @samp{echo "$word"}
14116 can give unexpected results when @code{word} starts with a dash.  It is
14117 often possible to avoid this problem using @samp{echo "x$word"}, taking
14118 the @samp{x} into account later in the pipe.
14120 @table @asis
14121 @item @command{.}
14122 @c --------------
14123 @prindex @command{.}
14124 Use @command{.} only with regular files (use @samp{test -f}).  Bash
14125 2.03, for instance, chokes on @samp{. /dev/null}.  Remember that
14126 @command{.} uses @env{PATH} if its argument contains no slashes.  Also,
14127 some shells, including bash 3.2, implicitly append the current directory
14128 to this @env{PATH} search, even though Posix forbids it.  So if you want
14129 to use @command{.} on a file @file{foo} in the current directory, you
14130 must use @samp{. ./foo}.
14132 @item @command{!}
14133 @c --------------
14134 @prindex @command{!}
14135 The Unix version 7 shell did not support
14136 negating the exit status of commands with @command{!}, and this feature
14137 is still absent from some shells (e.g., Solaris @command{/bin/sh}).
14138 Other shells, such as FreeBSD @command{/bin/sh} or @command{ash}, have
14139 bugs when using @command{!}:
14141 @example
14142 $ @kbd{sh -c '! : | :'; echo $?}
14144 $ @kbd{ash -c '! : | :'; echo $?}
14146 $ @kbd{sh -c '! @{ :; @}'; echo $?}
14148 $ @kbd{ash -c '! @{ :; @}'; echo $?}
14149 @{: not found
14150 Syntax error: "@}" unexpected
14152 @end example
14154 Shell code like this:
14156 @example
14157 if ! cmp file1 file2 >/dev/null 2>&1; then
14158   echo files differ or trouble
14160 @end example
14162 is therefore not portable in practice.  Typically it is easy to rewrite
14163 such code, e.g.:
14165 @example
14166 cmp file1 file2 >/dev/null 2>&1 ||
14167   echo files differ or trouble
14168 @end example
14170 More generally, one can always rewrite @samp{! @var{command}} as:
14172 @example
14173 if @var{command}; then (exit 1); else :; fi
14174 @end example
14177 @item @command{@{...@}}
14178 @c --------------------
14179 @prindex @command{@{...@}}
14180 Bash 3.2 (and earlier versions) sometimes does not properly set
14181 @samp{$?} when failing to write redirected output of a compound command.
14182 This problem is most commonly observed with @samp{@{@dots{}@}}; it does
14183 not occur with @samp{(@dots{})}.  For example:
14185 @example
14186 $ @kbd{bash -c '@{ echo foo; @} >/bad; echo $?'}
14187 bash: line 1: /bad: Permission denied
14189 $ @kbd{bash -c 'while :; do echo; done >/bad; echo $?'}
14190 bash: line 1: /bad: Permission denied
14192 @end example
14194 To work around the bug, prepend @samp{:;}:
14196 @example
14197 $ @kbd{bash -c ':;@{ echo foo; @} >/bad; echo $?'}
14198 bash: line 1: /bad: Permission denied
14200 @end example
14203 @item @command{break}
14204 @c ------------------
14205 @prindex @command{break}
14206 The use of @samp{break 2} etc.@: is safe.
14209 @item @command{case}
14210 @c -----------------
14211 @prindex @command{case}
14212 You don't need to quote the argument; no splitting is performed.
14214 You don't need the final @samp{;;}, but you should use it.
14216 Posix requires support for @code{case} patterns with opening
14217 parentheses like this:
14219 @example
14220 case $file_name in
14221   (*.c) echo "C source code";;
14222 esac
14223 @end example
14225 @noindent
14226 but the @code{(} in this example is not portable to many Bourne
14227 shell implementations, which is a pity for those of us using tools that
14228 rely on balanced parentheses.  For instance, with Solaris
14229 @command{/bin/sh}:
14231 @example
14232 $ @kbd{case foo in (foo) echo foo;; esac}
14233 @error{}syntax error: `(' unexpected
14234 @end example
14236 @noindent
14237 The leading @samp{(} can be omitted safely.  In contexts where
14238 unbalanced parentheses cause other problems, such as when using a case
14239 statement as an argument to an Autoconf macro, you can also resort to
14240 creative shell comments to supply the balance:
14242 @example
14243 case $file_name in #(
14244   *.c) echo "C source code";;
14245 esac
14246 @end example
14248 Zsh handles pattern fragments derived from parameter expansions or
14249 command substitutions as though quoted:
14251 @example
14252 $ pat=\?; case aa in ?$pat) echo match;; esac
14253 $ pat=\?; case a? in ?$pat) echo match;; esac
14254 match
14255 @end example
14257 @noindent
14258 Because of a bug in its @code{fnmatch}, Bash fails to properly
14259 handle backslashes in character classes:
14261 @example
14262 bash-2.02$ @kbd{case /tmp in [/\\]*) echo OK;; esac}
14263 bash-2.02$
14264 @end example
14266 @noindent
14267 This is extremely unfortunate, since you are likely to use this code to
14268 handle Posix or @sc{ms-dos} absolute file names.  To work around this
14269 bug, always put the backslash first:
14271 @example
14272 bash-2.02$ @kbd{case '\TMP' in [\\/]*) echo OK;; esac}
14274 bash-2.02$ @kbd{case /tmp in [\\/]*) echo OK;; esac}
14276 @end example
14278 Many Bourne shells cannot handle closing brackets in character classes
14279 correctly.
14281 Some shells also have problems with backslash escaping in case you do not want
14282 to match the backslash: both a backslash and the escaped character match this
14283 pattern.  To work around this, specify the character class in a variable, so
14284 that quote removal does not apply afterwards, and the special characters don't
14285 have to be backslash-escaped:
14287 @example
14288 $ @kbd{case '\' in [\<]) echo OK;; esac}
14290 $ @kbd{scanset='[<]'; case '\' in $scanset) echo OK;; esac}
14292 @end example
14294 Even with this, Solaris @command{ksh} matches a backslash if the set
14295 contains any
14296 of the characters @samp{|}, @samp{&}, @samp{(}, or @samp{)}.
14298 Conversely, Tru64 @command{ksh} (circa 2003) erroneously always matches
14299 a closing parenthesis if not specified in a character class:
14301 @example
14302 $ @kbd{case foo in *\)*) echo fail ;; esac}
14303 fail
14304 $ @kbd{case foo in *')'*) echo fail ;; esac}
14305 fail
14306 @end example
14308 Some shells, such as Ash 0.3.8, are confused by an empty
14309 @code{case}/@code{esac}:
14311 @example
14312 ash-0.3.8 $ @kbd{case foo in esac;}
14313 @error{}Syntax error: ";" unexpected (expecting ")")
14314 @end example
14317 @item @command{cd}
14318 @c ---------------
14319 @prindex @command{cd}
14320 Posix 1003.1-2001 requires that @command{cd} must support
14321 the @option{-L} (``logical'') and @option{-P} (``physical'') options,
14322 with @option{-L} being the default.  However, traditional shells do
14323 not support these options, and their @command{cd} command has the
14324 @option{-P} behavior.
14326 Portable scripts should assume neither option is supported, and should
14327 assume neither behavior is the default.  This can be a bit tricky,
14328 since the Posix default behavior means that, for example,
14329 @samp{ls ..} and @samp{cd ..} may refer to different directories if
14330 the current logical directory is a symbolic link.  It is safe to use
14331 @code{cd @var{dir}} if @var{dir} contains no @file{..} components.
14332 Also, Autoconf-generated scripts check for this problem when computing
14333 variables like @code{ac_top_srcdir} (@pxref{Configuration Actions}),
14334 so it is safe to @command{cd} to these variables.
14336 See @xref{Special Shell Variables}, for portability problems involving
14337 @command{cd} and the @env{CDPATH} environment variable.
14338 Also please see the discussion of the @command{pwd} command.
14341 @item @command{echo}
14342 @c -----------------
14343 @prindex @command{echo}
14344 The simple @command{echo} is probably the most surprising source of
14345 portability troubles.  It is not possible to use @samp{echo} portably
14346 unless both options and escape sequences are omitted.  New applications
14347 which are not aiming at portability should use @samp{printf} instead of
14348 @samp{echo}.
14350 Don't expect any option.  @xref{Preset Output Variables}, @code{ECHO_N}
14351 etc.@: for a means to simulate @option{-n}.
14353 Do not use backslashes in the arguments, as there is no consensus on
14354 their handling.  For @samp{echo '\n' | wc -l}, the @command{sh} of
14355 Solaris outputs 2, but Bash and Zsh (in @command{sh} emulation mode) output 1.
14356 The problem is truly @command{echo}: all the shells
14357 understand @samp{'\n'} as the string composed of a backslash and an
14358 @samp{n}.
14360 Because of these problems, do not pass a string containing arbitrary
14361 characters to @command{echo}.  For example, @samp{echo "$foo"} is safe
14362 if you know that @var{foo}'s value cannot contain backslashes and cannot
14363 start with @samp{-}, but otherwise you should use a here-document like
14364 this:
14366 @example
14367 cat <<EOF
14368 $foo
14370 @end example
14373 @item @command{eval}
14374 @c -----------------
14375 @prindex @command{eval}
14376 The @command{eval} command is useful in limited circumstances, e.g.,
14377 using commands like @samp{eval table_$key=\$value} and @samp{eval
14378 value=table_$key} to simulate a hash table when the key is known to be
14379 alphanumeric.  However, @command{eval} is tricky to use on arbitrary
14380 arguments, even when it is implemented correctly.
14382 It is obviously unwise to use @samp{eval $cmd} if the string value of
14383 @samp{cmd} was derived from an untrustworthy source.  But even if the
14384 string value is valid, @samp{eval $cmd} might not work as intended,
14385 since it causes field splitting and file name expansion to occur twice,
14386 once for the @command{eval} and once for the command itself.  It is
14387 therefore safer to use @samp{eval "$cmd"}.  For example, if @var{cmd}
14388 has the value @samp{cat test?.c}, @samp{eval $cmd} might expand to the
14389 equivalent of @samp{cat test;.c} if there happens to be a file named
14390 @file{test;.c} in the current directory; and this in turn
14391 mistakenly attempts to invoke @command{cat} on the file @file{test} and
14392 then execute the command @command{.c}.  To avoid this problem, use
14393 @samp{eval "$cmd"} rather than @samp{eval $cmd}.
14395 However, suppose that you want to output the text of the evaluated
14396 command just before executing it.  Assuming the previous example,
14397 @samp{echo "Executing: $cmd"} outputs @samp{Executing: cat test?.c}, but
14398 this output doesn't show the user that @samp{test;.c} is the actual name
14399 of the copied file.  Conversely, @samp{eval "echo Executing: $cmd"}
14400 works on this example, but it fails with @samp{cmd='cat foo >bar'},
14401 since it mistakenly replaces the contents of @file{bar} by the
14402 string @samp{cat foo}.  No simple, general, and portable solution to
14403 this problem is known.
14405 You should also be wary of common bugs in @command{eval} implementations.
14406 In some shell implementations (e.g., older @command{ash}, Open@acronym{BSD} 3.8
14407 @command{sh}, @command{pdksh} v5.2.14 99/07/13.2, and @command{zsh}
14408 4.2.5), the arguments of @samp{eval} are evaluated in a context where
14409 @samp{$?} is 0, so they exhibit behavior like this:
14411 @example
14412 $ @kbd{false; eval 'echo $?'}
14414 @end example
14416 The correct behavior here is to output a nonzero value,
14417 but portable scripts should not rely on this.
14419 You should not rely on @code{LINENO} within @command{eval}.
14420 @xref{Special Shell Variables}.
14422 @item @command{exec}
14423 @c -----------------
14424 @prindex @command{exec}
14425 Posix describes several categories of shell built-ins.  Special
14426 built-ins (such as @command{exit}) must impact the environment of the
14427 current shell, and need not be available through @command{exec}.  All
14428 other built-ins are regular, and must not propagate variable assignments
14429 to the environment of the current shell.  However, the group of regular
14430 built-ins is further distinguished by commands that do not require a
14431 @env{PATH} search (such as @command{cd}), in contrast to built-ins that
14432 are offered as a more efficient version of something that must still be
14433 found in a @env{PATH} search (such as @command{echo}).  Posix is not
14434 clear on whether @command{exec} must work with the list of 17 utilities
14435 that are invoked without a @env{PATH} search, and many platforms lack an
14436 executable for some of those built-ins:
14438 @example
14439 $ @kbd{sh -c 'exec cd /tmp'}
14440 sh: line 0: exec: cd: not found
14441 @end example
14443 All other built-ins that provide utilities specified by Posix must have
14444 a counterpart executable that exists on @env{PATH}, although Posix
14445 allows @command{exec} to use the built-in instead of the executable.
14446 For example, contrast @command{bash} 3.2 and @command{pdksh} 5.2.14:
14448 @example
14449 $ @kbd{bash -c 'pwd --version' | head -n1}
14450 bash: line 0: pwd: --: invalid option
14451 pwd: usage: pwd [-LP]
14452 $ @kbd{bash -c 'exec pwd --version' | head -n1}
14453 pwd (GNU coreutils) 6.10
14454 $ @kbd{pdksh -c 'exec pwd --version' | head -n1}
14455 pdksh: pwd: --: unknown option
14456 @end example
14458 When it is desired to avoid a regular shell built-in, the workaround is
14459 to use some other forwarding command, such as @command{env} or
14460 @command{nice}, that will ensure a path search:
14462 @example
14463 $ @kbd{pdksh -c 'exec true --version' | head -n1}
14464 $ @kbd{pdksh -c 'nice true --version' | head -n1}
14465 true (GNU coreutils) 6.10
14466 $ @kbd{pdksh -c 'env true --version' | head -n1}
14467 true (GNU coreutils) 6.10
14468 @end example
14470 @item @command{exit}
14471 @c -----------------
14472 @prindex @command{exit}
14473 The default value of @command{exit} is supposed to be @code{$?};
14474 unfortunately, some shells, such as the @acronym{DJGPP} port of Bash 2.04, just
14475 perform @samp{exit 0}.
14477 @example
14478 bash-2.04$ @kbd{foo=`exit 1` || echo fail}
14479 fail
14480 bash-2.04$ @kbd{foo=`(exit 1)` || echo fail}
14481 fail
14482 bash-2.04$ @kbd{foo=`(exit 1); exit` || echo fail}
14483 bash-2.04$
14484 @end example
14486 Using @samp{exit $?} restores the expected behavior.
14488 Some shell scripts, such as those generated by @command{autoconf}, use a
14489 trap to clean up before exiting.  If the last shell command exited with
14490 nonzero status, the trap also exits with nonzero status so that the
14491 invoker can tell that an error occurred.
14493 Unfortunately, in some shells, such as Solaris @command{/bin/sh}, an exit
14494 trap ignores the @code{exit} command's argument.  In these shells, a trap
14495 cannot determine whether it was invoked by plain @code{exit} or by
14496 @code{exit 1}.  Instead of calling @code{exit} directly, use the
14497 @code{AC_MSG_ERROR} macro that has a workaround for this problem.
14500 @item @command{export}
14501 @c -------------------
14502 @prindex @command{export}
14503 The builtin @command{export} dubs a shell variable @dfn{environment
14504 variable}.  Each update of exported variables corresponds to an update
14505 of the environment variables.  Conversely, each environment variable
14506 received by the shell when it is launched should be imported as a shell
14507 variable marked as exported.
14509 Alas, many shells, such as Solaris @command{/bin/sh},
14510 @sc{irix} 6.3, @sc{irix} 5.2,
14511 @acronym{AIX} 4.1.5, and Digital Unix 4.0, forget to
14512 @command{export} the environment variables they receive.  As a result,
14513 two variables coexist: the environment variable and the shell
14514 variable.  The following code demonstrates this failure:
14516 @example
14517 #!/bin/sh
14518 echo $FOO
14519 FOO=bar
14520 echo $FOO
14521 exec /bin/sh $0
14522 @end example
14524 @noindent
14525 when run with @samp{FOO=foo} in the environment, these shells print
14526 alternately @samp{foo} and @samp{bar}, although they should print only
14527 @samp{foo} and then a sequence of @samp{bar}s.
14529 Therefore you should @command{export} again each environment variable
14530 that you update; the export can occur before or after the assignment.
14532 Posix is not clear on whether the @command{export} of an undefined
14533 variable causes the variable to be defined with the value of an empty
14534 string, or merely marks any future definition of a variable by that name
14535 for export.  Various shells behave differently in this regard:
14537 @example
14538 $ @kbd{sh -c 'export foo; env | grep foo'}
14539 $ @kbd{ash -c 'export foo; env | grep foo'}
14540 foo=
14541 @end example
14543 @item @command{false}
14544 @c ------------------
14545 @prindex @command{false}
14546 Don't expect @command{false} to exit with status 1: in native
14547 Solaris @file{/bin/false} exits with status 255.
14550 @item @command{for}
14551 @c ----------------
14552 @prindex @command{for}
14553 To loop over positional arguments, use:
14555 @example
14556 for arg
14558   echo "$arg"
14559 done
14560 @end example
14562 @noindent
14563 You may @emph{not} leave the @code{do} on the same line as @code{for},
14564 since some shells improperly grok:
14566 @example
14567 for arg; do
14568   echo "$arg"
14569 done
14570 @end example
14572 If you want to explicitly refer to the positional arguments, given the
14573 @samp{$@@} bug (@pxref{Shell Substitutions}), use:
14575 @example
14576 for arg in $@{1+"$@@"@}; do
14577   echo "$arg"
14578 done
14579 @end example
14581 @noindent
14582 But keep in mind that Zsh, even in Bourne shell emulation mode, performs
14583 word splitting on @samp{$@{1+"$@@"@}}; see @ref{Shell Substitutions},
14584 item @samp{$@@}, for more.
14587 @item @command{if}
14588 @c ---------------
14589 @prindex @command{if}
14590 Using @samp{!} is not portable.  Instead of:
14592 @example
14593 if ! cmp -s file file.new; then
14594   mv file.new file
14596 @end example
14598 @noindent
14599 use:
14601 @example
14602 if cmp -s file file.new; then :; else
14603   mv file.new file
14605 @end example
14607 There are shells that do not reset the exit status from an @command{if}:
14609 @example
14610 $ @kbd{if (exit 42); then true; fi; echo $?}
14612 @end example
14614 @noindent
14615 whereas a proper shell should have printed @samp{0}.  This is especially
14616 bad in makefiles since it produces false failures.  This is why properly
14617 written makefiles, such as Automake's, have such hairy constructs:
14619 @example
14620 if test -f "$file"; then
14621   install "$file" "$dest"
14622 else
14623   :
14625 @end example
14628 @item @command{printf}
14629 @c ------------------
14630 @prindex @command{printf}
14631 A format string starting with a @samp{-} can cause problems.
14632 Bash interprets it as an option and
14633 gives an error.  And @samp{--} to mark the end of options is not good
14634 in the Net@acronym{BSD} Almquist shell (e.g., 0.4.6) which takes that
14635 literally as the format string.  Putting the @samp{-} in a @samp{%c}
14636 or @samp{%s} is probably easiest:
14638 @example
14639 printf %s -foo
14640 @end example
14642 Bash 2.03 mishandles an escape sequence that happens to evaluate to @samp{%}:
14644 @example
14645 $ @kbd{printf '\045'}
14646 bash: printf: `%': missing format character
14647 @end example
14649 Large outputs may cause trouble.  On Solaris 2.5.1 through 10, for
14650 example, @file{/usr/bin/printf} is buggy, so when using
14651 @command{/bin/sh} the command @samp{printf %010000x 123} normally dumps
14652 core.
14655 @item @command{read}
14656 @c ------------------
14657 @prindex @command{read}
14658 Not all shells support @option{-r} (Solaris @command{/bin/sh} for example).
14661 @item @command{pwd}
14662 @c ----------------
14663 @prindex @command{pwd}
14664 With modern shells, plain @command{pwd} outputs a ``logical''
14665 directory name, some of whose components may be symbolic links.  These
14666 directory names are in contrast to ``physical'' directory names, whose
14667 components are all directories.
14669 Posix 1003.1-2001 requires that @command{pwd} must support
14670 the @option{-L} (``logical'') and @option{-P} (``physical'') options,
14671 with @option{-L} being the default.  However, traditional shells do
14672 not support these options, and their @command{pwd} command has the
14673 @option{-P} behavior.
14675 Portable scripts should assume neither option is supported, and should
14676 assume neither behavior is the default.  Also, on many hosts
14677 @samp{/bin/pwd} is equivalent to @samp{pwd -P}, but Posix
14678 does not require this behavior and portable scripts should not rely on
14681 Typically it's best to use plain @command{pwd}.  On modern hosts this
14682 outputs logical directory names, which have the following advantages:
14684 @itemize @bullet
14685 @item
14686 Logical names are what the user specified.
14687 @item
14688 Physical names may not be portable from one installation
14689 host to another due to network file system gymnastics.
14690 @item
14691 On modern hosts @samp{pwd -P} may fail due to lack of permissions to
14692 some parent directory, but plain @command{pwd} cannot fail for this
14693 reason.
14694 @end itemize
14696 Also please see the discussion of the @command{cd} command.
14699 @item @command{set}
14700 @c ----------------
14701 @prindex @command{set}
14702 With the Free@acronym{BSD} 6.0 shell, the @command{set} command (without
14703 any options) does not sort its output.
14705 The @command{set} builtin faces the usual problem with arguments
14706 starting with a
14707 dash.  Modern shells such as Bash or Zsh understand @option{--} to specify
14708 the end of the options (any argument after @option{--} is a parameter,
14709 even @samp{-x} for instance), but many traditional shells (e.g., Solaris
14710 10 @command{/bin/sh}) simply stop option
14711 processing as soon as a non-option argument is found.  Therefore, use
14712 @samp{dummy} or simply @samp{x} to end the option processing, and use
14713 @command{shift} to pop it out:
14715 @example
14716 set x $my_list; shift
14717 @end example
14719 Avoid @samp{set -}, e.g., @samp{set - $my_list}.  Posix no
14720 longer requires support for this command, and in traditional shells
14721 @samp{set - $my_list} resets the @option{-v} and @option{-x} options, which
14722 makes scripts harder to debug.
14724 Some nonstandard shells do not recognize more than one option
14725 (e.g., @samp{set -e -x} assigns @samp{-x} to the command line).  It is
14726 better to combine them:
14728 @example
14729 set -ex
14730 @end example
14732 The @acronym{BSD} shell has had several problems with the @option{-e}
14733 option, partly because @acronym{BSD} @command{make} traditionally used
14734 @option{-e} even though this was incompatible with Posix
14735 (@pxref{Failure in Make Rules}).  Older versions of the @acronym{BSD}
14736 shell (circa 1990) mishandled @samp{&&}, @samp{||}, @samp{if}, and
14737 @samp{case} when @option{-e} was in effect, causing the shell to exit
14738 unexpectedly in some cases.  This was particularly a problem with
14739 makefiles, and led to circumlocutions like @samp{sh -c 'test -f file ||
14740 touch file'}, where the seemingly-unnecessary @samp{sh -c '@dots{}'}
14741 wrapper works around the bug.
14743 Even relatively-recent versions of the @acronym{BSD} shell (e.g.,
14744 Open@acronym{BSD} 3.4) wrongly exit with @option{-e} if a command within
14745 @samp{&&} fails inside a compound statement.  For example:
14747 @example
14748 #! /bin/sh
14749 set -e
14750 foo=''
14751 test -n "$foo" && exit 1
14752 echo one
14753 if :; then
14754   test -n "$foo" && exit 1
14756 echo two
14757 @end example
14759 @noindent
14760 does not print @samp{two}.  One workaround is to use @samp{if test -n
14761 "$foo"; then exit 1; fi} rather than @samp{test -n "$foo" && exit 1}.
14762 Another possibility is to warn @acronym{BSD} users not to use @samp{sh -e}.
14765 @item @command{shift}
14766 @c ------------------
14767 @prindex @command{shift}
14768 Not only is @command{shift}ing a bad idea when there is nothing left to
14769 shift, but in addition it is not portable: the shell of @acronym{MIPS
14770 RISC/OS} 4.52 refuses to do it.
14772 Don't use @samp{shift 2} etc.; it was not in the 7th Edition Bourne shell,
14773 and it is also absent in many pre-Posix shells.
14776 @item @command{source}
14777 @c -------------------
14778 @prindex @command{source}
14779 This command is not portable, as Posix does not require it; use
14780 @command{.} instead.
14783 @item @command{test}
14784 @c -----------------
14785 @prindex @command{test}
14786 The @code{test} program is the way to perform many file and string
14787 tests.  It is often invoked by the alternate name @samp{[}, but using
14788 that name in Autoconf code is asking for trouble since it is an M4 quote
14789 character.
14791 The @option{-a}, @option{-o}, @samp{(}, and @samp{)} operands are not
14792 portable and should be avoided.  Thus, portable uses of @command{test}
14793 should never have more than four arguments, and scripts should use shell
14794 constructs like @samp{&&} and @samp{||} instead.  If you combine
14795 @samp{&&} and @samp{||} in the same statement, keep in mind that they
14796 have equal precedence, so it is often better to parenthesize even when
14797 this is redundant.  For example:
14799 @smallexample
14800 # Not portable:
14801 test "X$a" = "X$b" -a \
14802   '(' "X$c" != "X$d" -o "X$e" = "X$f" ')'
14804 # Portable:
14805 test "X$a" = "X$b" &&
14806   @{ test "X$c" != "X$d" || test "X$e" = "X$f"; @}
14807 @end smallexample
14809 @command{test} does not process options like most other commands do; for
14810 example, it does not recognize the @option{--} argument as marking the
14811 end of options.
14813 It is safe to use @samp{!} as a @command{test} operator.  For example,
14814 @samp{if test ! -d foo; @dots{}} is portable even though @samp{if ! test
14815 -d foo; @dots{}} is not.
14818 @item @command{test} (files)
14819 @c -------------------------
14820 To enable @command{configure} scripts to support cross-compilation, they
14821 shouldn't do anything that tests features of the build system instead of
14822 the host system.  But occasionally you may find it necessary to check
14823 whether some arbitrary file exists.  To do so, use @samp{test -f} or
14824 @samp{test -r}.  Do not use @samp{test -x}, because 4.3@acronym{BSD} does not
14825 have it.  Do not use @samp{test -e} either, because Solaris @command{/bin/sh}
14826 lacks it.  To test for symbolic links on systems that have them, use
14827 @samp{test -h} rather than @samp{test -L}; either form conforms to
14828 Posix 1003.1-2001, but older shells like Solaris 8
14829 @code{/bin/sh} support only @option{-h}.
14831 @item @command{test} (strings)
14832 @c ---------------------------
14833 Posix says that @samp{test "@var{string}"} succeeds if @var{string} is
14834 not null, but this usage is not portable to traditional platforms like
14835 Solaris 10 @command{/bin/sh}, which mishandle strings like @samp{!} and
14836 @samp{-n}.
14838 Posix also says that @samp{test ! "@var{string}"},
14839 @samp{test -n "@var{string}"} and
14840 @samp{test -z "@var{string}"} work with any string, but many
14841 shells (such as Solaris, @acronym{AIX} 3.2, @sc{unicos} 10.0.0.6,
14842 Digital Unix 4, etc.)@: get confused if
14843 @var{string} looks like an operator:
14845 @example
14846 $ @kbd{test -n =}
14847 test: argument expected
14848 $ @kbd{test ! -n}
14849 test: argument expected
14850 @end example
14852 Similarly, Posix says that both @samp{test "@var{string1}" = "@var{string2"}}
14853 and @samp{test "@var{string1}" != "@var{string2"}} work for any pairs of
14854 strings, but in practice this is not true for troublesome strings that
14855 look like operators or parentheses, or that begin with @samp{-}.
14857 It is best to protect such strings with a leading @samp{X}, e.g.,
14858 @samp{test "X@var{string}" != X} rather than @samp{test -n
14859 "@var{string}"} or @samp{test ! "@var{string}"}.
14861 It is common to find variations of the following idiom:
14863 @example
14864 test -n "`echo $ac_feature | sed 's/[-a-zA-Z0-9_]//g'`" &&
14865   @var{action}
14866 @end example
14868 @noindent
14869 to take an action when a token matches a given pattern.  Such constructs
14870 should be avoided by using:
14872 @example
14873 case $ac_feature in
14874   *[!-a-zA-Z0-9_]*) @var{action};;
14875 esac
14876 @end example
14878 If the pattern is a complicated regular expression that cannot be
14879 expressed as a shell pattern, use something like this instead:
14881 @example
14882 expr "X$ac_feature" : 'X.*[^-a-zA-Z0-9_]' >/dev/null &&
14883   @var{action}
14884 @end example
14886 @samp{expr "X@var{foo}" : "X@var{bar}"} is more robust than @samp{echo
14887 "X@var{foo}" | grep "^X@var{bar}"}, because it avoids problems when
14888 @samp{@var{foo}} contains backslashes.
14891 @item @command{trap}
14892 @c -----------------
14893 @prindex @command{trap}
14894 It is safe to trap at least the signals 1, 2, 13, and 15.  You can also
14895 trap 0, i.e., have the @command{trap} run when the script ends (either via an
14896 explicit @command{exit}, or the end of the script).  The trap for 0 should be
14897 installed outside of a shell function, or @acronym{AIX} 5.3 @command{/bin/sh}
14898 will invoke the trap at the end of this function.
14900 Posix says that @samp{trap - 1 2 13 15} resets the traps for the
14901 specified signals to their default values, but many common shells (e.g.,
14902 Solaris @command{/bin/sh}) misinterpret this and attempt to execute a
14903 ``command'' named @command{-} when the specified conditions arise.
14904 There is no portable workaround, except for @samp{trap - 0}, for which
14905 @samp{trap '' 0} is a portable substitute.
14907 Although Posix is not absolutely clear on this point, it is widely
14908 admitted that when entering the trap @samp{$?} should be set to the exit
14909 status of the last command run before the trap.  The ambiguity can be
14910 summarized as: ``when the trap is launched by an @command{exit}, what is
14911 the @emph{last} command run: that before @command{exit}, or
14912 @command{exit} itself?''
14914 Bash considers @command{exit} to be the last command, while Zsh and
14915 Solaris @command{/bin/sh} consider that when the trap is run it is
14916 @emph{still} in the @command{exit}, hence it is the previous exit status
14917 that the trap receives:
14919 @example
14920 $ @kbd{cat trap.sh}
14921 trap 'echo $?' 0
14922 (exit 42); exit 0
14923 $ @kbd{zsh trap.sh}
14925 $ @kbd{bash trap.sh}
14927 @end example
14929 The portable solution is then simple: when you want to @samp{exit 42},
14930 run @samp{(exit 42); exit 42}, the first @command{exit} being used to
14931 set the exit status to 42 for Zsh, and the second to trigger the trap
14932 and pass 42 as exit status for Bash.
14934 The shell in Free@acronym{BSD} 4.0 has the following bug: @samp{$?} is
14935 reset to 0 by empty lines if the code is inside @command{trap}.
14937 @example
14938 $ @kbd{trap 'false}
14940 echo $?' 0
14941 $ @kbd{exit}
14943 @end example
14945 @noindent
14946 Fortunately, this bug only affects @command{trap}.
14948 @item @command{true}
14949 @c -----------------
14950 @prindex @command{true}
14951 @c Info cannot handle `:' in index entries.
14952 @c @prindex @command{:}
14953 Don't worry: as far as we know @command{true} is portable.
14954 Nevertheless, it's not always a builtin (e.g., Bash 1.x), and the
14955 portable shell community tends to prefer using @command{:}.  This has a
14956 funny side effect: when asked whether @command{false} is more portable
14957 than @command{true} Alexandre Oliva answered:
14959 @quotation
14960 In a sense, yes, because if it doesn't exist, the shell will produce an
14961 exit status of failure, which is correct for @command{false}, but not
14962 for @command{true}.
14963 @end quotation
14966 @item @command{unset}
14967 @c ------------------
14968 @prindex @command{unset}
14969 In some nonconforming shells (e.g., Bash 2.05a), @code{unset FOO} fails
14970 when @code{FOO} is not set.  Also, Bash 2.01 mishandles @code{unset
14971 MAIL} in some cases and dumps core.
14973 A few ancient shells lack @command{unset} entirely.  Nevertheless, because
14974 it is extremely useful to disable embarrassing variables such as
14975 @code{PS1}, you can test for its existence and use
14976 it @emph{provided} you give a neutralizing value when @command{unset} is
14977 not supported:
14979 @smallexample
14980 # "|| exit" suppresses any "Segmentation fault" message.
14981 if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; then
14982   unset=unset
14983 else
14984   unset=false
14986 $unset PS1 || PS1='$ '
14987 @end smallexample
14989 @noindent
14990 @xref{Special Shell Variables}, for some neutralizing values.  Also, see
14991 @ref{Limitations of Builtins}, documentation of @command{export}, for
14992 the case of environment variables.
14993 @end table
14995 @node Limitations of Usual Tools
14996 @section Limitations of Usual Tools
14997 @cindex Limitations of usual tools
14999 The small set of tools you can expect to find on any machine can still
15000 include some limitations you should be aware of.
15002 @table @asis
15003 @item Awk
15004 @c ------
15005 @prindex Awk
15006 Don't leave white space before the opening parenthesis in a user function call.
15007 Posix does not allow this and @acronym{GNU} Awk rejects it:
15009 @example
15010 $ @kbd{gawk 'function die () @{ print "Aaaaarg!"  @}
15011         BEGIN @{ die () @}'}
15012 gawk: cmd. line:2:         BEGIN @{ die () @}
15013 gawk: cmd. line:2:                      ^ parse error
15014 $ @kbd{gawk 'function die () @{ print "Aaaaarg!"  @}
15015         BEGIN @{ die() @}'}
15016 Aaaaarg!
15017 @end example
15019 Posix says that if a program contains only @samp{BEGIN} actions, and
15020 contains no instances of @code{getline}, then the program merely
15021 executes the actions without reading input.  However, traditional Awk
15022 implementations (such as Solaris 10 @command{awk}) read and discard
15023 input in this case.  Portable scripts can redirect input from
15024 @file{/dev/null} to work around the problem.  For example:
15026 @example
15027 awk 'BEGIN @{print "hello world"@}' </dev/null
15028 @end example
15030 Posix says that in an @samp{END} action, @samp{$NF} (and presumably,
15031 @samp{$1}) retain their value from the last record read, if no
15032 intervening @samp{getline} occurred.  However, some implementations
15033 (such as Solaris 10 @samp{/usr/bin/awk}, @samp{nawk}, or Darwin
15034 @samp{awk}) reset these variables.  A workaround is to use an
15035 intermediate variable prior to the @samp{END} block.  For example:
15037 @example
15038 $ @kbd{cat end.awk}
15039 @{ tmp = $1 @}
15040 END @{ print "a", $1, $NF, "b", tmp @}
15041 $ @kbd{echo 1 | awk -f end.awk}
15042 a   b 1
15043 $ @kbd{echo 1 | gawk -f end.awk}
15044 a 1 1 b 1
15045 @end example
15047 If you want your program to be deterministic, don't depend on @code{for}
15048 on arrays:
15050 @example
15051 $ @kbd{cat for.awk}
15052 END @{
15053   arr["foo"] = 1
15054   arr["bar"] = 1
15055   for (i in arr)
15056     print i
15058 $ @kbd{gawk -f for.awk </dev/null}
15061 $ @kbd{nawk -f for.awk </dev/null}
15064 @end example
15066 Some Awk implementations, such as @acronym{HP-UX} 11.0's native one,
15067 mishandle anchors:
15069 @example
15070 $ @kbd{echo xfoo | $AWK '/foo|^bar/ @{ print @}'}
15071 $ @kbd{echo bar | $AWK '/foo|^bar/ @{ print @}'}
15073 $ @kbd{echo xfoo | $AWK '/^bar|foo/ @{ print @}'}
15074 xfoo
15075 $ @kbd{echo bar | $AWK '/^bar|foo/ @{ print @}'}
15077 @end example
15079 @noindent
15080 Either do not depend on such patterns (i.e., use @samp{/^(.*foo|bar)/},
15081 or use a simple test to reject such implementations.
15083 On @samp{ia64-hp-hpux11.23}, Awk mishandles @code{printf} conversions
15084 after @code{%u}:
15086 @example
15087 $ @kbd{awk 'BEGIN @{ printf "%u %d\n", 0, -1 @}'}
15088 0 0
15089 @end example
15091 @acronym{AIX} version 5.2 has an arbitrary limit of 399 on the
15092 length of regular expressions and literal strings in an Awk program.
15094 Traditional Awk implementations derived from Unix version 7, such as
15095 Solaris @command{/bin/awk}, have many limitations and do not
15096 conform to Posix.  Nowadays @code{AC_PROG_AWK} (@pxref{Particular
15097 Programs}) finds you an Awk that doesn't have these problems, but if
15098 for some reason you prefer not to use @code{AC_PROG_AWK} you may need to
15099 address them.
15101 Traditional Awk does not support multidimensional arrays or user-defined
15102 functions.
15104 Traditional Awk does not support the @option{-v} option.  You can use
15105 assignments after the program instead, e.g., @code{$AWK '@{print v
15106 $1@}' v=x}; however, don't forget that such assignments are not
15107 evaluated until they are encountered (e.g., after any @code{BEGIN}
15108 action).
15110 Traditional Awk does not support the keywords @code{delete} or @code{do}.
15112 Traditional Awk does not support the expressions
15113 @code{@var{a}?@var{b}:@var{c}}, @code{!@var{a}}, @code{@var{a}^@var{b}},
15114 or @code{@var{a}^=@var{b}}.
15116 Traditional Awk does not support the predefined @code{CONVFMT} variable.
15118 Traditional Awk supports only the predefined functions @code{exp}, @code{index},
15119 @code{int}, @code{length}, @code{log}, @code{split}, @code{sprintf},
15120 @code{sqrt}, and @code{substr}.
15122 Traditional Awk @code{getline} is not at all compatible with Posix;
15123 avoid it.
15125 Traditional Awk has @code{for (i in a) @dots{}} but no other uses of the
15126 @code{in} keyword.  For example, it lacks @code{if (i in a) @dots{}}.
15128 In code portable to both traditional and modern Awk, @code{FS} must be a
15129 string containing just one ordinary character, and similarly for the
15130 field-separator argument to @code{split}.
15132 Traditional Awk has a limit of 99 fields in a record.  Since some Awk
15133 implementations, like Tru64's, split the input even if you don't refer
15134 to any field in the script, to circumvent this problem, set @samp{FS}
15135 to an unusual character and use @code{split}.
15137 Traditional Awk has a limit of at most 99 bytes in a number formatted by
15138 @code{OFMT}; for example, @code{OFMT="%.300e"; print 0.1;} typically
15139 dumps core.
15141 The original version of Awk had a limit of at most 99 bytes per
15142 @code{split} field, 99 bytes per @code{substr} substring, and 99 bytes
15143 per run of non-special characters in a @code{printf} format, but these
15144 bugs have been fixed on all practical hosts that we know of.
15146 @item @command{basename}
15147 @c ---------------------
15148 @prindex @command{basename}
15149 Not all hosts have a working @command{basename}.
15150 You can use @command{expr} instead.
15152 @c AS_BASENAME is to be replaced by a better API.
15153 @ignore
15154 Not all hosts have a working @command{basename}, and you should instead
15155 use @code{AS_BASENAME} (@pxref{Programming in M4sh}), followed by
15156 @command{expr} if you need to strip a suffix.  For example:
15158 @example
15159 a=`basename "$aname"`       # This is not portable.
15160 a=`AS_BASENAME(["$aname"])` # This is more portable.
15162 # This is not portable.
15163 c=`basename "$cname" .c`
15165 # This is more portable.
15166 c=`AS_BASENAME(["$cname"])`
15167 case $c in
15168 ?*.c) c=`expr "X$c" : 'X\(.*\)\.c'`;;
15169 esac
15170 @end example
15171 @end ignore
15174 @item @command{cat}
15175 @c ----------------
15176 @prindex @command{cat}
15177 Don't rely on any option.
15180 @item @command{cc}
15181 @c ---------------
15182 @prindex @command{cc}
15183 The command @samp{cc -c foo.c} traditionally produces an object file
15184 named @file{foo.o}.  Most compilers allow @option{-c} to be combined
15185 with @option{-o} to specify a different object file name, but
15186 Posix does not require this combination and a few compilers
15187 lack support for it.  @xref{C Compiler}, for how @acronym{GNU} Make
15188 tests for this feature with @code{AC_PROG_CC_C_O}.
15190 When a compilation such as @samp{cc -o foo foo.c} fails, some compilers
15191 (such as @sc{cds} on Reliant Unix) leave a @file{foo.o}.
15193 @acronym{HP-UX} @command{cc} doesn't accept @file{.S} files to preprocess and
15194 assemble.  @samp{cc -c foo.S} appears to succeed, but in fact does
15195 nothing.
15197 The default executable, produced by @samp{cc foo.c}, can be
15199 @itemize
15200 @item @file{a.out} --- usual Posix convention.
15201 @item @file{b.out} --- i960 compilers (including @command{gcc}).
15202 @item @file{a.exe} --- @acronym{DJGPP} port of @command{gcc}.
15203 @item @file{a_out.exe} --- GNV @command{cc} wrapper for DEC C on OpenVMS.
15204 @item @file{foo.exe} --- various MS-DOS compilers.
15205 @end itemize
15207 The C compiler's traditional name is @command{cc}, but other names like
15208 @command{gcc} are common.  Posix 1003.1-2001 specifies the
15209 name @command{c99}, but older Posix editions specified
15210 @command{c89} and anyway these standard names are rarely used in
15211 practice.  Typically the C compiler is invoked from makefiles that use
15212 @samp{$(CC)}, so the value of the @samp{CC} make variable selects the
15213 compiler name.
15216 @item @command{chmod}
15217 @c ------------------
15218 @prindex @command{chmod}
15219 Avoid usages like @samp{chmod -w file}; use @samp{chmod a-w file}
15220 instead, for two reasons.  First, plain @option{-w} does not necessarily
15221 make the file unwritable, since it does not affect mode bits that
15222 correspond to bits in the file mode creation mask.  Second,
15223 Posix says that the @option{-w} might be interpreted as an
15224 implementation-specific option, not as a mode; Posix suggests
15225 using @samp{chmod -- -w file} to avoid this confusion, but unfortunately
15226 @samp{--} does not work on some older hosts.
15229 @item @command{cmp}
15230 @c ----------------
15231 @prindex @command{cmp}
15232 @command{cmp} performs a raw data comparison of two files, while
15233 @command{diff} compares two text files.  Therefore, if you might compare
15234 DOS files, even if only checking whether two files are different, use
15235 @command{diff} to avoid spurious differences due to differences of
15236 newline encoding.
15239 @item @command{cp}
15240 @c ---------------
15241 @prindex @command{cp}
15242 Avoid the @option{-r} option, since Posix 1003.1-2004 marks it as
15243 obsolescent and its behavior on special files is implementation-defined.
15244 Use @option{-R} instead.  On @acronym{GNU} hosts the two options
15245 are equivalent, but on Solaris hosts (for example) @code{cp -r}
15246 reads from pipes instead of replicating them.
15248 Some @command{cp} implementations (e.g., @acronym{BSD/OS} 4.2) do not allow
15249 trailing slashes at the end of nonexistent destination directories.  To
15250 avoid this problem, omit the trailing slashes.  For example, use
15251 @samp{cp -R source /tmp/newdir} rather than @samp{cp -R source
15252 /tmp/newdir/} if @file{/tmp/newdir} does not exist.
15254 @c This is thanks to Ian.
15255 The ancient SunOS 4 @command{cp} does not support @option{-f}, although
15256 its @command{mv} does.
15258 @cindex timestamp resolution
15259 Traditionally, file timestamps had 1-second resolution, and @samp{cp
15260 -p} copied the timestamps exactly.  However, many modern file systems
15261 have timestamps with 1-nanosecond resolution.  Unfortunately, @samp{cp
15262 -p} implementations truncate timestamps when copying files, so this
15263 can result in the destination file appearing to be older than the
15264 source.  The exact amount of truncation depends on the resolution of
15265 the system calls that @command{cp} uses; traditionally this was
15266 @code{utime}, which has 1-second resolution, but some newer
15267 @command{cp} implementations use @code{utimes}, which has
15268 1-microsecond resolution.  These newer implementations include @acronym{GNU}
15269 Core Utilities 5.0.91 or later, and Solaris 8 (sparc) patch 109933-02 or
15270 later.  Unfortunately as of January 2006 there is still no system
15271 call to set timestamps to the full nanosecond resolution.
15273 Bob Proulx notes that @samp{cp -p} always @emph{tries} to copy
15274 ownerships.  But whether it actually does copy ownerships or not is a
15275 system dependent policy decision implemented by the kernel.  If the
15276 kernel allows it then it happens.  If the kernel does not allow it then
15277 it does not happen.  It is not something @command{cp} itself has control
15278 over.
15280 In Unix System V any user can chown files to any other user, and System
15281 V also has a non-sticky @file{/tmp}.  That probably derives from the
15282 heritage of System V in a business environment without hostile users.
15283 @acronym{BSD} changed this
15284 to be a more secure model where only root can @command{chown} files and
15285 a sticky @file{/tmp} is used.  That undoubtedly derives from the heritage
15286 of @acronym{BSD} in a campus environment.
15288 @acronym{GNU}/Linux and Solaris by default follow @acronym{BSD}, but
15289 can be configured to allow a System V style @command{chown}.  On the
15290 other hand, @acronym{HP-UX} follows System V, but can
15291 be configured to use the modern security model and disallow
15292 @command{chown}.  Since it is an administrator-configurable parameter
15293 you can't use the name of the kernel as an indicator of the behavior.
15297 @item @command{date}
15298 @c -----------------
15299 @prindex @command{date}
15300 Some versions of @command{date} do not recognize special @samp{%} directives,
15301 and unfortunately, instead of complaining, they just pass them through,
15302 and exit with success:
15304 @example
15305 $ @kbd{uname -a}
15306 OSF1 medusa.sis.pasteur.fr V5.1 732 alpha
15307 $ @kbd{date "+%s"}
15309 @end example
15312 @item @command{diff}
15313 @c -----------------
15314 @prindex @command{diff}
15315 Option @option{-u} is nonportable.
15317 Some implementations, such as Tru64's, fail when comparing to
15318 @file{/dev/null}.  Use an empty file instead.
15321 @item @command{dirname}
15322 @c --------------------
15323 @prindex @command{dirname}
15324 Not all hosts have a working @command{dirname}, and you should instead
15325 use @code{AS_DIRNAME} (@pxref{Programming in M4sh}).  For example:
15327 @example
15328 dir=`dirname "$file"`       # This is not portable.
15329 dir=`AS_DIRNAME(["$file"])` # This is more portable.
15330 @end example
15333 @item @command{egrep}
15334 @c ------------------
15335 @prindex @command{egrep}
15336 Posix 1003.1-2001 no longer requires @command{egrep},
15337 but many hosts do not yet support the Posix
15338 replacement @code{grep -E}.  Also, some traditional implementations do
15339 not work on long input lines.  To work around these problems, invoke
15340 @code{AC_PROG_EGREP} and then use @code{$EGREP}.
15342 Portable extended regular expressions should use @samp{\} only to escape
15343 characters in the string @samp{$()*+.?[\^@{|}.  For example, @samp{\@}}
15344 is not portable, even though it typically matches @samp{@}}.
15346 The empty alternative is not portable.  Use @samp{?} instead.  For
15347 instance with Digital Unix v5.0:
15349 @example
15350 > printf "foo\n|foo\n" | $EGREP '^(|foo|bar)$'
15351 |foo
15352 > printf "bar\nbar|\n" | $EGREP '^(foo|bar|)$'
15353 bar|
15354 > printf "foo\nfoo|\n|bar\nbar\n" | $EGREP '^(foo||bar)$'
15356 |bar
15357 @end example
15359 @command{$EGREP} also suffers the limitations of @command{grep}.
15361 @item @command{expr}
15362 @c -----------------
15363 @prindex @command{expr}
15364 No @command{expr} keyword starts with @samp{X}, so use @samp{expr
15365 X"@var{word}" : 'X@var{regex}'} to keep @command{expr} from
15366 misinterpreting @var{word}.
15368 Don't use @code{length}, @code{substr}, @code{match} and @code{index}.
15370 @item @command{expr} (@samp{|})
15371 @prindex @command{expr} (@samp{|})
15372 You can use @samp{|}.  Although Posix does require that @samp{expr
15373 ''} return the empty string, it does not specify the result when you
15374 @samp{|} together the empty string (or zero) with the empty string.  For
15375 example:
15377 @example
15378 expr '' \| ''
15379 @end example
15381 Posix 1003.2-1992 returns the empty string
15382 for this case, but traditional Unix returns @samp{0} (Solaris is
15383 one such example).  In Posix 1003.1-2001, the specification was
15384 changed to match traditional Unix's behavior (which is
15385 bizarre, but it's too late to fix this).  Please note that the same
15386 problem does arise when the empty string results from a computation,
15387 as in:
15389 @example
15390 expr bar : foo \| foo : bar
15391 @end example
15393 @noindent
15394 Avoid this portability problem by avoiding the empty string.
15397 @item @command{expr} (@samp{:})
15398 @c ----------------------------
15399 @prindex @command{expr}
15400 Portable @command{expr} regular expressions should use @samp{\} to
15401 escape only characters in the string @samp{$()*.0123456789[\^n@{@}}.
15402 For example, alternation, @samp{\|}, is common but Posix does not
15403 require its support, so it should be avoided in portable scripts.
15404 Similarly, @samp{\+} and @samp{\?} should be avoided.
15406 Portable @command{expr} regular expressions should not begin with
15407 @samp{^}.  Patterns are automatically anchored so leading @samp{^} is
15408 not needed anyway.
15410 The Posix standard is ambiguous as to whether
15411 @samp{expr 'a' : '\(b\)'} outputs @samp{0} or the empty string.
15412 In practice, it outputs the empty string on most platforms, but portable
15413 scripts should not assume this.  For instance, the @acronym{QNX} 4.25 native
15414 @command{expr} returns @samp{0}.
15416 One might think that a way to get a uniform behavior would be to use
15417 the empty string as a default value:
15419 @example
15420 expr a : '\(b\)' \| ''
15421 @end example
15423 @noindent
15424 Unfortunately this behaves exactly as the original expression; see the
15425 @command{expr} (@samp{|}) entry for more information.
15427 Some ancient @command{expr} implementations (e.g., SunOS 4 @command{expr} and
15428 Solaris 8 @command{/usr/ucb/expr}) have a silly length limit that causes
15429 @command{expr} to fail if the matched substring is longer than 120
15430 bytes.  In this case, you might want to fall back on @samp{echo|sed} if
15431 @command{expr} fails.  Nowadays this is of practical importance only for
15432 the rare installer who mistakenly puts @file{/usr/ucb} before
15433 @file{/usr/bin} in @env{PATH}.
15435 On Mac OS X 10.4, @command{expr} mishandles the pattern @samp{[^-]} in
15436 some cases.  For example, the command
15437 @example
15438 expr Xpowerpc-apple-darwin8.1.0 : 'X[^-]*-[^-]*-\(.*\)'
15439 @end example
15441 @noindent
15442 outputs @samp{apple-darwin8.1.0} rather than the correct @samp{darwin8.1.0}.
15443 This particular case can be worked around by substituting @samp{[^--]}
15444 for @samp{[^-]}.
15446 Don't leave, there is some more!
15448 The @acronym{QNX} 4.25 @command{expr}, in addition of preferring @samp{0} to
15449 the empty string, has a funny behavior in its exit status: it's always 1
15450 when parentheses are used!
15452 @example
15453 $ @kbd{val=`expr 'a' : 'a'`; echo "$?: $val"}
15454 0: 1
15455 $ @kbd{val=`expr 'a' : 'b'`; echo "$?: $val"}
15456 1: 0
15458 $ @kbd{val=`expr 'a' : '\(a\)'`; echo "?: $val"}
15459 1: a
15460 $ @kbd{val=`expr 'a' : '\(b\)'`; echo "?: $val"}
15461 1: 0
15462 @end example
15464 @noindent
15465 In practice this can be a big problem if you are ready to catch failures
15466 of @command{expr} programs with some other method (such as using
15467 @command{sed}), since you may get twice the result.  For instance
15469 @example
15470 $ @kbd{expr 'a' : '\(a\)' || echo 'a' | sed 's/^\(a\)$/\1/'}
15471 @end example
15473 @noindent
15474 outputs @samp{a} on most hosts, but @samp{aa} on @acronym{QNX} 4.25.  A
15475 simple workaround consists of testing @command{expr} and using a variable
15476 set to @command{expr} or to @command{false} according to the result.
15478 Tru64 @command{expr} incorrectly treats the result as a number, if it
15479 can be interpreted that way:
15481 @example
15482 $ @kbd{expr 00001 : '.*\(...\)'}
15484 @end example
15487 @item @command{fgrep}
15488 @c ------------------
15489 @prindex @command{fgrep}
15490 Posix 1003.1-2001 no longer requires @command{fgrep},
15491 but many hosts do not yet support the Posix
15492 replacement @code{grep -F}.  Also, some traditional implementations do
15493 not work on long input lines.  To work around these problems, invoke
15494 @code{AC_PROG_FGREP} and then use @code{$FGREP}.
15497 @item @command{find}
15498 @c -----------------
15499 @prindex @command{find}
15500 The option @option{-maxdepth} seems to be @acronym{GNU} specific.
15501 Tru64 v5.1, Net@acronym{BSD} 1.5 and Solaris @command{find}
15502 commands do not understand it.
15504 The replacement of @samp{@{@}} is guaranteed only if the argument is
15505 exactly @emph{@{@}}, not if it's only a part of an argument.  For
15506 instance on DU, and @acronym{HP-UX} 10.20 and @acronym{HP-UX} 11:
15508 @example
15509 $ @kbd{touch foo}
15510 $ @kbd{find . -name foo -exec echo "@{@}-@{@}" \;}
15511 @{@}-@{@}
15512 @end example
15514 @noindent
15515 while @acronym{GNU} @command{find} reports @samp{./foo-./foo}.
15518 @item @command{grep}
15519 @c -----------------
15520 @prindex @command{grep}
15521 Portable scripts can rely on the @command{grep} options @option{-c},
15522 @option{-l}, @option{-n}, and @option{-v}, but should avoid other
15523 options.  For example, don't use @option{-w}, as Posix does not require
15524 it and Irix 6.5.16m's @command{grep} does not support it.  Also,
15525 portable scripts should not combine @option{-c} with @option{-l},
15526 as Posix does not allow this.
15528 Some of the options required by Posix are not portable in practice.
15529 Don't use @samp{grep -q} to suppress output, because many @command{grep}
15530 implementations (e.g., Solaris) do not support @option{-q}.
15531 Don't use @samp{grep -s} to suppress output either, because Posix
15532 says @option{-s} does not suppress output, only some error messages;
15533 also, the @option{-s} option of traditional @command{grep} behaved
15534 like @option{-q} does in most modern implementations.  Instead,
15535 redirect the standard output and standard error (in case the file
15536 doesn't exist) of @code{grep} to @file{/dev/null}.  Check the exit
15537 status of @code{grep} to determine whether it found a match.
15539 Some traditional @command{grep} implementations do not work on long
15540 input lines.  On AIX the default @code{grep} silently truncates long
15541 lines on the input before matching.
15543 Also, many implementations do not support multiple regexps
15544 with @option{-e}: they either reject @option{-e} entirely (e.g., Solaris)
15545 or honor only the last pattern (e.g., @acronym{IRIX} 6.5 and NeXT).  To
15546 work around these problems, invoke @code{AC_PROG_GREP} and then use
15547 @code{$GREP}.
15549 Another possible workaround for the multiple @option{-e} problem is to
15550 separate the patterns by newlines, for example:
15552 @example
15553 grep 'foo
15554 bar' in.txt
15555 @end example
15557 @noindent
15558 except that this fails with traditional @command{grep}
15559 implementations and with Open@acronym{BSD} 3.8 @command{grep}.
15561 Traditional @command{grep} implementations (e.g., Solaris) do not
15562 support the @option{-E} or @option{-F} options.  To work around these
15563 problems, invoke @code{AC_PROG_EGREP} and then use @code{$EGREP}, and
15564 similarly for @code{AC_PROG_FGREP} and @code{$FGREP}.  Even if you are
15565 willing to require support for Posix @command{grep}, your script should
15566 not use both @option{-E} and @option{-F}, since Posix does not allow
15567 this combination.
15569 Portable @command{grep} regular expressions should use @samp{\} only to
15570 escape characters in the string @samp{$()*.0123456789[\^@{@}}.  For example,
15571 alternation, @samp{\|}, is common but Posix does not require its
15572 support in basic regular expressions, so it should be avoided in
15573 portable scripts.  Solaris and HP-UX @command{grep} do not support it.
15574 Similarly, the following escape sequences should also be avoided:
15575 @samp{\<}, @samp{\>}, @samp{\+}, @samp{\?}, @samp{\`}, @samp{\'},
15576 @samp{\B}, @samp{\b}, @samp{\S}, @samp{\s}, @samp{\W}, and @samp{\w}.
15578 Posix does not specify the behavior of @command{grep} on binary files.
15579 An example where this matters is using @acronym{BSD} @command{grep} to
15580 search text that includes embedded @acronym{ANSI} escape sequences for
15581 colored output to terminals (@samp{\033[m} is the sequence to restore
15582 normal output); the behavior depends on whether input is seekable:
15584 @example
15585 $ @kbd{printf 'esc\033[mape\n' > sample}
15586 $ @kbd{grep . sample}
15587 Binary file sample matches
15588 $ @kbd{cat sample | grep .}
15589 escape
15590 @end example
15593 @item @command{join}
15594 @c -----------------
15595 @prindex @command{join}
15596 Solaris 8 @command{join} has bugs when the second operand is standard
15597 input, and when standard input is a pipe.  For example, the following
15598 shell script causes Solaris 8 @command{join} to loop forever:
15600 @example
15601 cat >file <<'EOF'
15602 1 x
15603 2 y
15605 cat file | join file -
15606 @end example
15608 Use @samp{join - file} instead.
15611 @item @command{ln}
15612 @c ---------------
15613 @prindex @command{ln}
15614 @cindex Symbolic links
15615 Don't rely on @command{ln} having a @option{-f} option.  Symbolic links
15616 are not available on old systems; use @samp{$(LN_S)} as a portable substitute.
15618 For versions of the @acronym{DJGPP} before 2.04,
15619 @command{ln} emulates symbolic links
15620 to executables by generating a stub that in turn calls the real
15621 program.  This feature also works with nonexistent files like in the
15622 Posix spec.  So @samp{ln -s file link} generates @file{link.exe},
15623 which attempts to call @file{file.exe} if run.  But this feature only
15624 works for executables, so @samp{cp -p} is used instead for these
15625 systems.  @acronym{DJGPP} versions 2.04 and later have full support
15626 for symbolic links.
15629 @item @command{ls}
15630 @c ---------------
15631 @prindex @command{ls}
15632 @cindex Listing directories
15633 The portable options are @option{-acdilrtu}.  Current practice is for
15634 @option{-l} to output both owner and group, even though ancient versions
15635 of @command{ls} omitted the group.
15637 On ancient hosts, @samp{ls foo} sent the diagnostic @samp{foo not found}
15638 to standard output if @file{foo} did not exist.  Hence a shell command
15639 like @samp{sources=`ls *.c 2>/dev/null`} did not always work, since it
15640 was equivalent to @samp{sources='*.c not found'} in the absence of
15641 @samp{.c} files.  This is no longer a practical problem, since current
15642 @command{ls} implementations send diagnostics to standard error.
15644 @item @command{mkdir}
15645 @c ------------------
15646 @prindex @command{mkdir}
15647 @cindex Making directories
15648 No @command{mkdir} option is portable to older systems.  Instead of
15649 @samp{mkdir -p @var{file-name}}, you should use
15650 @code{AS_MKDIR_P(@var{file-name})} (@pxref{Programming in M4sh})
15651 or @code{AC_PROG_MKDIR_P} (@pxref{Particular Programs}).
15653 Combining the @option{-m} and @option{-p} options, as in @samp{mkdir -m
15654 go-w -p @var{dir}}, often leads to trouble.  Free@acronym{BSD}
15655 @command{mkdir} incorrectly attempts to change the permissions of
15656 @var{dir} even if it already exists.  @acronym{HP-UX} 11.23 and
15657 @acronym{IRIX} 6.5 @command{mkdir} often assign the wrong permissions to
15658 any newly-created parents of @var{dir}.
15660 Posix does not clearly specify whether @samp{mkdir -p foo}
15661 should succeed when @file{foo} is a symbolic link to an already-existing
15662 directory.  The @acronym{GNU} Core Utilities 5.1.0 @command{mkdir}
15663 succeeds, but Solaris @command{mkdir} fails.
15665 Traditional @code{mkdir -p} implementations suffer from race conditions.
15666 For example, if you invoke @code{mkdir -p a/b} and @code{mkdir -p a/c}
15667 at the same time, both processes might detect that @file{a} is missing,
15668 one might create @file{a}, then the other might try to create @file{a}
15669 and fail with a @code{File exists} diagnostic.  The @acronym{GNU} Core
15670 Utilities (@samp{fileutils} version 4.1), Free@acronym{BSD} 5.0,
15671 Net@acronym{BSD} 2.0.2, and Open@acronym{BSD} 2.4 are known to be
15672 race-free when two processes invoke @code{mkdir -p} simultaneously, but
15673 earlier versions are vulnerable.  Solaris @command{mkdir} is still
15674 vulnerable as of Solaris 10, and other traditional Unix systems are
15675 probably vulnerable too.  This possible race is harmful in parallel
15676 builds when several Make rules call @code{mkdir -p} to
15677 construct directories.  You may use
15678 @code{install-sh -d} as a safe replacement, provided this script is
15679 recent enough; the copy shipped with Autoconf 2.60 and Automake 1.10 is
15680 OK, but copies from older versions are vulnerable.
15683 @item @command{mktemp}
15684 @c -------------------
15685 @prindex @command{mktemp}
15686 @cindex Creating temporary files
15687 Shell scripts can use temporary files safely with @command{mktemp}, but
15688 it does not exist on all systems.  A portable way to create a safe
15689 temporary file name is to create a temporary directory with mode 700 and
15690 use a file inside this directory.  Both methods prevent attackers from
15691 gaining control, though @command{mktemp} is far less likely to fail
15692 gratuitously under attack.
15694 Here is sample code to create a new temporary directory safely:
15696 @example
15697 # Create a temporary directory $tmp in $TMPDIR (default /tmp).
15698 # Use mktemp if possible; otherwise fall back on mkdir,
15699 # with $RANDOM to make collisions less likely.
15700 : $@{TMPDIR=/tmp@}
15702   tmp=`
15703     (umask 077 && mktemp -d "$TMPDIR/fooXXXXXX") 2>/dev/null
15704   ` &&
15705   test -n "$tmp" && test -d "$tmp"
15706 @} || @{
15707   tmp=$TMPDIR/foo$$-$RANDOM
15708   (umask 077 && mkdir "$tmp")
15709 @} || exit $?
15710 @end example
15713 @item @command{mv}
15714 @c ---------------
15715 @prindex @command{mv}
15716 @cindex Moving open files
15717 The only portable options are @option{-f} and @option{-i}.
15719 Moving individual files between file systems is portable (it was in Unix
15720 version 6),
15721 but it is not always atomic: when doing @samp{mv new existing}, there's
15722 a critical section where neither the old nor the new version of
15723 @file{existing} actually exists.
15725 On some systems moving files from @file{/tmp} can sometimes cause
15726 undesirable (but perfectly valid) warnings, even if you created these
15727 files.  This is because @file{/tmp} belongs to a group that ordinary
15728 users are not members of, and files created in @file{/tmp} inherit
15729 the group of @file{/tmp}.  When the file is copied, @command{mv} issues
15730 a diagnostic without failing:
15732 @smallexample
15733 $ @kbd{touch /tmp/foo}
15734 $ @kbd{mv /tmp/foo .}
15735 @error{}mv: ./foo: set owner/group (was: 100/0): Operation not permitted
15736 $ @kbd{echo $?}
15738 $ @kbd{ls foo}
15740 @end smallexample
15742 @noindent
15743 This annoying behavior conforms to Posix, unfortunately.
15745 Moving directories across mount points is not portable, use @command{cp}
15746 and @command{rm}.
15748 @acronym{DOS} variants cannot rename or remove open files, and do not
15749 support commands like @samp{mv foo bar >foo}, even though this is
15750 perfectly portable among Posix hosts.
15753 @item @command{od}
15754 @c ---------------
15755 @prindex @command{od}
15757 In Mac OS X 10.3, @command{od} does not support the
15758 standard Posix options @option{-A}, @option{-j}, @option{-N}, or
15759 @option{-t}, or the @acronym{XSI} option @option{-s}.  The only
15760 supported Posix option is @option{-v}, and the only supported
15761 @acronym{XSI} options are those in @option{-bcdox}.  The @acronym{BSD}
15762 @command{hexdump} program can be used instead.
15764 This problem no longer exists in Mac OS X 10.4.3.
15767 @item @command{rm}
15768 @c ---------------
15769 @prindex @command{rm}
15770 The @option{-f} and @option{-r} options are portable.
15772 It is not portable to invoke @command{rm} without operands.  For
15773 example, on many systems @samp{rm -f -r} (with no other arguments)
15774 silently succeeds without doing anything, but it fails with a diagnostic
15775 on Net@acronym{BSD} 2.0.2.
15777 A file might not be removed even if its parent directory is writable
15778 and searchable.  Many Posix hosts cannot remove a mount point, a named
15779 stream, a working directory, or a last link to a file that is being
15780 executed.
15782 @acronym{DOS} variants cannot rename or remove open files, and do not
15783 support commands like @samp{rm foo >foo}, even though this is
15784 perfectly portable among Posix hosts.
15787 @item @command{sed}
15788 @c ----------------
15789 @prindex @command{sed}
15790 Patterns should not include the separator (unless escaped), even as part
15791 of a character class.  In conformance with Posix, the Cray
15792 @command{sed} rejects @samp{s/[^/]*$//}: use @samp{s,[^/]*$,,}.
15794 Avoid empty patterns within parentheses (i.e., @samp{\(\)}).  Posix does
15795 not require support for empty patterns, and Unicos 9 @command{sed} rejects
15796 them.
15798 Unicos 9 @command{sed} loops endlessly on patterns like @samp{.*\n.*}.
15800 Sed scripts should not use branch labels longer than 7 characters and
15801 should not contain comments.  @acronym{HP-UX} sed has a limit of 99 commands
15802 (not counting @samp{:} commands) and
15803 48 labels, which can not be circumvented by using more than one script
15804 file.  It can execute up to 19 reads with the @samp{r} command per cycle.
15805 Solaris @command{/usr/ucb/sed} rejects usages that exceed an limit of
15806 about 6000 bytes for the internal representation of commands.
15808 Avoid redundant @samp{;}, as some @command{sed} implementations, such as
15809 Net@acronym{BSD} 1.4.2's, incorrectly try to interpret the second
15810 @samp{;} as a command:
15812 @example
15813 $ @kbd{echo a | sed 's/x/x/;;s/x/x/'}
15814 sed: 1: "s/x/x/;;s/x/x/": invalid command code ;
15815 @end example
15817 Input should not have unreasonably long lines, since some @command{sed}
15818 implementations have an input buffer limited to 4000 bytes.
15820 Portable @command{sed} regular expressions should use @samp{\} only to escape
15821 characters in the string @samp{$()*.0123456789[\^n@{@}}.  For example,
15822 alternation, @samp{\|}, is common but Posix does not require its
15823 support, so it should be avoided in portable scripts.  Solaris
15824 @command{sed} does not support alternation; e.g., @samp{sed '/a\|b/d'}
15825 deletes only lines that contain the literal string @samp{a|b}.
15826 Similarly, @samp{\+} and @samp{\?} should be avoided.
15828 Anchors (@samp{^} and @samp{$}) inside groups are not portable.
15830 Nested parentheses in patterns (e.g., @samp{\(\(a*\)b*)\)}) are
15831 quite portable to current hosts, but was not supported by some ancient
15832 @command{sed} implementations like SVR3.
15834 Some @command{sed} implementations, e.g., Solaris,
15835 restrict the special role of the asterisk to one-character regular expressions.
15836 This may lead to unexpected behavior:
15838 @example
15839 $ @kbd{echo '1*23*4' | /usr/bin/sed 's/\(.\)*/x/g'}
15840 x2x4
15841 $ @kbd{echo '1*23*4' | /usr/xpg4/bin/sed 's/\(.\)*/x/g'}
15843 @end example
15845 The @option{-e} option is mostly portable.
15846 However, its argument
15847 cannot start with @samp{a}, @samp{c}, or @samp{i},
15848 as this runs afoul of a Tru64 5.1 bug.
15849 Also, its argument cannot be empty, as this fails on @acronym{AIX} 5.3.
15850 Some people prefer to use @samp{-e}:
15852 @example
15853 sed -e '@var{command-1}' \
15854     -e '@var{command-2}'
15855 @end example
15857 @noindent
15858 as opposed to the equivalent:
15860 @example
15861 sed '
15862   @var{command-1}
15863   @var{command-2}
15865 @end example
15867 @noindent
15868 The following usage is sometimes equivalent:
15870 @example
15871 sed '@var{command-1};@var{command-2}'
15872 @end example
15874 but Posix says that this use of a semicolon has undefined effect if
15875 @var{command-1}'s verb is @samp{@{}, @samp{a}, @samp{b}, @samp{c},
15876 @samp{i}, @samp{r}, @samp{t}, @samp{w}, @samp{:}, or @samp{#}, so you
15877 should use semicolon only with simple scripts that do not use these
15878 verbs.
15880 Commands inside @{ @} brackets are further restricted.  Posix says that
15881 they cannot be preceded by addresses, @samp{!}, or @samp{;}, and that
15882 each command must be followed immediately by a newline, without any
15883 intervening blanks or semicolons.  The closing bracket must be alone on
15884 a line, other than white space preceding or following it.
15886 Contrary to yet another urban legend, you may portably use @samp{&} in
15887 the replacement part of the @code{s} command to mean ``what was
15888 matched''.  All descendants of Unix version 7 @command{sed}
15889 (at least; we
15890 don't have first hand experience with older @command{sed} implementations) have
15891 supported it.
15893 Posix requires that you must not have any white space between
15894 @samp{!} and the following command.  It is OK to have blanks between
15895 the address and the @samp{!}.  For instance, on Solaris:
15897 @example
15898 $ @kbd{echo "foo" | sed -n '/bar/ ! p'}
15899 @error{}Unrecognized command: /bar/ ! p
15900 $ @kbd{echo "foo" | sed -n '/bar/! p'}
15901 @error{}Unrecognized command: /bar/! p
15902 $ @kbd{echo "foo" | sed -n '/bar/ !p'}
15904 @end example
15906 Posix also says that you should not combine @samp{!} and @samp{;}.  If
15907 you use @samp{!}, it is best to put it on a command that is delimited by
15908 newlines rather than @samp{;}.
15910 Also note that Posix requires that the @samp{b}, @samp{t}, @samp{r}, and
15911 @samp{w} commands be followed by exactly one space before their argument.
15912 On the other hand, no white space is allowed between @samp{:} and the
15913 subsequent label name.
15915 If a sed script is specified on the command line and ends in an
15916 @samp{a}, @samp{c}, or @samp{i} command, the last line of inserted text
15917 should be followed by a newline.  Otherwise some @command{sed}
15918 implementations (e.g., Open@acronym{BSD} 3.9) do not append a newline to the
15919 inserted text.
15921 Many @command{sed} implementations (e.g., MacOS X 10.4,
15922 Open@acronym{BSD} 3.9, Solaris 10
15923 @command{/usr/ucb/sed}) strip leading white space from the text of
15924 @samp{a}, @samp{c}, and @samp{i} commands.  Prepend a backslash to
15925 work around this incompatibility with Posix:
15927 @example
15928 $ @kbd{echo flushleft | sed 'a\}
15929 > @kbd{   indented}
15930 > @kbd{'}
15931 flushleft
15932 indented
15933 $ @kbd{echo foo | sed 'a\}
15934 > @kbd{\   indented}
15935 > @kbd{'}
15936 flushleft
15937    indented
15938 @end example
15940 Posix requires that with an empty regular expression, the last non-empty
15941 regular expression from either an address specification or substitution
15942 command is applied.  However, busybox 1.6.1 complains when using a
15943 substitution command with a replacement containing a back-reference to
15944 an empty regular expression; the workaround is repeating the regular
15945 expression.
15947 @example
15948 $ @kbd{echo abc | busybox sed '/a\(b\)c/ s//\1/'}
15949 sed: No previous regexp.
15950 $ @kbd{echo abc | busybox sed '/a\(b\)c/ s/a\(b\)c/\1/'}
15952 @end example
15955 @item @command{sed} (@samp{t})
15956 @c ---------------------------
15957 @prindex @command{sed} (@samp{t})
15958 Some old systems have @command{sed} that ``forget'' to reset their
15959 @samp{t} flag when starting a new cycle.  For instance on @acronym{MIPS
15960 RISC/OS}, and on @sc{irix} 5.3, if you run the following @command{sed}
15961 script (the line numbers are not actual part of the texts):
15963 @example
15964 s/keep me/kept/g  # a
15965 t end             # b
15966 s/.*/deleted/g    # c
15967 :end              # d
15968 @end example
15970 @noindent
15973 @example
15974 delete me         # 1
15975 delete me         # 2
15976 keep me           # 3
15977 delete me         # 4
15978 @end example
15980 @noindent
15981 you get
15983 @example
15984 deleted
15985 delete me
15986 kept
15987 deleted
15988 @end example
15990 @noindent
15991 instead of
15993 @example
15994 deleted
15995 deleted
15996 kept
15997 deleted
15998 @end example
16000 Why?  When processing line 1, (c) matches, therefore sets the @samp{t}
16001 flag, and the output is produced.  When processing
16002 line 2, the @samp{t} flag is still set (this is the bug).  Command (a)
16003 fails to match, but @command{sed} is not supposed to clear the @samp{t}
16004 flag when a substitution fails.  Command (b) sees that the flag is set,
16005 therefore it clears it, and jumps to (d), hence you get @samp{delete me}
16006 instead of @samp{deleted}.  When processing line (3), @samp{t} is clear,
16007 (a) matches, so the flag is set, hence (b) clears the flags and jumps.
16008 Finally, since the flag is clear, line 4 is processed properly.
16010 There are two things one should remember about @samp{t} in @command{sed}.
16011 Firstly, always remember that @samp{t} jumps if @emph{some} substitution
16012 succeeded, not only the immediately preceding substitution.  Therefore,
16013 always use a fake @samp{t clear} followed by a @samp{:clear} on the next
16014 line, to reset the @samp{t} flag where needed.
16016 Secondly, you cannot rely on @command{sed} to clear the flag at each new
16017 cycle.
16019 One portable implementation of the script above is:
16021 @example
16022 t clear
16023 :clear
16024 s/keep me/kept/g
16025 t end
16026 s/.*/deleted/g
16027 :end
16028 @end example
16030 @item @command{touch}
16031 @c ------------------
16032 @prindex @command{touch}
16033 @cindex timestamp resolution
16034 If you specify the desired timestamp (e.g., with the @option{-r}
16035 option), @command{touch} typically uses the @code{utime} or
16036 @code{utimes} system call, which can result in the same kind of
16037 timestamp truncation problems that @samp{cp -p} has.
16039 On ancient @acronym{BSD} systems, @command{touch} or any command that
16040 results in an empty file does not update the timestamps, so use a
16041 command like @command{echo} as a workaround.
16042 Also,
16043 @acronym{GNU} @command{touch} 3.16r (and presumably all before that)
16044 fails to work on SunOS 4.1.3 when the empty file is on an
16045 @acronym{NFS}-mounted 4.2 volume.
16046 However, these problems are no longer of practical concern.
16048 @item @command{tr}
16049 @c ---------------
16050 @prindex @command{tr}
16051 @cindex carriage return, deleting
16052 @cindex deleting carriage return
16053 Not all versions of @command{tr} handle all backslash character escapes.
16054 For example, Solaris 10 @command{/usr/ucb/tr} falls over, even though
16055 Solaris contains more modern @command{tr} in other locations.
16056 Therefore, it is more portable to use octal escapes, even though this
16057 ties the result to @acronym{ASCII}, when using @command{tr} to delete
16058 newlines or carriage returns.
16060 @example
16061 $ @kbd{@{ echo moon; echo light; @} | /usr/ucb/tr -d '\n' ; echo}
16063 light
16064 $ @kbd{@{ echo moon; echo light; @} | /usr/bin/tr -d '\n' ; echo}
16065 moonlight
16066 $ @kbd{@{ echo moon; echo light; @} | /usr/ucb/tr -d '\012' ; echo}
16067 moonlight
16068 @end example
16070 @end table
16073 @node Portable Make
16074 @chapter Portable Make Programming
16075 @prindex @command{make}
16076 @cindex Limitations of @command{make}
16078 Writing portable makefiles is an art.  Since a makefile's commands are
16079 executed by the shell, you must consider the shell portability issues
16080 already mentioned.  However, other issues are specific to @command{make}
16081 itself.
16083 @menu
16084 * $< in Ordinary Make Rules::   $< in ordinary rules
16085 * Failure in Make Rules::       Failing portably in rules
16086 * Special Chars in Names::      Special Characters in Macro Names
16087 * Backslash-Newline-Newline::   Empty last lines in macro definitions
16088 * Backslash-Newline Comments::  Spanning comments across line boundaries
16089 * Long Lines in Makefiles::     Line length limitations
16090 * Macros and Submakes::         @code{make macro=value} and submakes
16091 * The Make Macro MAKEFLAGS::    @code{$(MAKEFLAGS)} portability issues
16092 * The Make Macro SHELL::        @code{$(SHELL)} portability issues
16093 * Comments in Make Rules::      Other problems with Make comments
16094 * obj/ and Make::               Don't name a subdirectory @file{obj}
16095 * make -k Status::              Exit status of @samp{make -k}
16096 * VPATH and Make::              @code{VPATH} woes
16097 * Single Suffix Rules::         Single suffix rules and separated dependencies
16098 * Timestamps and Make::         Subsecond timestamp resolution
16099 @end menu
16101 @node $< in Ordinary Make Rules
16102 @section @code{$<} in Ordinary Make Rules
16104 Posix says that the @samp{$<} construct in makefiles can be
16105 used only in inference rules and in the @samp{.DEFAULT} rule; its
16106 meaning in ordinary rules is unspecified.  Solaris @command{make}
16107 for instance replaces it with the empty string.  Open@acronym{BSD} (3.0 and
16108 later) @command{make} diagnoses these uses and errors out.
16110 @node Failure in Make Rules
16111 @section Failure in Make Rules
16113 Since 1992 Posix has required that @command{make} must invoke
16114 each command with the equivalent of a @samp{sh -c} subshell.  However,
16115 many @command{make} implementations, including @acronym{BSD} make through 2004,
16116 use @samp{sh -e -c} instead, and the @option{-e} option causes the
16117 subshell to exit immediately if a subsidiary simple-command fails.  For
16118 example, the command @samp{touch T; rm -f U} always attempts to
16119 remove @file{U} with Posix make, but incompatible
16120 @command{make} implementations skip the @command{rm} if the
16121 @command{touch} fails.  One way to work around this is to reword the
16122 affected simple-commands so that they always succeed, e.g., @samp{touch
16123 T || :; rm -f U}.
16124 However, even this approach can run into common bugs in @acronym{BSD}
16125 implementations of the @option{-e} option of @command{sh} and
16126 @command{set} (@pxref{Limitations of Builtins}), so if you are worried
16127 about porting to buggy @acronym{BSD} shells it may be simpler to migrate
16128 complicated @command{make} actions into separate scripts.
16130 @node Special Chars in Names
16131 @section Special Characters in Make Macro Names
16133 Posix limits macro names to nonempty strings containing only
16134 @acronym{ASCII} letters and digits, @samp{.}, and @samp{_}.  Many
16135 @command{make} implementations allow a wider variety of characters, but
16136 portable makefiles should avoid them.  It is portable to start a name
16137 with a special character, e.g., @samp{$(.FOO)}.
16139 Some ancient @command{make} implementations don't support leading
16140 underscores in macro names.  An example is @acronym{NEWS-OS} 4.2R.
16142 @example
16143 $ @kbd{cat Makefile}
16144 _am_include = #
16145 _am_quote =
16146 all:; @@echo this is test
16147 $ @kbd{make}
16148 Make: Must be a separator on rules line 2.  Stop.
16149 $ @kbd{cat Makefile2}
16150 am_include = #
16151 am_quote =
16152 all:; @@echo this is test
16153 $ @kbd{make -f Makefile2}
16154 this is test
16155 @end example
16157 @noindent
16158 However, this problem is no longer of practical concern.
16160 @node Backslash-Newline-Newline
16161 @section Backslash-Newline-Newline in Make Macro Values
16163 @c  This has been seen on ia64 hpux 11.20, and on one hppa hpux 10.20,
16164 @c  but another hppa hpux 10.20 didn't have it.  Bob Proulx
16165 @c  <bob@proulx.com> thinks it was in hpux 8.0 too.
16166 On some versions of @acronym{HP-UX}, @command{make} reads multiple newlines
16167 following a backslash, continuing to the next non-empty line.  For
16168 example,
16170 @example
16171 FOO = one \
16173 BAR = two
16175 test:
16176         : FOO is "$(FOO)"
16177         : BAR is "$(BAR)"
16178 @end example
16180 @noindent
16181 shows @code{FOO} equal to @code{one BAR = two}.  Other implementations
16182 sensibly let a backslash continue only to the immediately following
16183 line.
16185 @node Backslash-Newline Comments
16186 @section Backslash-Newline in Make Comments
16188 According to Posix, Make comments start with @code{#}
16189 and continue until an unescaped newline is reached.
16191 @example
16192 $ @kbd{cat Makefile}
16193 # A = foo \
16194       bar \
16195       baz
16197 all:
16198         @@echo ok
16199 $ @kbd{make}   # GNU make
16201 @end example
16203 @noindent
16204 However this is not always the case.  Some implementations
16205 discard everything from @code{#} through the end of the line, ignoring any
16206 trailing backslash.
16208 @example
16209 $ @kbd{pmake}  # BSD make
16210 "Makefile", line 3: Need an operator
16211 Fatal errors encountered -- cannot continue
16212 @end example
16214 @noindent
16215 Therefore, if you want to comment out a multi-line definition, prefix each
16216 line with @code{#}, not only the first.
16218 @example
16219 # A = foo \
16220 #     bar \
16221 #     baz
16222 @end example
16224 @node Long Lines in Makefiles
16225 @section Long Lines in Makefiles
16227 Tru64 5.1's @command{make} has been reported to crash when given a
16228 makefile with lines longer than around 20 kB.  Earlier versions are
16229 reported to exit with @code{Line too long} diagnostics.
16231 @node Macros and Submakes
16232 @section @code{make macro=value} and Submakes
16234 A command-line variable definition such as @code{foo=bar} overrides any
16235 definition of @code{foo} in a makefile.  Some @command{make}
16236 implementations (such as @acronym{GNU} @command{make}) propagate this
16237 override to subsidiary invocations of @command{make}.  Some other
16238 implementations do not pass the substitution along to submakes.
16240 @example
16241 $ @kbd{cat Makefile}
16242 foo = foo
16243 one:
16244         @@echo $(foo)
16245         $(MAKE) two
16246 two:
16247         @@echo $(foo)
16248 $ @kbd{make foo=bar}            # GNU make 3.79.1
16250 make two
16251 make[1]: Entering directory `/home/adl'
16253 make[1]: Leaving directory `/home/adl'
16254 $ @kbd{pmake foo=bar}           # BSD make
16256 pmake two
16258 @end example
16260 You have a few possibilities if you do want the @code{foo=bar} override
16261 to propagate to submakes.  One is to use the @option{-e}
16262 option, which causes all environment variables to have precedence over
16263 the makefile macro definitions, and declare foo as an environment
16264 variable:
16266 @example
16267 $ @kbd{env foo=bar make -e}
16268 @end example
16270 The @option{-e} option is propagated to submakes automatically,
16271 and since the environment is inherited between @command{make}
16272 invocations, the @code{foo} macro is overridden in
16273 submakes as expected.
16275 This syntax (@code{foo=bar make -e}) is portable only when used
16276 outside of a makefile, for instance from a script or from the
16277 command line.  When run inside a @command{make} rule, @acronym{GNU}
16278 @command{make} 3.80 and prior versions forget to propagate the
16279 @option{-e} option to submakes.
16281 Moreover, using @option{-e} could have unexpected side effects if your
16282 environment contains some other macros usually defined by the
16283 makefile.  (See also the note about @code{make -e} and @code{SHELL}
16284 below.)
16286 Another way to propagate overrides to submakes is to do it
16287 manually, from your makefile:
16289 @example
16290 foo = foo
16291 one:
16292         @@echo $(foo)
16293         $(MAKE) foo=$(foo) two
16294 two:
16295         @@echo $(foo)
16296 @end example
16298 You need to foresee all macros that a user might want to override if
16299 you do that.
16301 @node The Make Macro MAKEFLAGS
16302 @section The Make Macro MAKEFLAGS
16303 @cindex @code{MAKEFLAGS} and @command{make}
16304 @cindex @command{make} and @code{MAKEFLAGS}
16306 Posix requires @command{make} to use @code{MAKEFLAGS} to affect the
16307 current and recursive invocations of make, but allows implementations
16308 several formats for the variable.  It is tricky to parse
16309 @code{$MAKEFLAGS} to determine whether @option{-s} for silent execution
16310 or @option{-k} for continued execution are in effect.  For example, you
16311 cannot assume that the first space-separated word in @code{$MAKEFLAGS}
16312 contains single-letter options, since in the Cygwin version of
16313 @acronym{GNU} @command{make} it is either @option{--unix} or
16314 @option{--win32} with the second word containing single-letter options.
16316 @example
16317 $ @kbd{cat Makefile}
16318 all:
16319         @@echo MAKEFLAGS = $(MAKEFLAGS)
16320 $ @kbd{make}
16321 MAKEFLAGS = --unix
16322 $ @kbd{make -k}
16323 MAKEFLAGS = --unix -k
16324 @end example
16326 @node The Make Macro SHELL
16327 @section The Make Macro @code{SHELL}
16328 @cindex @code{SHELL} and @command{make}
16329 @cindex @command{make} and @code{SHELL}
16331 Posix-compliant @command{make} internally uses the @code{$(SHELL)}
16332 macro to spawn shell processes and execute Make rules.  This
16333 is a builtin macro supplied by @command{make}, but it can be modified
16334 by a makefile or by a command-line argument.
16336 Not all @command{make} implementations define this @code{SHELL} macro.
16337 Tru64
16338 @command{make} is an example; this implementation always uses
16339 @code{/bin/sh}.  So it's a good idea to always define @code{SHELL} in
16340 your makefiles.  If you use Autoconf, do
16342 @example
16343 SHELL = @@SHELL@@
16344 @end example
16346 @noindent
16347 If you use Automake, this is done for you.
16349 Do not force @code{SHELL = /bin/sh} because that is not correct
16350 everywhere.  Remember, @file{/bin/sh} is not Posix compliant on many
16351 systems, such as FreeBSD 4, NetBSD 3, AIX 3, Solaris 10, or Tru64.
16352 Additionally, @acronym{DJGPP} lacks @code{/bin/sh}, and when its
16353 @acronym{GNU} @command{make} port sees such a setting it enters a
16354 special emulation mode where features like pipes and redirections are
16355 emulated on top of DOS's @command{command.com}.  Unfortunately this
16356 emulation is incomplete; for instance it does not handle command
16357 substitutions.  Using @code{@@SHELL@@} means that your makefile will
16358 benefit from the same improved shell, such as @command{bash} or
16359 @command{ksh}, that was discovered during @command{configure}, so that
16360 you aren't fighting two different sets of shell bugs between the two
16361 contexts.
16363 Posix-compliant @command{make} should never acquire the value of
16364 $(SHELL) from the environment, even when @code{make -e} is used
16365 (otherwise, think about what would happen to your rules if
16366 @code{SHELL=/bin/tcsh}).
16368 However not all @command{make} implementations have this exception.
16369 For instance it's not surprising that Tru64 @command{make} doesn't
16370 protect @code{SHELL}, since it doesn't use it.
16372 @example
16373 $ @kbd{cat Makefile}
16374 SHELL = /bin/sh
16375 FOO = foo
16376 all:
16377         @@echo $(SHELL)
16378         @@echo $(FOO)
16379 $ @kbd{env SHELL=/bin/tcsh FOO=bar make -e}   # Tru64 Make
16380 /bin/tcsh
16382 $ @kbd{env SHELL=/bin/tcsh FOO=bar gmake -e}  # GNU make
16383 /bin/sh
16385 @end example
16387 Conversely, @command{make} is not supposed to export any changes to the
16388 macro @code{SHELL} to child processes.  Again, many implementations
16389 break this rule:
16391 @example
16392 $ @kbd{cat Makefile}
16393 all:
16394         @@echo $(SHELL)
16395         @@printenv SHELL
16396 $ @kbd{env SHELL=sh make -e SHELL=/bin/ksh}   # BSD Make, GNU make 3.80
16397 /bin/ksh
16398 /bin/ksh
16399 $ @kbd{env SHELL=sh gmake -e SHELL=/bin/ksh}  # GNU make 3.81
16400 /bin/ksh
16402 @end example
16404 @node Comments in Make Rules
16405 @section Comments in Make Rules
16406 @cindex Comments in @file{Makefile} rules
16407 @cindex @file{Makefile} rules and comments
16409 Never put comments in a rule.
16411 Some @command{make} treat anything starting with a tab as a command for
16412 the current rule, even if the tab is immediately followed by a @code{#}.
16413 The @command{make} from Tru64 Unix V5.1 is one of them.  The following
16414 makefile runs @code{# foo} through the shell.
16416 @example
16417 all:
16418         # foo
16419 @end example
16421 @node obj/ and Make
16422 @section The @file{obj/} Subdirectory and Make
16423 @cindex @file{obj/}, subdirectory
16424 @cindex @acronym{BSD} @command{make} and @file{obj/}
16426 Never name one of your subdirectories @file{obj/} if you don't like
16427 surprises.
16429 If an @file{obj/} directory exists, @acronym{BSD} @command{make} enters it
16430 before reading the makefile.  Hence the makefile in the
16431 current directory is not read.
16433 @example
16434 $ @kbd{cat Makefile}
16435 all:
16436         echo Hello
16437 $ @kbd{cat obj/Makefile}
16438 all:
16439         echo World
16440 $ @kbd{make}      # GNU make
16441 echo Hello
16442 Hello
16443 $ @kbd{pmake}     # BSD make
16444 echo World
16445 World
16446 @end example
16448 @node make -k Status
16449 @section Exit Status of @code{make -k}
16450 @cindex @code{make -k}
16452 Do not rely on the exit status of @code{make -k}.  Some implementations
16453 reflect whether they encountered an error in their exit status; other
16454 implementations always succeed.
16456 @example
16457 $ @kbd{cat Makefile}
16458 all:
16459         false
16460 $ @kbd{make -k; echo exit status: $?}    # GNU make
16461 false
16462 make: *** [all] Error 1
16463 exit status: 2
16464 $ @kbd{pmake -k; echo exit status: $?}   # BSD make
16465 false
16466 *** Error code 1 (continuing)
16467 exit status: 0
16468 @end example
16470 @node VPATH and Make
16471 @section @code{VPATH} and Make
16472 @cindex @code{VPATH}
16474 Posix does not specify the semantics of @code{VPATH}.  Typically,
16475 @command{make} supports @code{VPATH}, but its implementation is not
16476 consistent.
16478 Autoconf and Automake support makefiles whose usages of @code{VPATH} are
16479 portable to recent-enough popular implementations of @command{make}, but
16480 to keep the resulting makefiles portable, a package's makefile
16481 prototypes must take the following issues into account.  These issues
16482 are complicated and are often poorly understood, and installers who use
16483 @code{VPATH} should expect to find many bugs in this area.  If you use
16484 @code{VPATH}, the simplest way to avoid these portability bugs is to
16485 stick with @acronym{GNU} @command{make}, since it is the most
16486 commonly-used @command{make} among Autoconf users.
16488 Here are some known issues with some @code{VPATH}
16489 implementations.
16491 @menu
16492 * VPATH and Double-colon::      Problems with @samp{::} on ancient hosts
16493 * $< in Explicit Rules::        @code{$<} does not work in ordinary rules
16494 * Automatic Rule Rewriting::    @code{VPATH} goes wild on Solaris
16495 * Tru64 Directory Magic::       @command{mkdir} goes wild on Tru64
16496 * Make Target Lookup::          More details about @code{VPATH} lookup
16497 @end menu
16499 @node VPATH and Double-colon
16500 @subsection @code{VPATH} and Double-colon Rules
16501 @cindex @code{VPATH} and double-colon rules
16502 @cindex double-colon rules and @code{VPATH}
16504 With ancient versions of Sun @command{make},
16505 any assignment to @code{VPATH} causes @command{make} to execute only
16506 the first set of double-colon rules.
16507 However, this problem is no longer of practical concern.
16509 @node $< in Explicit Rules
16510 @subsection @code{$<} Not Supported in Explicit Rules
16511 @cindex explicit rules, @code{$<}, and @code{VPATH}
16512 @cindex @code{$<}, explicit rules, and @code{VPATH}
16513 @cindex @code{VPATH}, explicit rules, and @code{$<}
16515 Using @code{$<} in explicit rules is not portable.
16516 The prerequisite file must be named explicitly in the rule.  If you want
16517 to find the prerequisite via a @code{VPATH} search, you have to code the
16518 whole thing manually.  @xref{Build Directories}.
16520 @node Automatic Rule Rewriting
16521 @subsection Automatic Rule Rewriting
16522 @cindex @code{VPATH} and automatic rule rewriting
16523 @cindex automatic rule rewriting and @code{VPATH}
16525 Some @command{make} implementations, such as Solaris and Tru64,
16526 search for prerequisites in @code{VPATH} and
16527 then rewrite each occurrence as a plain word in the rule.
16528 For instance:
16530 @example
16531 # This isn't portable to GNU make.
16532 VPATH = ../pkg/src
16533 f.c: if.c
16534         cp if.c f.c
16535 @end example
16537 @noindent
16538 executes @code{cp ../pkg/src/if.c f.c} if @file{if.c} is
16539 found in @file{../pkg/src}.
16541 However, this rule leads to real problems in practice.  For example, if
16542 the source directory contains an ordinary file named @file{test} that is
16543 used in a dependency, Solaris @command{make} rewrites commands like
16544 @samp{if test -r foo; @dots{}} to @samp{if ../pkg/src/test -r foo;
16545 @dots{}}, which is typically undesirable.  To avoid this problem,
16546 portable makefiles should never mention a source file whose name is that
16547 of a shell keyword like @file{until} or a shell command like
16548 @command{cat} or @command{gcc} or @command{test}.
16550 Because of these problems @acronym{GNU} @command{make} and many other
16551 @command{make} implementations do not rewrite commands, so portable
16552 makefiles should
16553 search @code{VPATH} manually.  It is tempting to write this:
16555 @smallexample
16556 # This isn't portable to Solaris make.
16557 VPATH = ../pkg/src
16558 f.c: if.c
16559         cp `test -f if.c || echo $(VPATH)/`if.c f.c
16560 @end smallexample
16562 @noindent
16563 However, the ``prerequisite rewriting'' still applies here.  So if
16564 @file{if.c} is in @file{../pkg/src}, Solaris and Tru64 @command{make}
16565 execute
16567 @smallexample
16568 cp `test -f ../pkg/src/if.c || echo ../pkg/src/`if.c f.c
16569 @end smallexample
16571 @noindent
16572 which reduces to
16574 @example
16575 cp if.c f.c
16576 @end example
16578 @noindent
16579 and thus fails.  Oops.
16581 A simple workaround, and good practice anyway, is to use @samp{$?} and
16582 @samp{$@@} when possible:
16584 @smallexample
16585 VPATH = ../pkg/src
16586 f.c: if.c
16587         cp $? $@@
16588 @end smallexample
16590 @noindent
16591 but this does not generalize well to commands with multiple
16592 prerequisites.  A more general workaround is to rewrite the rule so that
16593 the prerequisite @file{if.c} never appears as a plain word.  For
16594 example, these three rules would be safe, assuming @file{if.c} is in
16595 @file{../pkg/src} and the other files are in the working directory:
16597 @smallexample
16598 VPATH = ../pkg/src
16599 f.c: if.c f1.c
16600         cat `test -f ./if.c || echo $(VPATH)/`if.c f1.c >$@@
16601 g.c: if.c g1.c
16602         cat `test -f 'if.c' || echo $(VPATH)/`if.c g1.c >$@@
16603 h.c: if.c h1.c
16604         cat `test -f "if.c" || echo $(VPATH)/`if.c h1.c >$@@
16605 @end smallexample
16607 Things get worse when your prerequisites are in a macro.
16609 @example
16610 VPATH = ../pkg/src
16611 HEADERS = f.h g.h h.h
16612 install-HEADERS: $(HEADERS)
16613         for i in $(HEADERS); do \
16614           $(INSTALL) -m 644 \
16615             `test -f $$i || echo $(VPATH)/`$$i \
16616             $(DESTDIR)$(includedir)/$$i; \
16617         done
16618 @end example
16620 The above @code{install-HEADERS} rule is not Solaris-proof because @code{for
16621 i in $(HEADERS);} is expanded to @code{for i in f.h g.h h.h;}
16622 where @code{f.h} and @code{g.h} are plain words and are hence
16623 subject to @code{VPATH} adjustments.
16625 If the three files are in @file{../pkg/src}, the rule is run as:
16627 @example
16628 for i in ../pkg/src/f.h ../pkg/src/g.h h.h; do \
16629   install -m 644 \
16630      `test -f $i || echo ../pkg/src/`$i \
16631      /usr/local/include/$i; \
16632 done
16633 @end example
16635 where the two first @command{install} calls fail.  For instance,
16636 consider the @code{f.h} installation:
16638 @example
16639 install -m 644 \
16640   `test -f ../pkg/src/f.h || \
16641     echo ../pkg/src/ \
16642   `../pkg/src/f.h \
16643   /usr/local/include/../pkg/src/f.h;
16644 @end example
16646 @noindent
16647 It reduces to:
16649 @example
16650 install -m 644 \
16651   ../pkg/src/f.h \
16652   /usr/local/include/../pkg/src/f.h;
16653 @end example
16655 Note that the manual @code{VPATH} search did not cause any problems here;
16656 however this command installs @file{f.h} in an incorrect directory.
16658 Trying to quote @code{$(HEADERS)} in some way, as we did for
16659 @code{foo.c} a few makefiles ago, does not help:
16661 @example
16662 install-HEADERS: $(HEADERS)
16663         headers='$(HEADERS)'; \
16664         for i in $$headers; do \
16665           $(INSTALL) -m 644 \
16666             `test -f $$i || echo $(VPATH)/`$$i \
16667             $(DESTDIR)$(includedir)/$$i; \
16668         done
16669 @end example
16671 Now, @code{headers='$(HEADERS)'} macro-expands to:
16673 @example
16674 headers='f.h g.h h.h'
16675 @end example
16677 @noindent
16678 but @code{g.h} is still a plain word.  (As an aside, the idiom
16679 @code{headers='$(HEADERS)'; for i in $$headers;} is a good
16680 idea if @code{$(HEADERS)} can be empty, because some shells diagnose a
16681 syntax error on @code{for i in;}.)
16683 One workaround is to strip this unwanted @file{../pkg/src/} prefix manually:
16685 @example
16686 VPATH = ../pkg/src
16687 HEADERS = f.h g.h h.h
16688 install-HEADERS: $(HEADERS)
16689         headers='$(HEADERS)'; \
16690         for i in $$headers; do \
16691           i=`expr "$$i" : '$(VPATH)/\(.*\)'`;
16692           $(INSTALL) -m 644 \
16693             `test -f $$i || echo $(VPATH)/`$$i \
16694             $(DESTDIR)$(includedir)/$$i; \
16695         done
16696 @end example
16698 Automake does something similar.  However the above hack works only if
16699 the files listed in @code{HEADERS} are in the current directory or a
16700 subdirectory; they should not be in an enclosing directory.  If we had
16701 @code{HEADERS = ../f.h}, the above fragment would fail in a VPATH
16702 build with Tru64 @command{make}.  The reason is that not only does
16703 Tru64 @command{make} rewrite dependencies, but it also simplifies
16704 them.  Hence @code{../f.h} becomes @code{../pkg/f.h} instead of
16705 @code{../pkg/src/../f.h}.  This obviously defeats any attempt to strip
16706 a leading @file{../pkg/src/} component.
16708 The following example makes the behavior of Tru64 @command{make}
16709 more apparent.
16711 @example
16712 $ @kbd{cat Makefile}
16713 VPATH = sub
16714 all: ../foo
16715         echo ../foo
16716 $ @kbd{ls}
16717 Makefile foo
16718 $ @kbd{make}
16719 echo foo
16721 @end example
16723 @noindent
16724 Dependency @file{../foo} was found in @file{sub/../foo}, but Tru64
16725 @command{make} simplified it as @file{foo}.  (Note that the @file{sub/}
16726 directory does not even exist, this just means that the simplification
16727 occurred before the file was checked for.)
16729 For the record here is how SunOS 4 @command{make} behaves on this
16730 example.
16732 @smallexample
16733 $ @kbd{make}
16734 make: Fatal error: Don't know how to make target `../foo'
16735 $ @kbd{mkdir sub}
16736 $ @kbd{make}
16737 echo sub/../foo
16738 sub/../foo
16739 @end smallexample
16742 @node Tru64 Directory Magic
16743 @subsection Tru64 @command{make} Creates Prerequisite Directories Magically
16744 @cindex @code{VPATH} and prerequisite directories
16745 @cindex prerequisite directories and @code{VPATH}
16747 When a prerequisite is a subdirectory of @code{VPATH}, Tru64
16748 @command{make} creates it in the current directory.
16750 @example
16751 $ @kbd{mkdir -p foo/bar build}
16752 $ @kbd{cd build}
16753 $ @kbd{cat >Makefile <<END
16754 VPATH = ..
16755 all: foo/bar
16756 END}
16757 $ @kbd{make}
16758 mkdir foo
16759 mkdir foo/bar
16760 @end example
16762 This can yield unexpected results if a rule uses a manual @code{VPATH}
16763 search as presented before.
16765 @example
16766 VPATH = ..
16767 all : foo/bar
16768         command `test -d foo/bar || echo ../`foo/bar
16769 @end example
16771 The above @command{command} is run on the empty @file{foo/bar}
16772 directory that was created in the current directory.
16774 @node Make Target Lookup
16775 @subsection Make Target Lookup
16776 @cindex @code{VPATH}, resolving target pathnames
16778 @acronym{GNU} @command{make} uses a complex algorithm to decide when it
16779 should use files found via a @code{VPATH} search.  @xref{Search
16780 Algorithm, , How Directory Searches are Performed, make, The @acronym{GNU} Make
16781 Manual}.
16783 If a target needs to be rebuilt, @acronym{GNU} @command{make} discards the
16784 file name found during the @code{VPATH} search for this target, and
16785 builds the file locally using the file name given in the makefile.
16786 If a target does not need to be rebuilt, @acronym{GNU} @command{make} uses the
16787 file name found during the @code{VPATH} search.
16789 Other @command{make} implementations, like Net@acronym{BSD} @command{make}, are
16790 easier to describe: the file name found during the @code{VPATH} search
16791 is used whether the target needs to be rebuilt or not.  Therefore
16792 new files are created locally, but existing files are updated at their
16793 @code{VPATH} location.
16795 Open@acronym{BSD} and Free@acronym{BSD} @command{make}, however,
16796 never perform a
16797 @code{VPATH} search for a dependency that has an explicit rule.
16798 This is extremely annoying.
16800 When attempting a @code{VPATH} build for an autoconfiscated package
16801 (e.g., @code{mkdir build && cd build && ../configure}), this means
16802 @acronym{GNU}
16803 @command{make} builds everything locally in the @file{build}
16804 directory, while @acronym{BSD} @command{make} builds new files locally and
16805 updates existing files in the source directory.
16807 @example
16808 $ @kbd{cat Makefile}
16809 VPATH = ..
16810 all: foo.x bar.x
16811 foo.x bar.x: newer.x
16812         @@echo Building $@@
16813 $ @kbd{touch ../bar.x}
16814 $ @kbd{touch ../newer.x}
16815 $ @kbd{make}        # GNU make
16816 Building foo.x
16817 Building bar.x
16818 $ @kbd{pmake}       # NetBSD make
16819 Building foo.x
16820 Building ../bar.x
16821 $ @kbd{fmake}       # FreeBSD make, OpenBSD make
16822 Building foo.x
16823 Building bar.x
16824 $ @kbd{tmake}       # Tru64 make
16825 Building foo.x
16826 Building bar.x
16827 $ @kbd{touch ../bar.x}
16828 $ @kbd{make}        # GNU make
16829 Building foo.x
16830 $ @kbd{pmake}       # NetBSD make
16831 Building foo.x
16832 $ @kbd{fmake}       # FreeBSD make, OpenBSD make
16833 Building foo.x
16834 Building bar.x
16835 $ @kbd{tmake}       # Tru64 make
16836 Building foo.x
16837 Building bar.x
16838 @end example
16840 Note how Net@acronym{BSD} @command{make} updates @file{../bar.x} in its
16841 VPATH location, and how Free@acronym{BSD}, Open@acronym{BSD}, and Tru64
16842 @command{make} always
16843 update @file{bar.x}, even when @file{../bar.x} is up to date.
16845 Another point worth mentioning is that once @acronym{GNU} @command{make} has
16846 decided to ignore a @code{VPATH} file name (e.g., it ignored
16847 @file{../bar.x} in the above example) it continues to ignore it when
16848 the target occurs as a prerequisite of another rule.
16850 The following example shows that @acronym{GNU} @command{make} does not look up
16851 @file{bar.x} in @code{VPATH} before performing the @code{.x.y} rule,
16852 because it ignored the @code{VPATH} result of @file{bar.x} while running
16853 the @code{bar.x: newer.x} rule.
16855 @example
16856 $ @kbd{cat Makefile}
16857 VPATH = ..
16858 all: bar.y
16859 bar.x: newer.x
16860         @@echo Building $@@
16861 .SUFFIXES: .x .y
16862 .x.y:
16863         cp $< $@@
16864 $ @kbd{touch ../bar.x}
16865 $ @kbd{touch ../newer.x}
16866 $ @kbd{make}        # GNU make
16867 Building bar.x
16868 cp bar.x bar.y
16869 cp: cannot stat `bar.x': No such file or directory
16870 make: *** [bar.y] Error 1
16871 $ @kbd{pmake}       # NetBSD make
16872 Building ../bar.x
16873 cp ../bar.x bar.y
16874 $ @kbd{rm bar.y}
16875 $ @kbd{fmake}       # FreeBSD make, OpenBSD make
16876 echo Building bar.x
16877 cp bar.x bar.y
16878 cp: cannot stat `bar.x': No such file or directory
16879 *** Error code 1
16880 $ @kbd{tmake}       # Tru64 make
16881 Building bar.x
16882 cp: bar.x: No such file or directory
16883 *** Exit 1
16884 @end example
16886 Note that if you drop away the command from the @code{bar.x: newer.x}
16887 rule, @acronym{GNU} @command{make} magically starts to work: it
16888 knows that @code{bar.x} hasn't been updated, therefore it doesn't
16889 discard the result from @code{VPATH} (@file{../bar.x}) in succeeding
16890 uses.  Tru64 also works, but Free@acronym{BSD} and Open@acronym{BSD}
16891 still don't.
16893 @example
16894 $ @kbd{cat Makefile}
16895 VPATH = ..
16896 all: bar.y
16897 bar.x: newer.x
16898 .SUFFIXES: .x .y
16899 .x.y:
16900         cp $< $@@
16901 $ @kbd{touch ../bar.x}
16902 $ @kbd{touch ../newer.x}
16903 $ @kbd{make}        # GNU make
16904 cp ../bar.x bar.y
16905 $ @kbd{rm bar.y}
16906 $ @kbd{pmake}       # NetBSD make
16907 cp ../bar.x bar.y
16908 $ @kbd{rm bar.y}
16909 $ @kbd{fmake}       # FreeBSD make, OpenBSD make
16910 cp bar.x bar.y
16911 cp: cannot stat `bar.x': No such file or directory
16912 *** Error code 1
16913 $ @kbd{tmake}       # Tru64 make
16914 cp ../bar.x bar.y
16915 @end example
16917 It seems the sole solution that would please every @command{make}
16918 implementation is to never rely on @code{VPATH} searches for targets.
16919 In other words, @code{VPATH} should be reserved to unbuilt sources.
16922 @node Single Suffix Rules
16923 @section Single Suffix Rules and Separated Dependencies
16924 @cindex Single Suffix Inference Rule
16925 @cindex Rule, Single Suffix Inference
16926 A @dfn{Single Suffix Rule} is basically a usual suffix (inference) rule
16927 (@samp{.from.to:}), but which @emph{destination} suffix is empty
16928 (@samp{.from:}).
16930 @cindex Separated Dependencies
16931 @dfn{Separated dependencies} simply refers to listing the prerequisite
16932 of a target, without defining a rule.  Usually one can list on the one
16933 hand side, the rules, and on the other hand side, the dependencies.
16935 Solaris @command{make} does not support separated dependencies for
16936 targets defined by single suffix rules:
16938 @example
16939 $ @kbd{cat Makefile}
16940 .SUFFIXES: .in
16941 foo: foo.in
16942 .in:
16943         cp $< $@@
16944 $ @kbd{touch foo.in}
16945 $ @kbd{make}
16946 $ @kbd{ls}
16947 Makefile  foo.in
16948 @end example
16950 @noindent
16951 while @acronym{GNU} Make does:
16953 @example
16954 $ @kbd{gmake}
16955 cp foo.in foo
16956 $ @kbd{ls}
16957 Makefile  foo       foo.in
16958 @end example
16960 Note it works without the @samp{foo: foo.in} dependency.
16962 @example
16963 $ @kbd{cat Makefile}
16964 .SUFFIXES: .in
16965 .in:
16966         cp $< $@@
16967 $ @kbd{make foo}
16968 cp foo.in foo
16969 @end example
16971 @noindent
16972 and it works with double suffix inference rules:
16974 @example
16975 $ @kbd{cat Makefile}
16976 foo.out: foo.in
16977 .SUFFIXES: .in .out
16978 .in.out:
16979         cp $< $@@
16980 $ @kbd{make}
16981 cp foo.in foo.out
16982 @end example
16984 As a result, in such a case, you have to write target rules.
16986 @node Timestamps and Make
16987 @section Timestamp Resolution and Make
16988 @cindex timestamp resolution
16989 Traditionally, file timestamps had 1-second resolution, and
16990 @command{make} used those timestamps to determine whether one file was
16991 newer than the other.  However, many modern file systems have
16992 timestamps with 1-nanosecond resolution.  Some @command{make}
16993 implementations look at the entire timestamp; others ignore the
16994 fractional part, which can lead to incorrect results.  Normally this
16995 is not a problem, but in some extreme cases you may need to use tricks
16996 like @samp{sleep 1} to work around timestamp truncation bugs.
16998 Commands like @samp{cp -p} and @samp{touch -r} typically do not copy
16999 file timestamps to their full resolutions (@pxref{Limitations of Usual
17000 Tools}).  Hence you should be wary of rules like this:
17002 @example
17003 dest: src
17004         cp -p src dest
17005 @end example
17007 as @file{dest} often appears to be older than @file{src} after the
17008 timestamp is truncated, and this can cause @command{make} to do
17009 needless rework the next time it is invoked.  To work around this
17010 problem, you can use a timestamp file, e.g.:
17012 @example
17013 dest-stamp: src
17014         cp -p src dest
17015         date >dest-stamp
17016 @end example
17021 @c ======================================== Portable C and C++ Programming
17023 @node Portable C and C++
17024 @chapter Portable C and C++ Programming
17025 @cindex Portable C and C++ programming
17027 C and C++ programs often use low-level features of the underlying
17028 system, and therefore are often more difficult to make portable to other
17029 platforms.
17031 Several standards have been developed to help make your programs more
17032 portable.  If you write programs with these standards in mind, you can
17033 have greater confidence that your programs work on a wide variety
17034 of systems.  @xref{Standards, , Language Standards Supported by
17035 @acronym{GCC}, gcc, Using the @acronym{GNU} Compiler Collection
17036 (@acronym{GCC})}, for a list of C-related
17037 standards.  Many programs also assume the
17038 @uref{http://www.opengroup.org/susv3, Posix standard}.
17040 Some old code is written to be portable to K&R C, which predates any C
17041 standard.  K&R C compilers are no longer of practical interest, though,
17042 and the rest of section assumes at least C89, the first C standard.
17044 Program portability is a huge topic, and this section can only briefly
17045 introduce common pitfalls.  @xref{System Portability, , Portability
17046 between System Types, standards, @acronym{GNU} Coding Standards}, for
17047 more information.
17049 @menu
17050 * Varieties of Unportability::  How to make your programs unportable
17051 * Integer Overflow::            When integers get too large
17052 * Preprocessor Arithmetic::     @code{#if} expression problems
17053 * Null Pointers::               Properties of null pointers
17054 * Buffer Overruns::             Subscript errors and the like
17055 * Volatile Objects::            @code{volatile} and signals
17056 * Floating Point Portability::  Portable floating-point arithmetic
17057 * Exiting Portably::            Exiting and the exit status
17058 @end menu
17060 @node Varieties of Unportability
17061 @section Varieties of Unportability
17062 @cindex portability
17064 Autoconf tests and ordinary programs often need to test what is allowed
17065 on a system, and therefore they may need to deliberately exceed the
17066 boundaries of what the standards allow, if only to see whether an
17067 optional feature is present.  When you write such a program, you should
17068 keep in mind the difference between constraints, unspecified behavior,
17069 and undefined behavior.
17071 In C, a @dfn{constraint} is a rule that the compiler must enforce.  An
17072 example constraint is that C programs must not declare a bit-field with
17073 negative width.  Tests can therefore reliably assume that programs with
17074 negative-width bit-fields are rejected by a compiler that conforms
17075 to the standard.
17077 @dfn{Unspecified behavior} is valid behavior, where the standard allows
17078 multiple possibilities.  For example, the order of evaluation of
17079 function arguments is unspecified.  Some unspecified behavior is
17080 @dfn{implementation-defined}, i.e., documented by the implementation,
17081 but since Autoconf tests cannot read the documentation they cannot
17082 distinguish between implementation-defined and other unspecified
17083 behavior.  It is common for Autoconf tests to probe implementations to
17084 determine otherwise-unspecified behavior.
17086 @dfn{Undefined behavior} is invalid behavior, where the standard allows
17087 the implementation to do anything it pleases.  For example,
17088 dereferencing a null pointer leads to undefined behavior.  If possible,
17089 test programs should avoid undefined behavior, since a program with
17090 undefined behavior might succeed on a test that should fail.
17092 The above rules apply to programs that are intended to conform to the
17093 standard.  However, strictly-conforming programs are quite rare, since
17094 the standards are so limiting.  A major goal of Autoconf is to support
17095 programs that use implementation features not described by the standard,
17096 and it is fairly common for test programs to violate the above rules, if
17097 the programs work well enough in practice.
17099 @node Integer Overflow
17100 @section Integer Overflow
17101 @cindex integer overflow
17102 @cindex overflow, signed integer
17103 @cindex signed integer overflow
17104 @cindex wraparound arithmetic
17106 In practice many portable C programs assume that signed integer overflow wraps
17107 around reliably using two's complement arithmetic.  Yet the C standard
17108 says that program behavior is undefined on overflow, and in a few cases
17109 C programs do not work on some modern implementations because their
17110 overflows do not wrap around as their authors expected.  Conversely, in
17111 signed integer remainder, the C standard requires overflow
17112 behavior that is commonly not implemented.
17114 @menu
17115 * Integer Overflow Basics::      Why integer overflow is a problem
17116 * Signed Overflow Examples::     Examples of code assuming wraparound
17117 * Optimization and Wraparound::  Optimizations that break uses of wraparound
17118 * Signed Overflow Advice::       Practical advice for signed overflow issues
17119 * Signed Integer Division::      @code{INT_MIN / -1} and @code{INT_MIN % -1}
17120 @end menu
17122 @node Integer Overflow Basics
17123 @subsection Basics of Integer Overflow
17124 @cindex integer overflow
17125 @cindex overflow, signed integer
17126 @cindex signed integer overflow
17127 @cindex wraparound arithmetic
17129 In languages like C, unsigned integer overflow reliably wraps around;
17130 e.g., @code{UINT_MAX + 1} yields zero.
17131 This is guaranteed by the C standard and is
17132 portable in practice, unless you specify aggressive,
17133 nonstandard optimization options
17134 suitable only for special applications.
17136 In contrast, the C standard says that signed integer overflow leads to
17137 undefined behavior where a program can do anything, including dumping
17138 core or overrunning a buffer.  The misbehavior can even precede the
17139 overflow.  Such an overflow can occur during addition, subtraction,
17140 multiplication, division, and left shift.
17142 Despite this requirement of the standard, many C programs and Autoconf
17143 tests assume that signed integer overflow silently wraps around modulo a
17144 power of two, using two's complement arithmetic, so long as you cast the
17145 resulting value to a signed integer type or store it into a signed
17146 integer variable.  If you use conservative optimization flags, such
17147 programs are generally portable to the vast majority of modern
17148 platforms, with a few exceptions discussed later.
17150 For historical reasons the C standard also allows implementations with
17151 ones' complement or signed magnitude arithmetic, but it is safe to
17152 assume two's complement nowadays.
17154 Also, overflow can occur when converting an out-of-range value to a
17155 signed integer type.  Here a standard implementation must define what
17156 happens, but this might include raising an exception.  In practice all
17157 known implementations support silent wraparound in this case, so you need
17158 not worry about other possibilities.
17160 @node Signed Overflow Examples
17161 @subsection Examples of Code Assuming Wraparound Overflow
17162 @cindex integer overflow
17163 @cindex overflow, signed integer
17164 @cindex signed integer overflow
17165 @cindex wraparound arithmetic
17167 There has long been a tension between what the C standard requires for
17168 signed integer overflow, and what C programs commonly assume.  The
17169 standard allows aggressive optimizations based on assumptions that
17170 overflow never occurs, but many practical C programs rely on overflow
17171 wrapping around.  These programs do not conform to the standard, but
17172 they commonly work in practice because compiler writers are
17173 understandably reluctant to implement optimizations that would break
17174 many programs, unless perhaps a user specifies aggressive optimization.
17176 The C Standard says that if a program has signed integer overflow its
17177 behavior is undefined, and the undefined behavior can even precede the
17178 overflow.  To take an extreme example:
17180 @c Inspired by Robert Dewar's example in
17181 @c <http://gcc.gnu.org/ml/gcc/2007-01/msg00038.html> (2007-01-01).
17182 @example
17183 if (password == expected_password)
17184   allow_superuser_privileges ();
17185 else if (counter++ == INT_MAX)
17186   abort ();
17187 else
17188   printf ("%d password mismatches\n", counter);
17189 @end example
17191 @noindent
17192 If the @code{int} variable @code{counter} equals @code{INT_MAX},
17193 @code{counter++} must overflow and the behavior is undefined, so the C
17194 standard allows the compiler to optimize away the test against
17195 @code{INT_MAX} and the @code{abort} call.
17196 Worse, if an earlier bug in the program lets the compiler deduce that
17197 @code{counter == INT_MAX} or that @code{counter} previously overflowed,
17198 the C standard allows the compiler to optimize away the password test
17199 and generate code that allows superuser privileges unconditionally.
17201 Despite this requirement by the standard, it has long been common for C
17202 code to assume wraparound arithmetic after signed overflow, and all
17203 known practical C implementations support some C idioms that assume
17204 wraparound signed arithmetic, even if the idioms do not conform
17205 strictly to the standard.  If your code looks like the following
17206 examples it will almost surely work with real-world compilers.
17208 Here is an example derived from the 7th Edition Unix implementation of
17209 @code{atoi} (1979-01-10):
17211 @example
17212 char *p;
17213 int f, n;
17214 @dots{}
17215 while (*p >= '0' && *p <= '9')
17216   n = n * 10 + *p++ - '0';
17217 return (f ? -n : n);
17218 @end example
17220 @noindent
17221 Even if the input string is in range, on most modern machines this has
17222 signed overflow when computing the most negative integer (the @code{-n}
17223 overflows) or a value near an extreme integer (the first @code{+}
17224 overflows).
17226 Here is another example, derived from the 7th Edition implementation of
17227 @code{rand} (1979-01-10).  Here the programmer expects both
17228 multiplication and addition to wrap on overflow:
17230 @example
17231 static long int randx = 1;
17232 @dots{}
17233 randx = randx * 1103515245 + 12345;
17234 return (randx >> 16) & 077777;
17235 @end example
17237 In the following example, derived from the @acronym{GNU} C Library 2.5
17238 implementation of @code{mktime} (2006-09-09), the code assumes
17239 wraparound arithmetic in @code{+} to detect signed overflow:
17241 @example
17242 time_t t, t1, t2;
17243 int sec_requested, sec_adjustment;
17244 @dots{}
17245 t1 = t + sec_requested;
17246 t2 = t1 + sec_adjustment;
17247 if (((t1 < t) != (sec_requested < 0))
17248     | ((t2 < t1) != (sec_adjustment < 0)))
17249   return -1;
17250 @end example
17252 If your code looks like these examples, it is probably safe even though
17253 it does not strictly conform to the C standard.  This might lead one to
17254 believe that one can generally assume wraparound on overflow, but that
17255 is not always true, as can be seen in the next section.
17257 @node Optimization and Wraparound
17258 @subsection Optimizations That Break Wraparound Arithmetic
17259 @cindex loop induction
17261 Compilers sometimes generate code that is incompatible with wraparound
17262 integer arithmetic.  A simple example is an algebraic simplification: a
17263 compiler might translate @code{(i * 2000) / 1000} to @code{i * 2}
17264 because it assumes that @code{i * 2000} does not overflow.  The
17265 translation is not equivalent to the original when overflow occurs:
17266 e.g., in the typical case of 32-bit signed two's complement wraparound
17267 @code{int}, if @code{i} has type @code{int} and value @code{1073742},
17268 the original expression returns @minus{}2147483 but the optimized
17269 version returns the mathematically correct value 2147484.
17271 More subtly, loop induction optimizations often exploit the undefined
17272 behavior of signed overflow.  Consider the following contrived function
17273 @code{sumc}:
17275 @example
17277 sumc (int lo, int hi)
17279   int sum = 0;
17280   int i;
17281   for (i = lo; i <= hi; i++)
17282     sum ^= i * 53;
17283   return sum;
17285 @end example
17287 @noindent
17288 To avoid multiplying by 53 each time through the loop, an optimizing
17289 compiler might internally transform @code{sumc} to the equivalent of the
17290 following:
17292 @example
17294 transformed_sumc (int lo, int hi)
17296   int sum = 0;
17297   int hic = hi * 53;
17298   int ic;
17299   for (ic = lo * 53; ic <= hic; ic += 53)
17300     sum ^= ic;
17301   return sum;
17303 @end example
17305 @noindent
17306 This transformation is allowed by the C standard, but it is invalid for
17307 wraparound arithmetic when @code{INT_MAX / 53 < hi}, because then the
17308 overflow in computing expressions like @code{hi * 53} can cause the
17309 expression @code{i <= hi} to yield a different value from the
17310 transformed expression @code{ic <= hic}.
17312 For this reason, compilers that use loop induction and similar
17313 techniques often do not support reliable wraparound arithmetic when a
17314 loop induction variable like @code{ic} is involved.  Since loop
17315 induction variables are generated by the compiler, and are not visible
17316 in the source code, it is not always trivial to say whether the problem
17317 affects your code.
17319 Hardly any code actually depends on wraparound arithmetic in cases like
17320 these, so in practice these loop induction optimizations are almost
17321 always useful.  However, edge cases in this area can cause problems.
17322 For example:
17324 @example
17325 int j;
17326 for (j = 1; 0 < j; j *= 2)
17327   test (j);
17328 @end example
17330 @noindent
17331 Here, the loop attempts to iterate through all powers of 2 that
17332 @code{int} can represent, but the C standard allows a compiler to
17333 optimize away the comparison and generate an infinite loop,
17334 under the argument that behavior is undefined on overflow.  As of this
17335 writing this optimization is not done by any production version of
17336 @acronym{GCC} with @option{-O2}, but it might be performed by other
17337 compilers, or by more aggressive @acronym{GCC} optimization options,
17338 and the @acronym{GCC} developers have not decided whether it will
17339 continue to work with @acronym{GCC} and @option{-O2}.
17341 @node Signed Overflow Advice
17342 @subsection Practical Advice for Signed Overflow Issues
17343 @cindex integer overflow
17344 @cindex overflow, signed integer
17345 @cindex signed integer overflow
17346 @cindex wraparound arithmetic
17348 Ideally the safest approach is to avoid signed integer overflow
17349 entirely.  For example, instead of multiplying two signed integers, you
17350 can convert them to unsigned integers, multiply the unsigned values,
17351 then test whether the result is in signed range.
17353 Rewriting code in this way will be inconvenient, though, particularly if
17354 the signed values might be negative.  Also, it may hurt
17355 performance.  Using unsigned arithmetic to check for overflow is
17356 particularly painful to do portably and efficiently when dealing with an
17357 integer type like @code{uid_t} whose width and signedness vary from
17358 platform to platform.
17360 Furthermore, many C applications pervasively assume wraparound behavior
17361 and typically it is not easy to find and remove all these assumptions.
17362 Hence it is often useful to maintain nonstandard code that assumes
17363 wraparound on overflow, instead of rewriting the code.  The rest of this
17364 section attempts to give practical advice for this situation.
17366 If your code wants to detect signed integer overflow in @code{sum = a +
17367 b}, it is generally safe to use an expression like @code{(sum < a) != (b
17368 < 0)}.
17370 If your code uses a signed loop index, make sure that the index cannot
17371 overflow, along with all signed expressions derived from the index.
17372 Here is a contrived example of problematic code with two instances of
17373 overflow.
17375 @example
17376 for (i = INT_MAX - 10; i <= INT_MAX; i++)
17377   if (i + 1 < 0)
17378     @{
17379       report_overflow ();
17380       break;
17381     @}
17382 @end example
17384 @noindent
17385 Because of the two overflows, a compiler might optimize away or
17386 transform the two comparisons in a way that is incompatible with the
17387 wraparound assumption.
17389 If your code uses an expression like @code{(i * 2000) / 1000} and you
17390 actually want the multiplication to wrap around on overflow, use
17391 unsigned arithmetic
17392 to do it, e.g., @code{((int) (i * 2000u)) / 1000}.
17394 If your code assumes wraparound behavior and you want to insulate it
17395 against any @acronym{GCC} optimizations that would fail to support that
17396 behavior, you should use @acronym{GCC}'s @option{-fwrapv} option, which
17397 causes signed overflow to wrap around reliably (except for division and
17398 remainder, as discussed in the next section).
17400 If you need to port to platforms where signed integer overflow does not
17401 reliably wrap around (e.g., due to hardware overflow checking, or to
17402 highly aggressive optimizations), you should consider debugging with
17403 @acronym{GCC}'s @option{-ftrapv} option, which causes signed overflow to
17404 raise an exception.
17406 @node Signed Integer Division
17407 @subsection Signed Integer Division and Integer Overflow
17408 @cindex division, integer
17410 Overflow in signed
17411 integer division is not always harmless: for example, on CPUs of the
17412 i386 family, dividing @code{INT_MIN} by @code{-1} yields a SIGFPE signal
17413 which by default terminates the program.  Worse, taking the remainder
17414 of these two values typically yields the same signal on these CPUs,
17415 even though the C standard requires @code{INT_MIN % -1} to yield zero
17416 because the expression does not overflow.
17418 @node Preprocessor Arithmetic
17419 @section Preprocessor Arithmetic
17420 @cindex preprocessor arithmetic
17422 In C99, preprocessor arithmetic, used for @code{#if} expressions, must
17423 be evaluated as if all signed values are of type @code{intmax_t} and all
17424 unsigned values of type @code{uintmax_t}.  Many compilers are buggy in
17425 this area, though.  For example, as of 2007, Sun C mishandles @code{#if
17426 LLONG_MIN < 0} on a platform with 32-bit @code{long int} and 64-bit
17427 @code{long long int}.  Also, some older preprocessors mishandle
17428 constants ending in @code{LL}.  To work around these problems, you can
17429 compute the value of expressions like @code{LONG_MAX < LLONG_MAX} at
17430 @code{configure}-time rather than at @code{#if}-time.
17432 @node Null Pointers
17433 @section Properties of Null Pointers
17434 @cindex null pointers
17436 Most modern hosts reliably fail when you attempt to dereference a null
17437 pointer.
17439 On almost all modern hosts, null pointers use an all-bits-zero internal
17440 representation, so you can reliably use @code{memset} with 0 to set all
17441 the pointers in an array to null values.
17443 If @code{p} is a null pointer to an object type, the C expression
17444 @code{p + 0} always evaluates to @code{p} on modern hosts, even though
17445 the standard says that it has undefined behavior.
17447 @node Buffer Overruns
17448 @section Buffer Overruns and Subscript Errors
17449 @cindex buffer overruns
17451 Buffer overruns and subscript errors are the most common dangerous
17452 errors in C programs.  They result in undefined behavior because storing
17453 outside an array typically modifies storage that is used by some other
17454 object, and most modern systems lack runtime checks to catch these
17455 errors.  Programs should not rely on buffer overruns being caught.
17457 There is one exception to the usual rule that a portable program cannot
17458 address outside an array.  In C, it is valid to compute the address just
17459 past an object, e.g., @code{&a[N]} where @code{a} has @code{N} elements,
17460 so long as you do not dereference the resulting pointer.  But it is not
17461 valid to compute the address just before an object, e.g., @code{&a[-1]};
17462 nor is it valid to compute two past the end, e.g., @code{&a[N+1]}.  On
17463 most platforms @code{&a[-1] < &a[0] && &a[N] < &a[N+1]}, but this is not
17464 reliable in general, and it is usually easy enough to avoid the
17465 potential portability problem, e.g., by allocating an extra unused array
17466 element at the start or end.
17468 @uref{http://valgrind.org/, Valgrind} can catch many overruns.
17469 @acronym{GCC}
17470 users might also consider using the @option{-fmudflap} option to catch
17471 overruns.
17473 Buffer overruns are usually caused by off-by-one errors, but there are
17474 more subtle ways to get them.
17476 Using @code{int} values to index into an array or compute array sizes
17477 causes problems on typical 64-bit hosts where an array index might
17478 be @math{2^31} or larger.  Index values of type @code{size_t} avoid this
17479 problem, but cannot be negative.  Index values of type @code{ptrdiff_t}
17480 are signed, and are wide enough in practice.
17482 If you add or multiply two numbers to calculate an array size, e.g.,
17483 @code{malloc (x * sizeof y + z)}, havoc ensues if the addition or
17484 multiplication overflows.
17486 Many implementations of the @code{alloca} function silently misbehave
17487 and can generate buffer overflows if given sizes that are too large.
17488 The size limits are implementation dependent, but are at least 4000
17489 bytes on all platforms that we know about.
17491 The standard functions @code{asctime}, @code{asctime_r}, @code{ctime},
17492 @code{ctime_r}, and @code{gets} are prone to buffer overflows, and
17493 portable code should not use them unless the inputs are known to be
17494 within certain limits.  The time-related functions can overflow their
17495 buffers if given timestamps out of range (e.g., a year less than -999
17496 or greater than 9999).  Time-related buffer overflows cannot happen with
17497 recent-enough versions of the @acronym{GNU} C library, but are possible
17498 with other
17499 implementations.  The @code{gets} function is the worst, since it almost
17500 invariably overflows its buffer when presented with an input line larger
17501 than the buffer.
17503 @node Volatile Objects
17504 @section Volatile Objects
17505 @cindex volatile objects
17507 The keyword @code{volatile} is often misunderstood in portable code.
17508 Its use inhibits some memory-access optimizations, but programmers often
17509 wish that it had a different meaning than it actually does.
17511 @code{volatile} was designed for code that accesses special objects like
17512 memory-mapped device registers whose contents spontaneously change.
17513 Such code is inherently low-level, and it is difficult to specify
17514 portably what @code{volatile} means in these cases.  The C standard
17515 says, ``What constitutes an access to an object that has
17516 volatile-qualified type is implementation-defined,'' so in theory each
17517 implementation is supposed to fill in the gap by documenting what
17518 @code{volatile} means for that implementation.  In practice, though,
17519 this documentation is usually absent or incomplete.
17521 One area of confusion is the distinction between objects defined with
17522 volatile types, and volatile lvalues.  From the C standard's point of
17523 view, an object defined with a volatile type has externally visible
17524 behavior.  You can think of such objects as having little oscilloscope
17525 probes attached to them, so that the user can observe some properties of
17526 accesses to them, just as the user can observe data written to output
17527 files.  However, the standard does not make it clear whether users can
17528 observe accesses by volatile lvalues to ordinary objects.  For example:
17530 @example
17531 /* Declare and access a volatile object.
17532    Accesses to X are "visible" to users.  */
17533 static int volatile x;
17534 x = 1;
17536 /* Access two ordinary objects via a volatile lvalue.
17537    It's not clear whether accesses to *P are "visible".  */
17538 int y;
17539 int *z = malloc (sizeof (int));
17540 int volatile *p;
17541 p = &y;
17542 *p = 1;
17543 p = z;
17544 *p = 1;
17545 @end example
17547 Programmers often wish that @code{volatile} meant ``Perform the memory
17548 access here and now, without merging several memory accesses, without
17549 changing the memory word size, and without reordering.''  But the C
17550 standard does not require this.  For objects defined with a volatile
17551 type, accesses must be done before the next sequence point; but
17552 otherwise merging, reordering, and word-size change is allowed.  Worse,
17553 it is not clear from the standard whether volatile lvalues provide more
17554 guarantees in general than nonvolatile lvalues, if the underlying
17555 objects are ordinary.
17557 Even when accessing objects defined with a volatile type,
17558 the C standard allows only
17559 extremely limited signal handlers: the behavior is undefined if a signal
17560 handler reads any nonlocal object, or writes to any nonlocal object
17561 whose type is not @code{sig_atomic_t volatile}, or calls any standard
17562 library function other than @code{abort}, @code{signal}, and (if C99)
17563 @code{_Exit}.  Hence C compilers need not worry about a signal handler
17564 disturbing ordinary computation, unless the computation accesses a
17565 @code{sig_atomic_t volatile} lvalue that is not a local variable.
17566 (There is an obscure exception for accesses via a pointer to a volatile
17567 character, since it may point into part of a @code{sig_atomic_t
17568 volatile} object.)  Posix
17569 adds to the list of library functions callable from a portable signal
17570 handler, but otherwise is like the C standard in this area.
17572 Some C implementations allow memory-access optimizations within each
17573 translation unit, such that actual behavior agrees with the behavior
17574 required by the standard only when calling a function in some other
17575 translation unit, and a signal handler acts like it was called from a
17576 different translation unit.  The C standard hints that in these
17577 implementations, objects referred to by signal handlers ``would require
17578 explicit specification of @code{volatile} storage, as well as other
17579 implementation-defined restrictions.''  But unfortunately even for this
17580 special case these other restrictions are often not documented well.
17581 @xref{Volatiles, , When is a Volatile Object Accessed?, gcc, Using the
17582 @acronym{GNU} Compiler Collection (@acronym{GCC})}, for some
17583 restrictions imposed by @acronym{GCC}.  @xref{Defining Handlers, ,
17584 Defining Signal Handlers, libc, The @acronym{GNU} C Library}, for some
17585 restrictions imposed by the @acronym{GNU} C library.  Restrictions
17586 differ on other platforms.
17588 If possible, it is best to use a signal handler that fits within the
17589 limits imposed by the C and Posix standards.
17591 If this is not practical, you can try the following rules of thumb.  A
17592 signal handler should access only volatile lvalues, preferably lvalues
17593 that refer to objects defined with a volatile type, and should not
17594 assume that the accessed objects have an internally consistent state
17595 if they are larger than a machine word.  Furthermore, installers
17596 should employ compilers and compiler options that are commonly used
17597 for building operating system kernels, because kernels often need more
17598 from @code{volatile} than the C Standard requires, and installers who
17599 compile an application in a similar environment can sometimes benefit
17600 from the extra constraints imposed by kernels on compilers.
17601 Admittedly we are handwaving somewhat here, as there are few
17602 guarantees in this area; the rules of thumb may help to fix some bugs
17603 but there is a good chance that they will not fix them all.
17605 For @code{volatile}, C++ has the same problems that C does.
17606 Multithreaded applications have even more problems with @code{volatile},
17607 but they are beyond the scope of this section.
17609 The bottom line is that using @code{volatile} typically hurts
17610 performance but should not hurt correctness.  In some cases its use
17611 does help correctness, but these cases are often so poorly understood
17612 that all too often adding @code{volatile} to a data structure merely
17613 alleviates some symptoms of a bug while not fixing the bug in general.
17615 @node Floating Point Portability
17616 @section Floating Point Portability
17617 @cindex floating point
17619 Almost all modern systems use IEEE-754 floating point, and it is safe to
17620 assume IEEE-754 in most portable code these days.  For more information,
17621 please see David Goldberg's classic paper
17622 @uref{http://www.validlab.com/goldberg/paper.pdf, What Every Computer
17623 Scientist Should Know About Floating-Point Arithmetic}.
17625 @node Exiting Portably
17626 @section Exiting Portably
17627 @cindex exiting portably
17629 A C or C++ program can exit with status @var{N} by returning
17630 @var{N} from the @code{main} function.  Portable programs are supposed
17631 to exit either with status 0 or @code{EXIT_SUCCESS} to succeed, or with
17632 status @code{EXIT_FAILURE} to fail, but in practice it is portable to
17633 fail by exiting with status 1, and test programs that assume Posix can
17634 fail by exiting with status values from 1 through 255.  Programs on
17635 SunOS 2.0 (1985) through 3.5.2 (1988) incorrectly exited with zero
17636 status when @code{main} returned nonzero, but ancient systems like these
17637 are no longer of practical concern.
17639 A program can also exit with status @var{N} by passing @var{N} to the
17640 @code{exit} function, and a program can fail by calling the @code{abort}
17641 function.  If a program is specialized to just some platforms, it can fail
17642 by calling functions specific to those platforms, e.g., @code{_exit}
17643 (Posix) and @code{_Exit} (C99).  However, like other functions, an exit
17644 function should be declared, typically by including a header.  For
17645 example, if a C program calls @code{exit}, it should include @file{stdlib.h}
17646 either directly or via the default includes (@pxref{Default Includes}).
17648 A program can fail due to undefined behavior such as dereferencing a null
17649 pointer, but this is not recommended as undefined behavior allows an
17650 implementation to do whatever it pleases and this includes exiting
17651 successfully.
17654 @c ================================================== Manual Configuration
17656 @node Manual Configuration
17657 @chapter Manual Configuration
17659 A few kinds of features can't be guessed automatically by running test
17660 programs.  For example, the details of the object-file format, or
17661 special options that need to be passed to the compiler or linker.  You
17662 can check for such features using ad-hoc means, such as having
17663 @command{configure} check the output of the @code{uname} program, or
17664 looking for libraries that are unique to particular systems.  However,
17665 Autoconf provides a uniform method for handling unguessable features.
17667 @menu
17668 * Specifying Names::            Specifying the system type
17669 * Canonicalizing::              Getting the canonical system type
17670 * Using System Type::           What to do with the system type
17671 @end menu
17673 @node Specifying Names
17674 @section Specifying the System Type
17675 @cindex System type
17677 Autoconf-generated
17678 @command{configure} scripts can make decisions based on a canonical name
17679 for the system type, which has the form:
17680 @samp{@var{cpu}-@var{vendor}-@var{os}}, where @var{os} can be
17681 @samp{@var{system}} or @samp{@var{kernel}-@var{system}}
17683 @command{configure} can usually guess the canonical name for the type of
17684 system it's running on.  To do so it runs a script called
17685 @command{config.guess}, which infers the name using the @code{uname}
17686 command or symbols predefined by the C preprocessor.
17688 Alternately, the user can specify the system type with command line
17689 arguments to @command{configure}.  Doing so is necessary when
17690 cross-compiling.  In the most complex case of cross-compiling, three
17691 system types are involved.  The options to specify them are:
17693 @table @option
17694 @item --build=@var{build-type}
17695 the type of system on which the package is being configured and
17696 compiled.  It defaults to the result of running @command{config.guess}.
17698 @item --host=@var{host-type}
17699 the type of system on which the package runs.  By default it is the
17700 same as the build machine.  Specifying it enables the cross-compilation
17701 mode.
17703 @item --target=@var{target-type}
17704 the type of system for which any compiler tools in the package
17705 produce code (rarely needed).  By default, it is the same as host.
17706 @end table
17708 If you mean to override the result of @command{config.guess}, use
17709 @option{--build}, not @option{--host}, since the latter enables
17710 cross-compilation.  For historical reasons,
17711 whenever you specify @option{--host},
17712 be sure to specify @option{--build} too; this will be fixed in the
17713 future.  So, to enter cross-compilation mode, use a command like this
17715 @example
17716 ./configure --build=i686-pc-linux-gnu --host=m68k-coff
17717 @end example
17719 @noindent
17720 Note that if you do not specify @option{--host}, @command{configure}
17721 fails if it can't run the code generated by the specified compiler.  For
17722 example, configuring as follows fails:
17724 @example
17725 ./configure CC=m68k-coff-gcc
17726 @end example
17728 In the future, when cross-compiling Autoconf will @emph{not}
17729 accept tools (compilers, linkers, assemblers) whose name is not
17730 prefixed with the host type.  The only case when this may be
17731 useful is when you really are not cross-compiling, but only
17732 building for a least-common-denominator architecture: an example
17733 is building for @code{i386-pc-linux-gnu} while running on an
17734 @code{i686-pc-linux-gnu} architecture.  In this case, some particular
17735 pairs might be similar enough to let you get away with the system
17736 compilers, but in general the compiler might make bogus assumptions
17737 on the host: if you know what you are doing, please create symbolic
17738 links from the host compiler to the build compiler.
17740 @cindex @command{config.sub}
17741 @command{configure} recognizes short aliases for many system types; for
17742 example, @samp{decstation} can be used instead of
17743 @samp{mips-dec-ultrix4.2}.  @command{configure} runs a script called
17744 @command{config.sub} to canonicalize system type aliases.
17746 This section deliberately omits the description of the obsolete
17747 interface; see @ref{Hosts and Cross-Compilation}.
17750 @node Canonicalizing
17751 @section Getting the Canonical System Type
17752 @cindex System type
17753 @cindex Canonical system type
17755 The following macros make the system type available to @command{configure}
17756 scripts.
17758 @ovindex build_alias
17759 @ovindex host_alias
17760 @ovindex target_alias
17762 The variables @samp{build_alias}, @samp{host_alias}, and
17763 @samp{target_alias} are always exactly the arguments of @option{--build},
17764 @option{--host}, and @option{--target}; in particular, they are left empty
17765 if the user did not use them, even if the corresponding
17766 @code{AC_CANONICAL} macro was run.  Any configure script may use these
17767 variables anywhere.  These are the variables that should be used when in
17768 interaction with the user.
17770 If you need to recognize some special environments based on their system
17771 type, run the following macros to get canonical system names.  These
17772 variables are not set before the macro call.
17774 If you use these macros, you must distribute @command{config.guess} and
17775 @command{config.sub} along with your source code.  @xref{Output}, for
17776 information about the @code{AC_CONFIG_AUX_DIR} macro which you can use
17777 to control in which directory @command{configure} looks for those scripts.
17780 @defmac AC_CANONICAL_BUILD
17781 @acindex{CANONICAL_BUILD}
17782 @ovindex build
17783 @ovindex build_cpu
17784 @ovindex build_vendor
17785 @ovindex build_os
17786 Compute the canonical build-system type variable, @code{build}, and its
17787 three individual parts @code{build_cpu}, @code{build_vendor}, and
17788 @code{build_os}.
17790 If @option{--build} was specified, then @code{build} is the
17791 canonicalization of @code{build_alias} by @command{config.sub},
17792 otherwise it is determined by the shell script @command{config.guess}.
17793 @end defmac
17795 @defmac AC_CANONICAL_HOST
17796 @acindex{CANONICAL_HOST}
17797 @ovindex host
17798 @ovindex host_cpu
17799 @ovindex host_vendor
17800 @ovindex host_os
17801 Compute the canonical host-system type variable, @code{host}, and its
17802 three individual parts @code{host_cpu}, @code{host_vendor}, and
17803 @code{host_os}.
17805 If @option{--host} was specified, then @code{host} is the
17806 canonicalization of @code{host_alias} by @command{config.sub},
17807 otherwise it defaults to @code{build}.
17808 @end defmac
17810 @defmac AC_CANONICAL_TARGET
17811 @acindex{CANONICAL_TARGET}
17812 @ovindex target
17813 @ovindex target_cpu
17814 @ovindex target_vendor
17815 @ovindex target_os
17816 Compute the canonical target-system type variable, @code{target}, and its
17817 three individual parts @code{target_cpu}, @code{target_vendor}, and
17818 @code{target_os}.
17820 If @option{--target} was specified, then @code{target} is the
17821 canonicalization of @code{target_alias} by @command{config.sub},
17822 otherwise it defaults to @code{host}.
17823 @end defmac
17825 Note that there can be artifacts due to the backward compatibility
17826 code.  See @xref{Hosts and Cross-Compilation}, for more.
17828 @node Using System Type
17829 @section Using the System Type
17831 In @file{configure.ac} the system type is generally used by one or more
17832 @code{case} statements to select system-specifics.  Shell wildcards can
17833 be used to match a group of system types.
17835 For example, an extra assembler code object file could be chosen, giving
17836 access to a CPU cycle counter register.  @code{$(CYCLE_OBJ)} in the
17837 following would be used in a makefile to add the object to a
17838 program or library.
17840 @example
17841 case $host in
17842   alpha*-*-*) CYCLE_OBJ=rpcc.o ;;
17843   i?86-*-*)   CYCLE_OBJ=rdtsc.o ;;
17844   *)          CYCLE_OBJ= ;;
17845 esac
17846 AC_SUBST([CYCLE_OBJ])
17847 @end example
17849 @code{AC_CONFIG_LINKS} (@pxref{Configuration Links}) is another good way
17850 to select variant source files, for example optimized code for some
17851 CPUs.  The configured CPU type doesn't always indicate exact CPU types,
17852 so some runtime capability checks may be necessary too.
17854 @example
17855 case $host in
17856   alpha*-*-*)   AC_CONFIG_LINKS([dither.c:alpha/dither.c]) ;;
17857   powerpc*-*-*) AC_CONFIG_LINKS([dither.c:powerpc/dither.c]) ;;
17858   *-*-*)        AC_CONFIG_LINKS([dither.c:generic/dither.c]) ;;
17859 esac
17860 @end example
17862 The host system type can also be used to find cross-compilation tools
17863 with @code{AC_CHECK_TOOL} (@pxref{Generic Programs}).
17865 The above examples all show @samp{$host}, since this is where the code
17866 is going to run.  Only rarely is it necessary to test @samp{$build}
17867 (which is where the build is being done).
17869 Whenever you're tempted to use @samp{$host} it's worth considering
17870 whether some sort of probe would be better.  New system types come along
17871 periodically or previously missing features are added.  Well-written
17872 probes can adapt themselves to such things, but hard-coded lists of
17873 names can't.  Here are some guidelines,
17875 @itemize @bullet
17876 @item
17877 Availability of libraries and library functions should always be checked
17878 by probing.
17879 @item
17880 Variant behavior of system calls is best identified with runtime tests
17881 if possible, but bug workarounds or obscure difficulties might have to
17882 be driven from @samp{$host}.
17883 @item
17884 Assembler code is inevitably highly CPU-specific and is best selected
17885 according to @samp{$host_cpu}.
17886 @item
17887 Assembler variations like underscore prefix on globals or ELF versus
17888 COFF type directives are however best determined by probing, perhaps
17889 even examining the compiler output.
17890 @end itemize
17892 @samp{$target} is for use by a package creating a compiler or similar.
17893 For ordinary packages it's meaningless and should not be used.  It
17894 indicates what the created compiler should generate code for, if it can
17895 cross-compile.  @samp{$target} generally selects various hard-coded CPU
17896 and system conventions, since usually the compiler or tools under
17897 construction themselves determine how the target works.
17900 @c ===================================================== Site Configuration.
17902 @node Site Configuration
17903 @chapter Site Configuration
17905 @command{configure} scripts support several kinds of local configuration
17906 decisions.  There are ways for users to specify where external software
17907 packages are, include or exclude optional features, install programs
17908 under modified names, and set default values for @command{configure}
17909 options.
17911 @menu
17912 * Help Formatting::             Customizing @samp{configure --help}
17913 * External Software::           Working with other optional software
17914 * Package Options::             Selecting optional features
17915 * Pretty Help Strings::         Formatting help string
17916 * Option Checking::             Controlling checking of @command{configure} options
17917 * Site Details::                Configuring site details
17918 * Transforming Names::          Changing program names when installing
17919 * Site Defaults::               Giving @command{configure} local defaults
17920 @end menu
17922 @node Help Formatting
17923 @section Controlling Help Output
17925 Users consult @samp{configure --help} to learn of configuration
17926 decisions specific to your package.  By default, @command{configure}
17927 breaks this output into sections for each type of option; within each
17928 section, help strings appear in the order @file{configure.ac} defines
17929 them:
17931 @example
17932 Optional Features:
17933   @dots{}
17934   --enable-bar            include bar
17936 Optional Packages:
17937   @dots{}
17938   --with-foo              use foo
17939 @end example
17941 @defmac AC_PRESERVE_HELP_ORDER
17942 @acindex{PRESERVE_HELP_ORDER}
17944 Request an alternate @option{--help} format, in which options of all
17945 types appear together, in the order defined.  Call this macro before any
17946 @code{AC_ARG_ENABLE} or @code{AC_ARG_WITH}.
17948 @example
17949 Optional Features and Packages:
17950   @dots{}
17951   --enable-bar            include bar
17952   --with-foo              use foo
17953 @end example
17955 @end defmac
17957 @node External Software
17958 @section Working With External Software
17959 @cindex External software
17961 Some packages require, or can optionally use, other software packages
17962 that are already installed.  The user can give @command{configure}
17963 command line options to specify which such external software to use.
17964 The options have one of these forms:
17966 @c FIXME: Can't use @ovar here, Texinfo 4.0 goes lunatic and emits something
17967 @c awful.
17968 @example
17969 --with-@var{package}[=@var{arg}]
17970 --without-@var{package}
17971 @end example
17973 For example, @option{--with-gnu-ld} means work with the @acronym{GNU} linker
17974 instead of some other linker.  @option{--with-x} means work with The X
17975 Window System.
17977 The user can give an argument by following the package name with
17978 @samp{=} and the argument.  Giving an argument of @samp{no} is for
17979 packages that are used by default; it says to @emph{not} use the
17980 package.  An argument that is neither @samp{yes} nor @samp{no} could
17981 include a name or number of a version of the other package, to specify
17982 more precisely which other package this program is supposed to work
17983 with.  If no argument is given, it defaults to @samp{yes}.
17984 @option{--without-@var{package}} is equivalent to
17985 @option{--with-@var{package}=no}.
17987 Normally @command{configure} scripts complain about
17988 @option{--with-@var{package}} options that they do not support.
17989 @xref{Option Checking}, for details, and for how to override the
17990 defaults.
17992 For each external software package that may be used, @file{configure.ac}
17993 should call @code{AC_ARG_WITH} to detect whether the @command{configure}
17994 user asked to use it.  Whether each package is used or not by default,
17995 and which arguments are valid, is up to you.
17997 @anchor{AC_ARG_WITH}
17998 @defmac AC_ARG_WITH (@var{package}, @var{help-string}, @
17999   @ovar{action-if-given}, @ovar{action-if-not-given})
18000 @acindex{ARG_WITH}
18001 If the user gave @command{configure} the option @option{--with-@var{package}}
18002 or @option{--without-@var{package}}, run shell commands
18003 @var{action-if-given}.  If neither option was given, run shell commands
18004 @var{action-if-not-given}.  The name @var{package} indicates another
18005 software package that this program should work with.  It should consist
18006 only of alphanumeric characters, dashes, and dots.
18008 The option's argument is available to the shell commands
18009 @var{action-if-given} in the shell variable @code{withval}, which is
18010 actually just the value of the shell variable named
18011 @code{with_@var{package}}, with any non-alphanumeric characters in
18012 @var{package} changed into @samp{_}.  You may use that variable instead,
18013 if you wish.
18015 The argument @var{help-string} is a description of the option that
18016 looks like this:
18017 @example
18018   --with-readline         support fancy command line editing
18019 @end example
18021 @noindent
18022 @var{help-string} may be more than one line long, if more detail is
18023 needed.  Just make sure the columns line up in @samp{configure
18024 --help}.  Avoid tabs in the help string.  You'll need to enclose the
18025 help string in @samp{[} and @samp{]} in order to produce the leading
18026 blanks.
18028 You should format your @var{help-string} with the macro
18029 @code{AS_HELP_STRING} (@pxref{Pretty Help Strings}).
18031 The following example shows how to use the @code{AC_ARG_WITH} macro in
18032 a common situation.  You want to let the user decide whether to enable
18033 support for an external library (e.g., the readline library); if the user
18034 specified neither @option{--with-readline} nor @option{--without-readline},
18035 you want to enable support for readline only if the library is available
18036 on the system.
18038 @c FIXME: Remove AS_IF when the problem of AC_REQUIRE within `if' is solved.
18039 @example
18040 AC_ARG_WITH([readline],
18041   [AS_HELP_STRING([--with-readline],
18042     [support fancy command line editing @@<:@@default=check@@:>@@])],
18043   [],
18044   [with_readline=check])
18046 LIBREADLINE=
18047 AS_IF([test "x$with_readline" != xno],
18048   [AC_CHECK_LIB([readline], [main],
18049     [AC_SUBST([LIBREADLINE], ["-lreadline -lncurses"])
18050      AC_DEFINE([HAVE_LIBREADLINE], [1],
18051                [Define if you have libreadline])
18052     ],
18053     [if test "x$with_readline" != xcheck; then
18054        AC_MSG_FAILURE(
18055          [--with-readline was given, but test for readline failed])
18056      fi
18057     ], -lncurses)])
18058 @end example
18060 The next example shows how to use @code{AC_ARG_WITH} to give the user the
18061 possibility to enable support for the readline library, in case it is still
18062 experimental and not well tested, and is therefore disabled by default.
18064 @c FIXME: Remove AS_IF when the problem of AC_REQUIRE within `if' is solved.
18065 @example
18066 AC_ARG_WITH([readline],
18067   [AS_HELP_STRING([--with-readline],
18068     [enable experimental support for readline])],
18069   [],
18070   [with_readline=no])
18072 LIBREADLINE=
18073 AS_IF([test "x$with_readline" != xno],
18074   [AC_CHECK_LIB([readline], [main],
18075     [AC_SUBST([LIBREADLINE], ["-lreadline -lncurses"])
18076      AC_DEFINE([HAVE_LIBREADLINE], [1],
18077                [Define if you have libreadline])
18078     ],
18079     [AC_MSG_FAILURE(
18080        [--with-readline was given, but test for readline failed])],
18081     [-lncurses])])
18082 @end example
18084 The last example shows how to use @code{AC_ARG_WITH} to give the user the
18085 possibility to disable support for the readline library, given that it is
18086 an important feature and that it should be enabled by default.
18088 @c FIXME: Remove AS_IF when the problem of AC_REQUIRE within `if' is solved.
18089 @example
18090 AC_ARG_WITH([readline],
18091   [AS_HELP_STRING([--without-readline],
18092     [disable support for readline])],
18093   [],
18094   [with_readline=yes])
18096 LIBREADLINE=
18097 AS_IF([test "x$with_readline" != xno],
18098   [AC_CHECK_LIB([readline], [main],
18099     [AC_SUBST([LIBREADLINE], ["-lreadline -lncurses"])
18100      AC_DEFINE([HAVE_LIBREADLINE], [1],
18101                [Define if you have libreadline])
18102     ],
18103     [AC_MSG_FAILURE(
18104        [readline test failed (--without-readline to disable)])],
18105     [-lncurses])])
18106 @end example
18108 These three examples can be easily adapted to the case where
18109 @code{AC_ARG_ENABLE} should be preferred to @code{AC_ARG_WITH} (see
18110 @ref{Package Options}).
18111 @end defmac
18113 @node Package Options
18114 @section Choosing Package Options
18115 @cindex Package options
18116 @cindex Options, package
18118 If a software package has optional compile-time features, the user can
18119 give @command{configure} command line options to specify whether to
18120 compile them.  The options have one of these forms:
18122 @c FIXME: Can't use @ovar here, Texinfo 4.0 goes lunatic and emits something
18123 @c awful.
18124 @example
18125 --enable-@var{feature}[=@var{arg}]
18126 --disable-@var{feature}
18127 @end example
18129 These options allow users to choose which optional features to build and
18130 install.  @option{--enable-@var{feature}} options should never make a
18131 feature behave differently or cause one feature to replace another.
18132 They should only cause parts of the program to be built rather than left
18133 out.
18135 The user can give an argument by following the feature name with
18136 @samp{=} and the argument.  Giving an argument of @samp{no} requests
18137 that the feature @emph{not} be made available.  A feature with an
18138 argument looks like @option{--enable-debug=stabs}.  If no argument is
18139 given, it defaults to @samp{yes}.  @option{--disable-@var{feature}} is
18140 equivalent to @option{--enable-@var{feature}=no}.
18142 Normally @command{configure} scripts complain about
18143 @option{--enable-@var{package}} options that they do not support.
18144 @xref{Option Checking}, for details, and for how to override the
18145 defaults.
18147 For each optional feature, @file{configure.ac} should call
18148 @code{AC_ARG_ENABLE} to detect whether the @command{configure} user asked
18149 to include it.  Whether each feature is included or not by default, and
18150 which arguments are valid, is up to you.
18152 @anchor{AC_ARG_ENABLE}
18153 @defmac AC_ARG_ENABLE (@var{feature}, @var{help-string}, @
18154   @ovar{action-if-given}, @ovar{action-if-not-given})
18155 @acindex{ARG_ENABLE}
18156 If the user gave @command{configure} the option
18157 @option{--enable-@var{feature}} or @option{--disable-@var{feature}}, run
18158 shell commands @var{action-if-given}.  If neither option was given, run
18159 shell commands @var{action-if-not-given}.  The name @var{feature}
18160 indicates an optional user-level facility.  It should consist only of
18161 alphanumeric characters, dashes, and dots.
18163 The option's argument is available to the shell commands
18164 @var{action-if-given} in the shell variable @code{enableval}, which is
18165 actually just the value of the shell variable named
18166 @code{enable_@var{feature}}, with any non-alphanumeric characters in
18167 @var{feature} changed into @samp{_}.  You may use that variable instead,
18168 if you wish.  The @var{help-string} argument is like that of
18169 @code{AC_ARG_WITH} (@pxref{External Software}).
18171 You should format your @var{help-string} with the macro
18172 @code{AS_HELP_STRING} (@pxref{Pretty Help Strings}).
18174 See the examples suggested with the definition of @code{AC_ARG_WITH}
18175 (@pxref{External Software}) to get an idea of possible applications of
18176 @code{AC_ARG_ENABLE}.
18177 @end defmac
18179 @node Pretty Help Strings
18180 @section Making Your Help Strings Look Pretty
18181 @cindex Help strings
18183 Properly formatting the @samp{help strings} which are used in
18184 @code{AC_ARG_WITH} (@pxref{External Software}) and @code{AC_ARG_ENABLE}
18185 (@pxref{Package Options}) can be challenging.  Specifically, you want
18186 your own @samp{help strings} to line up in the appropriate columns of
18187 @samp{configure --help} just like the standard Autoconf @samp{help
18188 strings} do.  This is the purpose of the @code{AS_HELP_STRING} macro.
18190 @anchor{AS_HELP_STRING}
18191 @defmac AS_HELP_STRING (@var{left-hand-side}, @var{right-hand-side} @
18192   @dvar{indent-column, 26}, @dvar{wrap-column, 79})
18193 @asindex{HELP_STRING}
18195 Expands into an help string that looks pretty when the user executes
18196 @samp{configure --help}.  It is typically used in @code{AC_ARG_WITH}
18197 (@pxref{External Software}) or @code{AC_ARG_ENABLE} (@pxref{Package
18198 Options}).  The following example makes this clearer.
18200 @example
18201 AC_ARG_WITH([foo],
18202   [AS_HELP_STRING([--with-foo],
18203      [use foo (default is no)])],
18204   [use_foo=$withval],
18205   [use_foo=no])
18206 @end example
18208 Then the last few lines of @samp{configure --help} appear like
18209 this:
18211 @example
18212 --enable and --with options recognized:
18213   --with-foo              use foo (default is no)
18214 @end example
18216 Macro expansion is performed on the first argument.  However, the second
18217 argument of @code{AS_HELP_STRING} is treated as a whitespace separated
18218 list of text to be reformatted, and is not subject to macro expansion.
18219 Since it is not expanded, it should not be double quoted.
18220 @xref{Autoconf Language}, for a more detailed explanation.
18222 The @code{AS_HELP_STRING} macro is particularly helpful when the
18223 @var{left-hand-side} and/or @var{right-hand-side} are composed of macro
18224 arguments, as shown in the following example.  Be aware that
18225 @var{left-hand-side} may not expand to unbalanced quotes,
18226 although quadrigraphs can be used.
18228 @example
18229 AC_DEFUN([MY_ARG_WITH],
18230   [AC_ARG_WITH(m4_translit([[$1]], [_], [-]),
18231      [AS_HELP_STRING([--with-m4_translit([$1], [_], [-])],
18232                      [use $1 (default is $2)])],
18233      [use_[]$1=$withval],
18234      [use_[]$1=$2])])
18235 MY_ARG_WITH([a_b], [no])
18236 @end example
18237 @noindent
18238 Here, the last few lines of @samp{configure --help} will include:
18240 @example
18241 --enable and --with options recognized:
18242   --with-a-b              use a_b (default is no)
18243 @end example
18245 The parameters @var{indent-column} and @var{wrap-column} were introduced
18246 in Autoconf 2.62.  Generally, they should not be specified; they exist
18247 for fine-tuning of the wrapping.
18248 @example
18249 AS_HELP_STRING([--option], [description of option])
18250 @result{}  --option                description of option
18251 AS_HELP_STRING([--option], [description of option], [15], [30])
18252 @result{}  --option     description of
18253 @result{}               option
18254 @end example
18255 @end defmac
18258 @node Option Checking
18259 @section Controlling Checking of @command{configure} Options
18260 @cindex Options, Package
18262 The @command{configure} script checks its command-line options against a
18263 list of known options, like @option{--help} or @option{--config-cache}.
18264 An unknown option ordinarily indicates a mistake by the user and
18265 @command{configure} halts with an error.  However, by default unknown
18266 @option{--with-@var{package}} and @option{--enable-@var{feature}}
18267 options elicit only a warning, to support configuring entire source
18268 trees.
18270 Source trees often contain multiple packages with a top-level
18271 @command{configure} script that uses the @code{AC_CONFIG_SUBDIRS} macro
18272 (@pxref{Subdirectories}).  Because the packages generally support
18273 different @option{--with-@var{package}} and
18274 @option{--enable-@var{feature}} options, the @acronym{GNU} Coding
18275 Standards say they must accept unrecognized options without halting.
18276 Even a warning message is undesirable here, so @code{AC_CONFIG_SUBDIRS}
18277 automatically disables the warnings.
18279 This default behavior may be modified in two ways.  First, the installer
18280 can invoke @code{configure --disable-option-checking} to disable
18281 these warnings, or invoke @code{configure --enable-option-checking=fatal}
18282 options to turn them into fatal errors, respectively.  Second, the
18283 maintainer can use @code{AC_DISABLE_OPTION_CHECKING}.
18285 @defmac AC_DISABLE_OPTION_CHECKING
18286 @acindex{DISABLE_OPTION_CHECKING}
18288 By default, disable warnings related to any unrecognized
18289 @option{--with-@var{package}} or @option{--enable-@var{feature}}
18290 options.  This is implied by @code{AC_CONFIG_SUBDIRS}.
18292 The installer can override this behavior by passing
18293 @option{--enable-option-checking} (enable warnings) or
18294 @option{--enable-option-checking=fatal} (enable errors) to
18295 @command{configure}.
18296 @end defmac
18299 @node Site Details
18300 @section Configuring Site Details
18301 @cindex Site details
18303 Some software packages require complex site-specific information.  Some
18304 examples are host names to use for certain services, company names, and
18305 email addresses to contact.  Since some configuration scripts generated
18306 by Metaconfig ask for such information interactively, people sometimes
18307 wonder how to get that information in Autoconf-generated configuration
18308 scripts, which aren't interactive.
18310 Such site configuration information should be put in a file that is
18311 edited @emph{only by users}, not by programs.  The location of the file
18312 can either be based on the @code{prefix} variable, or be a standard
18313 location such as the user's home directory.  It could even be specified
18314 by an environment variable.  The programs should examine that file at
18315 runtime, rather than at compile time.  Runtime configuration is more
18316 convenient for users and makes the configuration process simpler than
18317 getting the information while configuring.  @xref{Directory Variables, ,
18318 Variables for Installation Directories, standards, @acronym{GNU} Coding
18319 Standards}, for more information on where to put data files.
18321 @node Transforming Names
18322 @section Transforming Program Names When Installing
18323 @cindex Transforming program names
18324 @cindex Program names, transforming
18326 Autoconf supports changing the names of programs when installing them.
18327 In order to use these transformations, @file{configure.ac} must call the
18328 macro @code{AC_ARG_PROGRAM}.
18330 @defmac AC_ARG_PROGRAM
18331 @acindex{ARG_PROGRAM}
18332 @ovindex program_transform_name
18333 Place in output variable @code{program_transform_name} a sequence of
18334 @code{sed} commands for changing the names of installed programs.
18336 If any of the options described below are given to @command{configure},
18337 program names are transformed accordingly.  Otherwise, if
18338 @code{AC_CANONICAL_TARGET} has been called and a @option{--target} value
18339 is given, the target type followed by a dash is used as a prefix.
18340 Otherwise, no program name transformation is done.
18341 @end defmac
18343 @menu
18344 * Transformation Options::      @command{configure} options to transform names
18345 * Transformation Examples::     Sample uses of transforming names
18346 * Transformation Rules::        Makefile uses of transforming names
18347 @end menu
18349 @node Transformation Options
18350 @subsection Transformation Options
18352 You can specify name transformations by giving @command{configure} these
18353 command line options:
18355 @table @option
18356 @item --program-prefix=@var{prefix}
18357 prepend @var{prefix} to the names;
18359 @item --program-suffix=@var{suffix}
18360 append @var{suffix} to the names;
18362 @item --program-transform-name=@var{expression}
18363 perform @code{sed} substitution @var{expression} on the names.
18364 @end table
18366 @node Transformation Examples
18367 @subsection Transformation Examples
18369 These transformations are useful with programs that can be part of a
18370 cross-compilation development environment.  For example, a
18371 cross-assembler running on a Sun 4 configured with
18372 @option{--target=i960-vxworks} is normally installed as
18373 @file{i960-vxworks-as}, rather than @file{as}, which could be confused
18374 with a native Sun 4 assembler.
18376 You can force a program name to begin with @file{g}, if you don't want
18377 @acronym{GNU} programs installed on your system to shadow other programs with
18378 the same name.  For example, if you configure @acronym{GNU} @code{diff} with
18379 @option{--program-prefix=g}, then when you run @samp{make install} it is
18380 installed as @file{/usr/local/bin/gdiff}.
18382 As a more sophisticated example, you could use
18384 @example
18385 --program-transform-name='s/^/g/; s/^gg/g/; s/^gless/less/'
18386 @end example
18387 @noindent
18389 to prepend @samp{g} to most of the program names in a source tree,
18390 excepting those like @code{gdb} that already have one and those like
18391 @code{less} and @code{lesskey} that aren't @acronym{GNU} programs.  (That is
18392 assuming that you have a source tree containing those programs that is
18393 set up to use this feature.)
18395 One way to install multiple versions of some programs simultaneously is
18396 to append a version number to the name of one or both.  For example, if
18397 you want to keep Autoconf version 1 around for awhile, you can configure
18398 Autoconf version 2 using @option{--program-suffix=2} to install the
18399 programs as @file{/usr/local/bin/autoconf2},
18400 @file{/usr/local/bin/autoheader2}, etc.  Nevertheless, pay attention
18401 that only the binaries are renamed, therefore you'd have problems with
18402 the library files which might overlap.
18404 @node Transformation Rules
18405 @subsection Transformation Rules
18407 Here is how to use the variable @code{program_transform_name} in a
18408 @file{Makefile.in}:
18410 @example
18411 PROGRAMS = cp ls rm
18412 transform = @@program_transform_name@@
18413 install:
18414         for p in $(PROGRAMS); do \
18415           $(INSTALL_PROGRAM) $$p $(DESTDIR)$(bindir)/`echo $$p | \
18416                                               sed '$(transform)'`; \
18417         done
18419 uninstall:
18420         for p in $(PROGRAMS); do \
18421           rm -f $(DESTDIR)$(bindir)/`echo $$p | sed '$(transform)'`; \
18422         done
18423 @end example
18425 It is guaranteed that @code{program_transform_name} is never empty, and
18426 that there are no useless separators.  Therefore you may safely embed
18427 @code{program_transform_name} within a sed program using @samp{;}:
18429 @example
18430 transform = @@program_transform_name@@
18431 transform_exe = s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/
18432 @end example
18434 Whether to do the transformations on documentation files (Texinfo or
18435 @code{man}) is a tricky question; there seems to be no perfect answer,
18436 due to the several reasons for name transforming.  Documentation is not
18437 usually particular to a specific architecture, and Texinfo files do not
18438 conflict with system documentation.  But they might conflict with
18439 earlier versions of the same files, and @code{man} pages sometimes do
18440 conflict with system documentation.  As a compromise, it is probably
18441 best to do name transformations on @code{man} pages but not on Texinfo
18442 manuals.
18444 @node Site Defaults
18445 @section Setting Site Defaults
18446 @cindex Site defaults
18448 Autoconf-generated @command{configure} scripts allow your site to provide
18449 default values for some configuration values.  You do this by creating
18450 site- and system-wide initialization files.
18452 @evindex CONFIG_SITE
18453 If the environment variable @code{CONFIG_SITE} is set, @command{configure}
18454 uses its value as the name of a shell script to read.  Otherwise, it
18455 reads the shell script @file{@var{prefix}/share/config.site} if it exists,
18456 then @file{@var{prefix}/etc/config.site} if it exists.  Thus,
18457 settings in machine-specific files override those in machine-independent
18458 ones in case of conflict.
18460 Site files can be arbitrary shell scripts, but only certain kinds of
18461 code are really appropriate to be in them.  Because @command{configure}
18462 reads any cache file after it has read any site files, a site file can
18463 define a default cache file to be shared between all Autoconf-generated
18464 @command{configure} scripts run on that system (@pxref{Cache Files}).  If
18465 you set a default cache file in a site file, it is a good idea to also
18466 set the output variable @code{CC} in that site file, because the cache
18467 file is only valid for a particular compiler, but many systems have
18468 several available.
18470 You can examine or override the value set by a command line option to
18471 @command{configure} in a site file; options set shell variables that have
18472 the same names as the options, with any dashes turned into underscores.
18473 The exceptions are that @option{--without-} and @option{--disable-} options
18474 are like giving the corresponding @option{--with-} or @option{--enable-}
18475 option and the value @samp{no}.  Thus, @option{--cache-file=localcache}
18476 sets the variable @code{cache_file} to the value @samp{localcache};
18477 @option{--enable-warnings=no} or @option{--disable-warnings} sets the variable
18478 @code{enable_warnings} to the value @samp{no}; @option{--prefix=/usr} sets the
18479 variable @code{prefix} to the value @samp{/usr}; etc.
18481 Site files are also good places to set default values for other output
18482 variables, such as @code{CFLAGS}, if you need to give them non-default
18483 values: anything you would normally do, repetitively, on the command
18484 line.  If you use non-default values for @var{prefix} or
18485 @var{exec_prefix} (wherever you locate the site file), you can set them
18486 in the site file if you specify it with the @code{CONFIG_SITE}
18487 environment variable.
18489 You can set some cache values in the site file itself.  Doing this is
18490 useful if you are cross-compiling, where it is impossible to check features
18491 that require running a test program.  You could ``prime the cache'' by
18492 setting those values correctly for that system in
18493 @file{@var{prefix}/etc/config.site}.  To find out the names of the cache
18494 variables you need to set, look for shell variables with @samp{_cv_} in
18495 their names in the affected @command{configure} scripts, or in the Autoconf
18496 M4 source code for those macros.
18498 The cache file is careful to not override any variables set in the site
18499 files.  Similarly, you should not override command-line options in the
18500 site files.  Your code should check that variables such as @code{prefix}
18501 and @code{cache_file} have their default values (as set near the top of
18502 @command{configure}) before changing them.
18504 Here is a sample file @file{/usr/share/local/gnu/share/config.site}.  The
18505 command @samp{configure --prefix=/usr/share/local/gnu} would read this
18506 file (if @code{CONFIG_SITE} is not set to a different file).
18508 @example
18509 # config.site for configure
18511 # Change some defaults.
18512 test "$prefix" = NONE && prefix=/usr/share/local/gnu
18513 test "$exec_prefix" = NONE && exec_prefix=/usr/local/gnu
18514 test "$sharedstatedir" = '$@{prefix@}/com' && sharedstatedir=/var
18515 test "$localstatedir" = '$@{prefix@}/var' && localstatedir=/var
18517 # Give Autoconf 2.x generated configure scripts a shared default
18518 # cache file for feature test results, architecture-specific.
18519 if test "$cache_file" = /dev/null; then
18520   cache_file="$prefix/var/config.cache"
18521   # A cache file is only valid for one C compiler.
18522   CC=gcc
18524 @end example
18526 @cindex Filesystem Hierarchy Standard
18527 @cindex FHS
18529 Another use of @file{config.site} is for priming the directory variables
18530 in a manner consistent with the Filesystem Hierarchy Standard
18531 (@acronym{FHS}).  Once the following file is installed at
18532 @file{/usr/share/config.site}, a user can execute simply
18533 @code{./configure --prefix=/usr} to get all the directories chosen in
18534 the locations recommended by @acronym{FHS}.
18536 @example
18537 # /usr/local/config.site for FHS defaults when installing below /usr,
18538 # and the respective settings were not changed on the command line.
18539 if test "$prefix" = /usr; then
18540   test "$sysconfdir" = '$@{prefix@}/etc' && sysconfdir=/etc
18541   test "$sharedstatedir" = '$@{prefix@}/com' && sharedstatedir=/var
18542   test "$localstatedir" = '$@{prefix@}/var' && localstatedir=/var
18544 @end example
18547 @c ============================================== Running configure Scripts.
18549 @node Running configure Scripts
18550 @chapter Running @command{configure} Scripts
18551 @cindex @command{configure}
18553 Below are instructions on how to configure a package that uses a
18554 @command{configure} script, suitable for inclusion as an @file{INSTALL}
18555 file in the package.  A plain-text version of @file{INSTALL} which you
18556 may use comes with Autoconf.
18558 @menu
18559 * Basic Installation::          Instructions for typical cases
18560 * Compilers and Options::       Selecting compilers and optimization
18561 * Multiple Architectures::      Compiling for multiple architectures at once
18562 * Installation Names::          Installing in different directories
18563 * Optional Features::           Selecting optional features
18564 * Particular Systems::          Particular systems
18565 * System Type::                 Specifying the system type
18566 * Sharing Defaults::            Setting site-wide defaults for @command{configure}
18567 * Defining Variables::          Specifying the compiler etc.
18568 * configure Invocation::        Changing how @command{configure} runs
18569 @end menu
18571 @set autoconf
18572 @include install.texi
18575 @c ============================================== config.status Invocation
18577 @node config.status Invocation
18578 @chapter config.status Invocation
18579 @cindex @command{config.status}
18581 The @command{configure} script creates a file named @file{config.status},
18582 which actually configures, @dfn{instantiates}, the template files.  It
18583 also records the configuration options that were specified when the
18584 package was last configured in case reconfiguring is needed.
18586 Synopsis:
18587 @example
18588 ./config.status @var{option}@dots{} [@var{file}@dots{}]
18589 @end example
18591 It configures the @var{files}; if none are specified, all the templates
18592 are instantiated.  The files must be specified without their
18593 dependencies, as in
18595 @example
18596 ./config.status foobar
18597 @end example
18599 @noindent
18602 @example
18603 ./config.status foobar:foo.in:bar.in
18604 @end example
18606 The supported options are:
18608 @table @option
18609 @item --help
18610 @itemx -h
18611 Print a summary of the command line options, the list of the template
18612 files, and exit.
18614 @item --version
18615 @itemx -V
18616 Print the version number of Autoconf and the configuration settings,
18617 and exit.
18619 @item --silent
18620 @itemx --quiet
18621 @itemx -q
18622 Do not print progress messages.
18624 @item --debug
18625 @itemx -d
18626 Don't remove the temporary files.
18628 @item --file=@var{file}[:@var{template}]
18629 Require that @var{file} be instantiated as if
18630 @samp{AC_CONFIG_FILES(@var{file}:@var{template})} was used.  Both
18631 @var{file} and @var{template} may be @samp{-} in which case the standard
18632 output and/or standard input, respectively, is used.  If a
18633 @var{template} file name is relative, it is first looked for in the build
18634 tree, and then in the source tree.  @xref{Configuration Actions}, for
18635 more details.
18637 This option and the following ones provide one way for separately
18638 distributed packages to share the values computed by @command{configure}.
18639 Doing so can be useful if some of the packages need a superset of the
18640 features that one of them, perhaps a common library, does.  These
18641 options allow a @file{config.status} file to create files other than the
18642 ones that its @file{configure.ac} specifies, so it can be used for a
18643 different package.
18645 @item --header=@var{file}[:@var{template}]
18646 Same as @option{--file} above, but with @samp{AC_CONFIG_HEADERS}.
18648 @item --recheck
18649 Ask @file{config.status} to update itself and exit (no instantiation).
18650 This option is useful if you change @command{configure}, so that the
18651 results of some tests might be different from the previous run.  The
18652 @option{--recheck} option reruns @command{configure} with the same arguments
18653 you used before, plus the @option{--no-create} option, which prevents
18654 @command{configure} from running @file{config.status} and creating
18655 @file{Makefile} and other files, and the @option{--no-recursion} option,
18656 which prevents @command{configure} from running other @command{configure}
18657 scripts in subdirectories.  (This is so other Make rules can
18658 run @file{config.status} when it changes; @pxref{Automatic Remaking},
18659 for an example).
18660 @end table
18662 @file{config.status} checks several optional environment variables that
18663 can alter its behavior:
18665 @defvar CONFIG_SHELL
18666 @evindex CONFIG_SHELL
18667 The shell with which to run @command{configure} for the @option{--recheck}
18668 option.  It must be Bourne-compatible.  The default is a shell that
18669 supports @code{LINENO} if available, and @file{/bin/sh} otherwise.
18670 Invoking @command{configure} by hand bypasses this setting, so you may
18671 need to use a command like @samp{CONFIG_SHELL=/bin/bash /bin/bash ./configure}
18672 to insure that the same shell is used everywhere.  The absolute name of the
18673 shell should be passed.
18674 @end defvar
18676 @defvar CONFIG_STATUS
18677 @evindex CONFIG_STATUS
18678 The file name to use for the shell script that records the
18679 configuration.  The default is @file{./config.status}.  This variable is
18680 useful when one package uses parts of another and the @command{configure}
18681 scripts shouldn't be merged because they are maintained separately.
18682 @end defvar
18684 You can use @file{./config.status} in your makefiles.  For example, in
18685 the dependencies given above (@pxref{Automatic Remaking}),
18686 @file{config.status} is run twice when @file{configure.ac} has changed.
18687 If that bothers you, you can make each run only regenerate the files for
18688 that rule:
18689 @example
18690 @group
18691 config.h: stamp-h
18692 stamp-h: config.h.in config.status
18693         ./config.status config.h
18694         echo > stamp-h
18696 Makefile: Makefile.in config.status
18697         ./config.status Makefile
18698 @end group
18699 @end example
18701 The calling convention of @file{config.status} has changed; see
18702 @ref{Obsolete config.status Use}, for details.
18705 @c =================================================== Obsolete Constructs
18707 @node Obsolete Constructs
18708 @chapter Obsolete Constructs
18709 @cindex Obsolete constructs
18711 Autoconf changes, and throughout the years some constructs have been
18712 obsoleted.  Most of the changes involve the macros, but in some cases
18713 the tools themselves, or even some concepts, are now considered
18714 obsolete.
18716 You may completely skip this chapter if you are new to Autoconf.  Its
18717 intention is mainly to help maintainers updating their packages by
18718 understanding how to move to more modern constructs.
18720 @menu
18721 * Obsolete config.status Use::  Obsolete convention for @command{config.status}
18722 * acconfig Header::             Additional entries in @file{config.h.in}
18723 * autoupdate Invocation::       Automatic update of @file{configure.ac}
18724 * Obsolete Macros::             Backward compatibility macros
18725 * Autoconf 1::                  Tips for upgrading your files
18726 * Autoconf 2.13::               Some fresher tips
18727 @end menu
18729 @node Obsolete config.status Use
18730 @section Obsolete @file{config.status} Invocation
18732 @file{config.status} now supports arguments to specify the files to
18733 instantiate; see @ref{config.status Invocation}, for more details.
18734 Before, environment variables had to be used.
18736 @defvar CONFIG_COMMANDS
18737 @evindex CONFIG_COMMANDS
18738 The tags of the commands to execute.  The default is the arguments given
18739 to @code{AC_OUTPUT} and @code{AC_CONFIG_COMMANDS} in
18740 @file{configure.ac}.
18741 @end defvar
18743 @defvar CONFIG_FILES
18744 @evindex CONFIG_FILES
18745 The files in which to perform @samp{@@@var{variable}@@} substitutions.
18746 The default is the arguments given to @code{AC_OUTPUT} and
18747 @code{AC_CONFIG_FILES} in @file{configure.ac}.
18748 @end defvar
18750 @defvar CONFIG_HEADERS
18751 @evindex CONFIG_HEADERS
18752 The files in which to substitute C @code{#define} statements.  The
18753 default is the arguments given to @code{AC_CONFIG_HEADERS}; if that
18754 macro was not called, @file{config.status} ignores this variable.
18755 @end defvar
18757 @defvar CONFIG_LINKS
18758 @evindex CONFIG_LINKS
18759 The symbolic links to establish.  The default is the arguments given to
18760 @code{AC_CONFIG_LINKS}; if that macro was not called,
18761 @file{config.status} ignores this variable.
18762 @end defvar
18764 In @ref{config.status Invocation}, using this old interface, the example
18765 would be:
18767 @example
18768 @group
18769 config.h: stamp-h
18770 stamp-h: config.h.in config.status
18771         CONFIG_COMMANDS= CONFIG_LINKS= CONFIG_FILES= \
18772           CONFIG_HEADERS=config.h ./config.status
18773         echo > stamp-h
18775 Makefile: Makefile.in config.status
18776         CONFIG_COMMANDS= CONFIG_LINKS= CONFIG_HEADERS= \
18777           CONFIG_FILES=Makefile ./config.status
18778 @end group
18779 @end example
18781 @noindent
18782 (If @file{configure.ac} does not call @code{AC_CONFIG_HEADERS}, there is
18783 no need to set @code{CONFIG_HEADERS} in the @command{make} rules.  Equally
18784 for @code{CONFIG_COMMANDS}, etc.)
18787 @node acconfig Header
18788 @section @file{acconfig.h}
18790 @cindex @file{acconfig.h}
18791 @cindex @file{config.h.top}
18792 @cindex @file{config.h.bot}
18794 In order to produce @file{config.h.in}, @command{autoheader} needs to
18795 build or to find templates for each symbol.  Modern releases of Autoconf
18796 use @code{AH_VERBATIM} and @code{AH_TEMPLATE} (@pxref{Autoheader
18797 Macros}), but in older releases a file, @file{acconfig.h}, contained the
18798 list of needed templates.  @command{autoheader} copied comments and
18799 @code{#define} and @code{#undef} statements from @file{acconfig.h} in
18800 the current directory, if present.  This file used to be mandatory if
18801 you @code{AC_DEFINE} any additional symbols.
18803 Modern releases of Autoconf also provide @code{AH_TOP} and
18804 @code{AH_BOTTOM} if you need to prepend/append some information to
18805 @file{config.h.in}.  Ancient versions of Autoconf had a similar feature:
18806 if @file{./acconfig.h} contains the string @samp{@@TOP@@},
18807 @command{autoheader} copies the lines before the line containing
18808 @samp{@@TOP@@} into the top of the file that it generates.  Similarly,
18809 if @file{./acconfig.h} contains the string @samp{@@BOTTOM@@},
18810 @command{autoheader} copies the lines after that line to the end of the
18811 file it generates.  Either or both of those strings may be omitted.  An
18812 even older alternate way to produce the same effect in ancient versions
18813 of Autoconf is to create the files @file{@var{file}.top} (typically
18814 @file{config.h.top}) and/or @file{@var{file}.bot} in the current
18815 directory.  If they exist, @command{autoheader} copies them to the
18816 beginning and end, respectively, of its output.
18818 In former versions of Autoconf, the files used in preparing a software
18819 package for distribution were:
18820 @example
18821 @group
18822 configure.ac --.   .------> autoconf* -----> configure
18823                +---+
18824 [aclocal.m4] --+   `---.
18825 [acsite.m4] ---'       |
18826                        +--> [autoheader*] -> [config.h.in]
18827 [acconfig.h] ----.     |
18828                  +-----'
18829 [config.h.top] --+
18830 [config.h.bot] --'
18831 @end group
18832 @end example
18834 Using only the @code{AH_} macros, @file{configure.ac} should be
18835 self-contained, and should not depend upon @file{acconfig.h} etc.
18838 @node autoupdate Invocation
18839 @section Using @command{autoupdate} to Modernize @file{configure.ac}
18840 @cindex @command{autoupdate}
18842 The @command{autoupdate} program updates a @file{configure.ac} file that
18843 calls Autoconf macros by their old names to use the current macro names.
18844 In version 2 of Autoconf, most of the macros were renamed to use a more
18845 uniform and descriptive naming scheme.  @xref{Macro Names}, for a
18846 description of the new scheme.  Although the old names still work
18847 (@pxref{Obsolete Macros}, for a list of the old macros and the corresponding
18848 new names), you can make your @file{configure.ac} files more readable
18849 and make it easier to use the current Autoconf documentation if you
18850 update them to use the new macro names.
18852 @evindex SIMPLE_BACKUP_SUFFIX
18853 If given no arguments, @command{autoupdate} updates @file{configure.ac},
18854 backing up the original version with the suffix @file{~} (or the value
18855 of the environment variable @code{SIMPLE_BACKUP_SUFFIX}, if that is
18856 set).  If you give @command{autoupdate} an argument, it reads that file
18857 instead of @file{configure.ac} and writes the updated file to the
18858 standard output.
18860 @noindent
18861 @command{autoupdate} accepts the following options:
18863 @table @option
18864 @item --help
18865 @itemx -h
18866 Print a summary of the command line options and exit.
18868 @item --version
18869 @itemx -V
18870 Print the version number of Autoconf and exit.
18872 @item --verbose
18873 @itemx -v
18874 Report processing steps.
18876 @item --debug
18877 @itemx -d
18878 Don't remove the temporary files.
18880 @item --force
18881 @itemx -f
18882 Force the update even if the file has not changed.  Disregard the cache.
18884 @item --include=@var{dir}
18885 @itemx -I @var{dir}
18886 Also look for input files in @var{dir}.  Multiple invocations accumulate.
18887 Directories are browsed from last to first.
18888 @end table
18890 @node Obsolete Macros
18891 @section Obsolete Macros
18893 Several macros are obsoleted in Autoconf, for various reasons (typically
18894 they failed to quote properly, couldn't be extended for more recent
18895 issues, etc.).  They are still supported, but deprecated: their use
18896 should be avoided.
18898 During the jump from Autoconf version 1 to version 2, most of the
18899 macros were renamed to use a more uniform and descriptive naming scheme,
18900 but their signature did not change.  @xref{Macro Names}, for a
18901 description of the new naming scheme.  Below, if there is just the mapping
18902 from old names to new names for these macros, the reader is invited to
18903 refer to the definition of the new macro for the signature and the
18904 description.
18906 @defmac AC_AIX
18907 @acindex{AIX}
18908 @cvindex _ALL_SOURCE
18909 This macro is a platform-specific subset of
18910 @code{AC_USE_SYSTEM_EXTENSIONS} (@pxref{AC_USE_SYSTEM_EXTENSIONS}).
18911 @end defmac
18913 @defmac AC_ALLOCA
18914 @acindex{ALLOCA}
18915 Replaced by @code{AC_FUNC_ALLOCA} (@pxref{AC_FUNC_ALLOCA}).
18916 @end defmac
18918 @defmac AC_ARG_ARRAY
18919 @acindex{ARG_ARRAY}
18920 Removed because of limited usefulness.
18921 @end defmac
18923 @defmac AC_C_CROSS
18924 @acindex{C_CROSS}
18925 This macro is obsolete; it does nothing.
18926 @end defmac
18928 @defmac AC_C_LONG_DOUBLE
18929 @acindex{C_LONG_DOUBLE}
18930 @cvindex HAVE_LONG_DOUBLE
18931 If the C compiler supports a working @code{long double} type with more
18932 range or precision than the @code{double} type, define
18933 @code{HAVE_LONG_DOUBLE}.
18935 You should use @code{AC_TYPE_LONG_DOUBLE} or
18936 @code{AC_TYPE_LONG_DOUBLE_WIDER} instead.  @xref{Particular Types}.
18937 @end defmac
18939 @defmac AC_CANONICAL_SYSTEM
18940 @acindex{CANONICAL_SYSTEM}
18941 Determine the system type and set output variables to the names of the
18942 canonical system types.  @xref{Canonicalizing}, for details about the
18943 variables this macro sets.
18945 The user is encouraged to use either @code{AC_CANONICAL_BUILD}, or
18946 @code{AC_CANONICAL_HOST}, or @code{AC_CANONICAL_TARGET}, depending on
18947 the needs.  Using @code{AC_CANONICAL_TARGET} is enough to run the two
18948 other macros (@pxref{Canonicalizing}).
18949 @end defmac
18951 @defmac AC_CHAR_UNSIGNED
18952 @acindex{CHAR_UNSIGNED}
18953 Replaced by @code{AC_C_CHAR_UNSIGNED} (@pxref{AC_C_CHAR_UNSIGNED}).
18954 @end defmac
18956 @defmac AC_CHECK_TYPE (@var{type}, @var{default})
18957 @acindex{CHECK_TYPE}
18958 Autoconf, up to 2.13, used to provide this version of
18959 @code{AC_CHECK_TYPE}, deprecated because of its flaws.  First, although
18960 it is a member of the @code{CHECK} clan, it does
18961 more than just checking.  Secondly, missing types are defined
18962 using @code{#define}, not @code{typedef}, and this can lead to
18963 problems in the case of pointer types.
18965 This use of @code{AC_CHECK_TYPE} is obsolete and discouraged; see
18966 @ref{Generic Types}, for the description of the current macro.
18968 If the type @var{type} is not defined, define it to be the C (or C++)
18969 builtin type @var{default}, e.g., @samp{short int} or @samp{unsigned int}.
18971 This macro is equivalent to:
18973 @example
18974 AC_CHECK_TYPE([@var{type}], [],
18975   [AC_DEFINE_UNQUOTED([@var{type}], [@var{default}],
18976      [Define to `@var{default}'
18977       if <sys/types.h> does not define.])])
18978 @end example
18980 In order to keep backward compatibility, the two versions of
18981 @code{AC_CHECK_TYPE} are implemented, selected using these heuristics:
18983 @enumerate
18984 @item
18985 If there are three or four arguments, the modern version is used.
18987 @item
18988 If the second argument appears to be a C or C++ type, then the
18989 obsolete version is used.  This happens if the argument is a C or C++
18990 @emph{builtin} type or a C identifier ending in @samp{_t}, optionally
18991 followed by one of @samp{[(* } and then by a string of zero or more
18992 characters taken from the set @samp{[]()* _a-zA-Z0-9}.
18994 @item
18995 If the second argument is spelled with the alphabet of valid C and C++
18996 types, the user is warned and the modern version is used.
18998 @item
18999 Otherwise, the modern version is used.
19000 @end enumerate
19002 @noindent
19003 You are encouraged either to use a valid builtin type, or to use the
19004 equivalent modern code (see above), or better yet, to use
19005 @code{AC_CHECK_TYPES} together with
19007 @example
19008 #ifndef HAVE_LOFF_T
19009 typedef loff_t off_t;
19010 #endif
19011 @end example
19012 @end defmac
19013 @c end of AC_CHECK_TYPE
19015 @defmac AC_CHECKING (@var{feature-description})
19016 @acindex{CHECKING}
19017 Same as
19019 @example
19020 AC_MSG_NOTICE([checking @var{feature-description}@dots{}]
19021 @end example
19023 @noindent
19024 @xref{AC_MSG_NOTICE}.
19025 @end defmac
19027 @defmac AC_COMPILE_CHECK (@var{echo-text}, @var{includes}, @
19028   @var{function-body}, @var{action-if-true}, @ovar{action-if-false})
19029 @acindex{COMPILE_CHECK}
19030 This is an obsolete version of @code{AC_TRY_COMPILE} itself replaced by
19031 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}), with the
19032 addition that it prints @samp{checking for @var{echo-text}} to the
19033 standard output first, if @var{echo-text} is non-empty.  Use
19034 @code{AC_MSG_CHECKING} and @code{AC_MSG_RESULT} instead to print
19035 messages (@pxref{Printing Messages}).
19036 @end defmac
19038 @defmac AC_CONST
19039 @acindex{CONST}
19040 Replaced by @code{AC_C_CONST} (@pxref{AC_C_CONST}).
19041 @end defmac
19043 @defmac AC_CROSS_CHECK
19044 @acindex{CROSS_CHECK}
19045 Same as @code{AC_C_CROSS}, which is obsolete too, and does nothing
19046 @code{:-)}.
19047 @end defmac
19049 @defmac AC_CYGWIN
19050 @acindex{CYGWIN}
19051 @evindex CYGWIN
19052 Check for the Cygwin environment in which case the shell variable
19053 @code{CYGWIN} is set to @samp{yes}.  Don't use this macro, the dignified
19054 means to check the nature of the host is using @code{AC_CANONICAL_HOST}
19055 (@pxref{Canonicalizing}).  As a matter of fact this macro is defined as:
19057 @example
19058 AC_REQUIRE([AC_CANONICAL_HOST])[]dnl
19059 case $host_os in
19060   *cygwin* ) CYGWIN=yes;;
19061          * ) CYGWIN=no;;
19062 esac
19063 @end example
19065 Beware that the variable @env{CYGWIN} has a special meaning when
19066 running Cygwin, and should not be changed.  That's yet another reason
19067 not to use this macro.
19068 @end defmac
19070 @defmac AC_DECL_SYS_SIGLIST
19071 @acindex{DECL_SYS_SIGLIST}
19072 @cvindex SYS_SIGLIST_DECLARED
19073 Same as:
19075 @example
19076 AC_CHECK_DECLS([sys_siglist], [], [],
19077 [#include <signal.h>
19078 /* NetBSD declares sys_siglist in unistd.h.  */
19079 #ifdef HAVE_UNISTD_H
19080 # include <unistd.h>
19081 #endif
19083 @end example
19085 @noindent
19086 @xref{AC_CHECK_DECLS}.
19087 @end defmac
19089 @defmac AC_DECL_YYTEXT
19090 @acindex{DECL_YYTEXT}
19091 Does nothing, now integrated in @code{AC_PROG_LEX} (@pxref{AC_PROG_LEX}).
19092 @end defmac
19094 @defmac AC_DIR_HEADER
19095 @acindex{DIR_HEADER}
19096 @cvindex DIRENT
19097 @cvindex SYSNDIR
19098 @cvindex SYSDIR
19099 @cvindex NDIR
19100 Like calling @code{AC_FUNC_CLOSEDIR_VOID}
19101 (@pxref{AC_FUNC_CLOSEDIR_VOID}) and @code{AC_HEADER_DIRENT}
19102 (@pxref{AC_HEADER_DIRENT}),
19103 but defines a different set of C preprocessor macros to indicate which
19104 header file is found:
19106 @multitable {@file{sys/ndir.h}} {Old Symbol} {@code{HAVE_SYS_NDIR_H}}
19107 @item Header            @tab Old Symbol     @tab New Symbol
19108 @item @file{dirent.h}   @tab @code{DIRENT}  @tab @code{HAVE_DIRENT_H}
19109 @item @file{sys/ndir.h} @tab @code{SYSNDIR} @tab @code{HAVE_SYS_NDIR_H}
19110 @item @file{sys/dir.h}  @tab @code{SYSDIR}  @tab @code{HAVE_SYS_DIR_H}
19111 @item @file{ndir.h}     @tab @code{NDIR}    @tab @code{HAVE_NDIR_H}
19112 @end multitable
19113 @end defmac
19115 @defmac AC_DYNIX_SEQ
19116 @acindex{DYNIX_SEQ}
19117 If on DYNIX/ptx, add @option{-lseq} to output variable
19118 @code{LIBS}.  This macro used to be defined as
19120 @example
19121 AC_CHECK_LIB([seq], [getmntent], [LIBS="-lseq $LIBS"])
19122 @end example
19124 @noindent
19125 now it is just @code{AC_FUNC_GETMNTENT} (@pxref{AC_FUNC_GETMNTENT}).
19126 @end defmac
19128 @defmac AC_EXEEXT
19129 @acindex{EXEEXT}
19130 @ovindex EXEEXT
19131 Defined the output variable @code{EXEEXT} based on the output of the
19132 compiler, which is now done automatically.  Typically set to empty
19133 string if Posix and @samp{.exe} if a @acronym{DOS} variant.
19134 @end defmac
19136 @defmac AC_EMXOS2
19137 @acindex{EMXOS2}
19138 Similar to @code{AC_CYGWIN} but checks for the EMX environment on OS/2
19139 and sets @code{EMXOS2}.  Don't use this macro, the dignified means to
19140 check the nature of the host is using @code{AC_CANONICAL_HOST}
19141 (@pxref{Canonicalizing}).
19142 @end defmac
19144 @defmac AC_ENABLE (@var{feature}, @var{action-if-given}, @
19145   @ovar{action-if-not-given})
19146 @acindex{ENABLE}
19147 This is an obsolete version of @code{AC_ARG_ENABLE} that does not
19148 support providing a help string (@pxref{AC_ARG_ENABLE}).
19149 @end defmac
19151 @defmac AC_ERROR
19152 @acindex{ERROR}
19153 Replaced by @code{AC_MSG_ERROR} (@pxref{AC_MSG_ERROR}).
19154 @end defmac
19156 @defmac AC_FIND_X
19157 @acindex{FIND_X}
19158 Replaced by @code{AC_PATH_X} (@pxref{AC_PATH_X}).
19159 @end defmac
19161 @defmac AC_FIND_XTRA
19162 @acindex{FIND_XTRA}
19163 Replaced by @code{AC_PATH_XTRA} (@pxref{AC_PATH_XTRA}).
19164 @end defmac
19166 @defmac AC_FOREACH
19167 @acindex{FOREACH}
19168 Replaced by @code{m4_foreach_w} (@pxref{m4_foreach_w}).
19169 @end defmac
19171 @defmac AC_FUNC_CHECK
19172 @acindex{FUNC_CHECK}
19173 Replaced by @code{AC_CHECK_FUNC} (@pxref{AC_CHECK_FUNC}).
19174 @end defmac
19176 @anchor{AC_FUNC_SETVBUF_REVERSED}
19177 @defmac AC_FUNC_SETVBUF_REVERSED
19178 @acindex{FUNC_SETVBUF_REVERSED}
19179 @cvindex SETVBUF_REVERSED
19180 @c @fuindex setvbuf
19181 @prindex @code{setvbuf}
19182 Do nothing.  Formerly, this macro checked whether @code{setvbuf} takes
19183 the buffering type as its second argument and the buffer pointer as the
19184 third, instead of the other way around, and defined
19185 @code{SETVBUF_REVERSED}.  However, the last systems to have the problem
19186 were those based on SVR2, which became obsolete in 1987, and the macro
19187 is no longer needed.
19188 @end defmac
19190 @defmac AC_FUNC_WAIT3
19191 @acindex{FUNC_WAIT3}
19192 @cvindex HAVE_WAIT3
19193 If @code{wait3} is found and fills in the contents of its third argument
19194 (a @samp{struct rusage *}), which @acronym{HP-UX} does not do, define
19195 @code{HAVE_WAIT3}.
19197 These days portable programs should use @code{waitpid}, not
19198 @code{wait3}, as @code{wait3} has been removed from Posix.
19199 @end defmac
19201 @defmac AC_GCC_TRADITIONAL
19202 @acindex{GCC_TRADITIONAL}
19203 Replaced by @code{AC_PROG_GCC_TRADITIONAL} (@pxref{AC_PROG_GCC_TRADITIONAL}).
19204 @end defmac
19206 @defmac AC_GETGROUPS_T
19207 @acindex{GETGROUPS_T}
19208 Replaced by @code{AC_TYPE_GETGROUPS} (@pxref{AC_TYPE_GETGROUPS}).
19209 @end defmac
19211 @defmac AC_GETLOADAVG
19212 @acindex{GETLOADAVG}
19213 Replaced by @code{AC_FUNC_GETLOADAVG} (@pxref{AC_FUNC_GETLOADAVG}).
19214 @end defmac
19216 @defmac AC_GNU_SOURCE
19217 @acindex{GNU_SOURCE}
19218 @cvindex _GNU_SOURCE
19219 This macro is a platform-specific subset of
19220 @code{AC_USE_SYSTEM_EXTENSIONS} (@pxref{AC_USE_SYSTEM_EXTENSIONS}).
19221 @end defmac
19223 @defmac AC_HAVE_FUNCS
19224 @acindex{HAVE_FUNCS}
19225 Replaced by @code{AC_CHECK_FUNCS} (@pxref{AC_CHECK_FUNCS}).
19226 @end defmac
19228 @defmac AC_HAVE_HEADERS
19229 @acindex{HAVE_HEADERS}
19230 Replaced by @code{AC_CHECK_HEADERS} (@pxref{AC_CHECK_HEADERS}).
19231 @end defmac
19233 @defmac AC_HAVE_LIBRARY (@var{library}, @ovar{action-if-found}, @
19234   @ovar{action-if-not-found}, @ovar{other-libraries})
19235 @acindex{HAVE_LIBRARY}
19236 This macro is equivalent to calling @code{AC_CHECK_LIB} with a
19237 @var{function} argument of @code{main}.  In addition, @var{library} can
19238 be written as any of @samp{foo}, @option{-lfoo}, or @samp{libfoo.a}.  In
19239 all of those cases, the compiler is passed @option{-lfoo}.  However,
19240 @var{library} cannot be a shell variable; it must be a literal name.
19241 @xref{AC_CHECK_LIB}.
19242 @end defmac
19244 @defmac AC_HAVE_POUNDBANG
19245 @acindex{HAVE_POUNDBANG}
19246 Replaced by @code{AC_SYS_INTERPRETER} (@pxref{AC_SYS_INTERPRETER}).
19247 @end defmac
19249 @defmac AC_HEADER_CHECK
19250 @acindex{HEADER_CHECK}
19251 Replaced by @code{AC_CHECK_HEADER} (@pxref{AC_CHECK_HEADER}).
19252 @end defmac
19254 @defmac AC_HEADER_EGREP
19255 @acindex{HEADER_EGREP}
19256 Replaced by @code{AC_EGREP_HEADER} (@pxref{AC_EGREP_HEADER}).
19257 @end defmac
19259 @defmac AC_HELP_STRING
19260 @acindex{HELP_STRING}
19261 Replaced by @code{AS_HELP_STRING} (@pxref{AS_HELP_STRING}).
19262 @end defmac
19264 @defmac AC_INIT (@var{unique-file-in-source-dir})
19265 @acindex{INIT}
19266 Formerly @code{AC_INIT} used to have a single argument, and was
19267 equivalent to:
19269 @example
19270 AC_INIT
19271 AC_CONFIG_SRCDIR(@var{unique-file-in-source-dir})
19272 @end example
19273 See @ref{AC_INIT} and @ref{AC_CONFIG_SRCDIR}.
19274 @end defmac
19276 @defmac AC_INLINE
19277 @acindex{INLINE}
19278 Replaced by @code{AC_C_INLINE} (@pxref{AC_C_INLINE}).
19279 @end defmac
19281 @defmac AC_INT_16_BITS
19282 @acindex{INT_16_BITS}
19283 @cvindex INT_16_BITS
19284 If the C type @code{int} is 16 bits wide, define @code{INT_16_BITS}.
19285 Use @samp{AC_CHECK_SIZEOF(int)} instead (@pxref{AC_CHECK_SIZEOF}).
19286 @end defmac
19288 @defmac AC_IRIX_SUN
19289 @acindex{IRIX_SUN}
19290 If on @sc{irix} (Silicon Graphics Unix), add @option{-lsun} to output
19291 @code{LIBS}.  If you were using it to get @code{getmntent}, use
19292 @code{AC_FUNC_GETMNTENT} instead.  If you used it for the NIS versions
19293 of the password and group functions, use @samp{AC_CHECK_LIB(sun,
19294 getpwnam)}.  Up to Autoconf 2.13, it used to be
19296 @example
19297 AC_CHECK_LIB([sun], [getmntent], [LIBS="-lsun $LIBS"])
19298 @end example
19300 @noindent
19301 now it is defined as
19303 @example
19304 AC_FUNC_GETMNTENT
19305 AC_CHECK_LIB([sun], [getpwnam])
19306 @end example
19308 @noindent
19309 See @ref{AC_FUNC_GETMNTENT} and @ref{AC_CHECK_LIB}.
19310 @end defmac
19312 @defmac AC_ISC_POSIX
19313 @acindex{ISC_POSIX}
19314 @ovindex LIBS
19315 This macro adds @option{-lcposix} to output variable @code{LIBS} if
19316 necessary for Posix facilities.  Sun dropped support for the obsolete
19317 @sc{interactive} Systems Corporation Unix on 2006-07-23.  New programs
19318 need not use this macro.  It is implemented as
19319 @code{AC_SEARCH_LIBS([strerror], [cposix])} (@pxref{AC_SEARCH_LIBS}).
19320 @end defmac
19322 @defmac AC_LANG_C
19323 @acindex{LANG_C}
19324 Same as @samp{AC_LANG([C])} (@pxref{AC_LANG}).
19325 @end defmac
19327 @defmac AC_LANG_CPLUSPLUS
19328 @acindex{LANG_CPLUSPLUS}
19329 Same as @samp{AC_LANG([C++])} (@pxref{AC_LANG}).
19330 @end defmac
19332 @defmac AC_LANG_FORTRAN77
19333 @acindex{LANG_FORTRAN77}
19334 Same as @samp{AC_LANG([Fortran 77])} (@pxref{AC_LANG}).
19335 @end defmac
19337 @defmac AC_LANG_RESTORE
19338 @acindex{LANG_RESTORE}
19339 Select the @var{language} that is saved on the top of the stack, as set
19340 by @code{AC_LANG_SAVE}, remove it from the stack, and call
19341 @code{AC_LANG(@var{language})}.  @xref{Language Choice}, for the
19342 preferred way to change languages.
19343 @end defmac
19345 @defmac AC_LANG_SAVE
19346 @acindex{LANG_SAVE}
19347 Remember the current language (as set by @code{AC_LANG}) on a stack.
19348 The current language does not change.  @code{AC_LANG_PUSH} is preferred
19349 (@pxref{AC_LANG_PUSH}).
19350 @end defmac
19352 @defmac AC_LINK_FILES (@var{source}@dots{}, @var{dest}@dots{})
19353 @acindex{LINK_FILES}
19354 This is an obsolete version of @code{AC_CONFIG_LINKS}
19355 (@pxref{AC_CONFIG_LINKS}.  An updated version of:
19357 @example
19358 AC_LINK_FILES(config/$machine.h config/$obj_format.h,
19359               host.h            object.h)
19360 @end example
19362 @noindent
19365 @example
19366 AC_CONFIG_LINKS([host.h:config/$machine.h
19367                 object.h:config/$obj_format.h])
19368 @end example
19369 @end defmac
19371 @defmac AC_LN_S
19372 @acindex{LN_S}
19373 Replaced by @code{AC_PROG_LN_S} (@pxref{AC_PROG_LN_S}).
19374 @end defmac
19376 @defmac AC_LONG_64_BITS
19377 @acindex{LONG_64_BITS}
19378 @cvindex LONG_64_BITS
19379 Define @code{LONG_64_BITS} if the C type @code{long int} is 64 bits wide.
19380 Use the generic macro @samp{AC_CHECK_SIZEOF([long int])} instead
19381 (@pxref{AC_CHECK_SIZEOF}).
19382 @end defmac
19384 @defmac AC_LONG_DOUBLE
19385 @acindex{LONG_DOUBLE}
19386 If the C compiler supports a working @code{long double} type with more
19387 range or precision than the @code{double} type, define
19388 @code{HAVE_LONG_DOUBLE}.
19390 You should use @code{AC_TYPE_LONG_DOUBLE} or
19391 @code{AC_TYPE_LONG_DOUBLE_WIDER} instead.  @xref{Particular Types}.
19392 @end defmac
19394 @defmac AC_LONG_FILE_NAMES
19395 @acindex{LONG_FILE_NAMES}
19396 Replaced by
19397 @example
19398 AC_SYS_LONG_FILE_NAMES
19399 @end example
19400 @noindent
19401 @xref{AC_SYS_LONG_FILE_NAMES}.
19402 @end defmac
19404 @defmac AC_MAJOR_HEADER
19405 @acindex{MAJOR_HEADER}
19406 Replaced by @code{AC_HEADER_MAJOR} (@pxref{AC_HEADER_MAJOR}).
19407 @end defmac
19409 @defmac AC_MEMORY_H
19410 @acindex{MEMORY_H}
19411 @cvindex NEED_MEMORY_H
19412 Used to define @code{NEED_MEMORY_H} if the @code{mem} functions were
19413 defined in @file{memory.h}.  Today it is equivalent to
19414 @samp{AC_CHECK_HEADERS([memory.h])} (@pxref{AC_CHECK_HEADERS}).  Adjust
19415 your code to depend upon
19416 @code{HAVE_MEMORY_H}, not @code{NEED_MEMORY_H}; see @ref{Standard
19417 Symbols}.
19418 @end defmac
19420 @defmac AC_MINGW32
19421 @acindex{MINGW32}
19422 Similar to @code{AC_CYGWIN} but checks for the MinGW compiler
19423 environment and sets @code{MINGW32}.  Don't use this macro, the
19424 dignified means to check the nature of the host is using
19425 @code{AC_CANONICAL_HOST} (@pxref{Canonicalizing}).
19426 @end defmac
19428 @defmac AC_MINIX
19429 @acindex{MINIX}
19430 @cvindex _MINIX
19431 @cvindex _POSIX_SOURCE
19432 @cvindex _POSIX_1_SOURCE
19433 This macro is a platform-specific subset of
19434 @code{AC_USE_SYSTEM_EXTENSIONS} (@pxref{AC_USE_SYSTEM_EXTENSIONS}).
19435 @end defmac
19437 @defmac AC_MINUS_C_MINUS_O
19438 @acindex{MINUS_C_MINUS_O}
19439 Replaced by @code{AC_PROG_CC_C_O} (@pxref{AC_PROG_CC_C_O}).
19440 @end defmac
19442 @defmac AC_MMAP
19443 @acindex{MMAP}
19444 Replaced by @code{AC_FUNC_MMAP} (@pxref{AC_FUNC_MMAP}).
19445 @end defmac
19447 @defmac AC_MODE_T
19448 @acindex{MODE_T}
19449 Replaced by @code{AC_TYPE_MODE_T} (@pxref{AC_TYPE_MODE_T}).
19450 @end defmac
19452 @defmac AC_OBJEXT
19453 @acindex{OBJEXT}
19454 @ovindex OBJEXT
19455 Defined the output variable @code{OBJEXT} based on the output of the
19456 compiler, after .c files have been excluded.  Typically set to @samp{o}
19457 if Posix, @samp{obj} if a @acronym{DOS} variant.
19458 Now the compiler checking macros handle
19459 this automatically.
19460 @end defmac
19462 @defmac AC_OBSOLETE (@var{this-macro-name}, @ovar{suggestion})
19463 @acindex{OBSOLETE}
19464 Make M4 print a message to the standard error output warning that
19465 @var{this-macro-name} is obsolete, and giving the file and line number
19466 where it was called.  @var{this-macro-name} should be the name of the
19467 macro that is calling @code{AC_OBSOLETE}.  If @var{suggestion} is given,
19468 it is printed at the end of the warning message; for example, it can be
19469 a suggestion for what to use instead of @var{this-macro-name}.
19471 For instance
19473 @example
19474 AC_OBSOLETE([$0], [; use AC_CHECK_HEADERS(unistd.h) instead])dnl
19475 @end example
19477 @noindent
19478 You are encouraged to use @code{AU_DEFUN} instead, since it gives better
19479 services to the user (@pxref{AU_DEFUN}).
19480 @end defmac
19482 @defmac AC_OFF_T
19483 @acindex{OFF_T}
19484 Replaced by @code{AC_TYPE_OFF_T} (@pxref{AC_TYPE_OFF_T}).
19485 @end defmac
19487 @defmac AC_OUTPUT (@ovar{file}@dots{}, @ovar{extra-cmds}, @ovar{init-cmds})
19488 @acindex{OUTPUT}
19489 The use of @code{AC_OUTPUT} with arguments is deprecated.  This obsoleted
19490 interface is equivalent to:
19492 @example
19493 @group
19494 AC_CONFIG_FILES(@var{file}@dots{})
19495 AC_CONFIG_COMMANDS([default],
19496                    @var{extra-cmds}, @var{init-cmds})
19497 AC_OUTPUT
19498 @end group
19499 @end example
19501 @noindent
19502 See @ref{AC_CONFIG_FILES}, @ref{AC_CONFIG_COMMANDS}, and @ref{AC_OUTPUT}.
19503 @end defmac
19505 @defmac AC_OUTPUT_COMMANDS (@var{extra-cmds}, @ovar{init-cmds})
19506 @acindex{OUTPUT_COMMANDS}
19507 Specify additional shell commands to run at the end of
19508 @file{config.status}, and shell commands to initialize any variables
19509 from @command{configure}.  This macro may be called multiple times.  It is
19510 obsolete, replaced by @code{AC_CONFIG_COMMANDS} (@pxref{AC_CONFIG_COMMANDS}).
19512 Here is an unrealistic example:
19514 @example
19515 fubar=27
19516 AC_OUTPUT_COMMANDS([echo this is extra $fubar, and so on.],
19517                    [fubar=$fubar])
19518 AC_OUTPUT_COMMANDS([echo this is another, extra, bit],
19519                    [echo init bit])
19520 @end example
19522 Aside from the fact that @code{AC_CONFIG_COMMANDS} requires an
19523 additional key, an important difference is that
19524 @code{AC_OUTPUT_COMMANDS} is quoting its arguments twice, unlike
19525 @code{AC_CONFIG_COMMANDS}.  This means that @code{AC_CONFIG_COMMANDS}
19526 can safely be given macro calls as arguments:
19528 @example
19529 AC_CONFIG_COMMANDS(foo, [my_FOO()])
19530 @end example
19532 @noindent
19533 Conversely, where one level of quoting was enough for literal strings
19534 with @code{AC_OUTPUT_COMMANDS}, you need two with
19535 @code{AC_CONFIG_COMMANDS}.  The following lines are equivalent:
19537 @example
19538 @group
19539 AC_OUTPUT_COMMANDS([echo "Square brackets: []"])
19540 AC_CONFIG_COMMANDS([default], [[echo "Square brackets: []"]])
19541 @end group
19542 @end example
19543 @end defmac
19545 @defmac AC_PID_T
19546 @acindex{PID_T}
19547 Replaced by @code{AC_TYPE_PID_T} (@pxref{AC_TYPE_PID_T}).
19548 @end defmac
19550 @defmac AC_PREFIX
19551 @acindex{PREFIX}
19552 Replaced by @code{AC_PREFIX_PROGRAM} (@pxref{AC_PREFIX_PROGRAM}).
19553 @end defmac
19555 @defmac AC_PROGRAMS_CHECK
19556 @acindex{PROGRAMS_CHECK}
19557 Replaced by @code{AC_CHECK_PROGS} (@pxref{AC_CHECK_PROGS}).
19558 @end defmac
19560 @defmac AC_PROGRAMS_PATH
19561 @acindex{PROGRAMS_PATH}
19562 Replaced by @code{AC_PATH_PROGS} (@pxref{AC_PATH_PROGS}).
19563 @end defmac
19565 @defmac AC_PROGRAM_CHECK
19566 @acindex{PROGRAM_CHECK}
19567 Replaced by @code{AC_CHECK_PROG} (@pxref{AC_CHECK_PROG}).
19568 @end defmac
19570 @defmac AC_PROGRAM_EGREP
19571 @acindex{PROGRAM_EGREP}
19572 Replaced by @code{AC_EGREP_CPP} (@pxref{AC_EGREP_CPP}).
19573 @end defmac
19575 @defmac AC_PROGRAM_PATH
19576 @acindex{PROGRAM_PATH}
19577 Replaced by @code{AC_PATH_PROG} (@pxref{AC_PATH_PROG}).
19578 @end defmac
19580 @defmac AC_REMOTE_TAPE
19581 @acindex{REMOTE_TAPE}
19582 Removed because of limited usefulness.
19583 @end defmac
19585 @defmac AC_RESTARTABLE_SYSCALLS
19586 @acindex{RESTARTABLE_SYSCALLS}
19587 This macro was renamed @code{AC_SYS_RESTARTABLE_SYSCALLS}.  However,
19588 these days portable programs should use @code{sigaction} with
19589 @code{SA_RESTART} if they want restartable system calls.  They should
19590 not rely on @code{HAVE_RESTARTABLE_SYSCALLS}, since nowadays whether a
19591 system call is restartable is a dynamic issue, not a configuration-time
19592 issue.
19593 @end defmac
19595 @defmac AC_RETSIGTYPE
19596 @acindex{RETSIGTYPE}
19597 Replaced by @code{AC_TYPE_SIGNAL} (@pxref{AC_TYPE_SIGNAL}), which itself
19598 is obsolete when assuming C89 or better.
19599 @end defmac
19601 @defmac AC_RSH
19602 @acindex{RSH}
19603 Removed because of limited usefulness.
19604 @end defmac
19606 @defmac AC_SCO_INTL
19607 @acindex{SCO_INTL}
19608 @ovindex LIBS
19609 If on SCO Unix, add @option{-lintl} to output variable @code{LIBS}.  This
19610 macro used to do this:
19612 @example
19613 AC_CHECK_LIB([intl], [strftime], [LIBS="-lintl $LIBS"])
19614 @end example
19616 @noindent
19617 Now it just calls @code{AC_FUNC_STRFTIME} instead (@pxref{AC_FUNC_STRFTIME}).
19618 @end defmac
19620 @defmac AC_SETVBUF_REVERSED
19621 @acindex{SETVBUF_REVERSED}
19622 Replaced by
19623 @example
19624 AC_FUNC_SETVBUF_REVERSED
19625 @end example
19626 @noindent
19627 @xref{AC_FUNC_SETVBUF_REVERSED}.
19628 @end defmac
19630 @defmac AC_SET_MAKE
19631 @acindex{SET_MAKE}
19632 Replaced by @code{AC_PROG_MAKE_SET} (@pxref{AC_PROG_MAKE_SET}).
19633 @end defmac
19635 @defmac AC_SIZEOF_TYPE
19636 @acindex{SIZEOF_TYPE}
19637 Replaced by @code{AC_CHECK_SIZEOF} (@pxref{AC_CHECK_SIZEOF}).
19638 @end defmac
19640 @defmac AC_SIZE_T
19641 @acindex{SIZE_T}
19642 Replaced by @code{AC_TYPE_SIZE_T} (@pxref{AC_TYPE_SIZE_T}).
19643 @end defmac
19645 @defmac AC_STAT_MACROS_BROKEN
19646 @acindex{STAT_MACROS_BROKEN}
19647 Replaced by @code{AC_HEADER_STAT} (@pxref{AC_HEADER_STAT}).
19648 @end defmac
19650 @defmac AC_STDC_HEADERS
19651 @acindex{STDC_HEADERS}
19652 Replaced by @code{AC_HEADER_STDC} (@pxref{AC_HEADER_STDC}).
19653 @end defmac
19655 @defmac AC_STRCOLL
19656 @acindex{STRCOLL}
19657 Replaced by @code{AC_FUNC_STRCOLL} (@pxref{AC_FUNC_STRCOLL}).
19658 @end defmac
19660 @defmac AC_STRUCT_ST_BLKSIZE
19661 @acindex{STRUCT_ST_BLKSIZE}
19662 @cvindex HAVE_STRUCT_STAT_ST_BLKSIZE
19663 @cvindex HAVE_ST_BLKSIZE
19664 If @code{struct stat} contains an @code{st_blksize} member, define
19665 @code{HAVE_STRUCT_STAT_ST_BLKSIZE}.  The former name,
19666 @code{HAVE_ST_BLKSIZE} is to be avoided, as its support will cease in
19667 the future.  This macro is obsoleted, and should be replaced by
19669 @example
19670 AC_CHECK_MEMBERS([struct stat.st_blksize])
19671 @end example
19672 @noindent
19673 @xref{AC_CHECK_MEMBERS}.
19674 @end defmac
19676 @defmac AC_STRUCT_ST_RDEV
19677 @acindex{STRUCT_ST_RDEV}
19678 @cvindex HAVE_ST_RDEV
19679 @cvindex HAVE_STRUCT_STAT_ST_RDEV
19680 If @code{struct stat} contains an @code{st_rdev} member, define
19681 @code{HAVE_STRUCT_STAT_ST_RDEV}.  The former name for this macro,
19682 @code{HAVE_ST_RDEV}, is to be avoided as it will cease to be supported
19683 in the future.  Actually, even the new macro is obsolete and should be
19684 replaced by:
19685 @example
19686 AC_CHECK_MEMBERS([struct stat.st_rdev])
19687 @end example
19688 @noindent
19689 @xref{AC_CHECK_MEMBERS}.
19690 @end defmac
19692 @defmac AC_ST_BLKSIZE
19693 @acindex{ST_BLKSIZE}
19694 Replaced by @code{AC_CHECK_MEMBERS} (@pxref{AC_CHECK_MEMBERS}).
19695 @end defmac
19697 @defmac AC_ST_BLOCKS
19698 @acindex{ST_BLOCKS}
19699 Replaced by @code{AC_STRUCT_ST_BLOCKS} (@pxref{AC_STRUCT_ST_BLOCKS}).
19700 @end defmac
19702 @defmac AC_ST_RDEV
19703 @acindex{ST_RDEV}
19704 Replaced by @code{AC_CHECK_MEMBERS} (@pxref{AC_CHECK_MEMBERS}).
19705 @end defmac
19707 @defmac AC_SYS_RESTARTABLE_SYSCALLS
19708 @acindex{SYS_RESTARTABLE_SYSCALLS}
19709 @cvindex HAVE_RESTARTABLE_SYSCALLS
19710 If the system automatically restarts a system call that is interrupted
19711 by a signal, define @code{HAVE_RESTARTABLE_SYSCALLS}.  This macro does
19712 not check whether system calls are restarted in general---it checks whether a
19713 signal handler installed with @code{signal} (but not @code{sigaction})
19714 causes system calls to be restarted.  It does not check whether system calls
19715 can be restarted when interrupted by signals that have no handler.
19717 These days portable programs should use @code{sigaction} with
19718 @code{SA_RESTART} if they want restartable system calls.  They should
19719 not rely on @code{HAVE_RESTARTABLE_SYSCALLS}, since nowadays whether a
19720 system call is restartable is a dynamic issue, not a configuration-time
19721 issue.
19722 @end defmac
19724 @defmac AC_SYS_SIGLIST_DECLARED
19725 @acindex{SYS_SIGLIST_DECLARED}
19726 This macro was renamed @code{AC_DECL_SYS_SIGLIST}.  However, even that
19727 name is obsolete, as the same functionality is now acheived via
19728 @code{AC_CHECK_DECLS} (@pxref{AC_CHECK_DECLS}).
19729 @end defmac
19731 @defmac AC_TEST_CPP
19732 @acindex{TEST_CPP}
19733 This macro was renamed @code{AC_TRY_CPP}, which in turn was replaced by
19734 @code{AC_PREPROC_IFELSE} (@pxref{AC_PREPROC_IFELSE}).
19735 @end defmac
19737 @defmac AC_TEST_PROGRAM
19738 @acindex{TEST_PROGRAM}
19739 This macro was renamed @code{AC_TRY_RUN}, which in turn was replaced by
19740 @code{AC_RUN_IFELSE} (@pxref{AC_RUN_IFELSE}).
19741 @end defmac
19743 @defmac AC_TIMEZONE
19744 @acindex{TIMEZONE}
19745 Replaced by @code{AC_STRUCT_TIMEZONE} (@pxref{AC_STRUCT_TIMEZONE}).
19746 @end defmac
19748 @defmac AC_TIME_WITH_SYS_TIME
19749 @acindex{TIME_WITH_SYS_TIME}
19750 Replaced by @code{AC_HEADER_TIME} (@pxref{AC_HEADER_TIME}).
19751 @end defmac
19753 @defmac AC_TRY_COMPILE (@var{includes}, @var{function-body}, @
19754   @ovar{action-if-true}, @ovar{action-if-false})
19755 @acindex{TRY_COMPILE}
19756 Same as:
19758 @example
19759 AC_COMPILE_IFELSE(
19760   [AC_LANG_PROGRAM([[@var{includes}]],
19761      [[@var{function-body}]])],
19762   [@var{action-if-true}],
19763   [@var{action-if-false}])
19764 @end example
19766 @noindent
19767 @xref{Running the Compiler}.
19769 This macro double quotes both @var{includes} and @var{function-body}.
19771 For C and C++, @var{includes} is any @code{#include} statements needed
19772 by the code in @var{function-body} (@var{includes} is ignored if
19773 the currently selected language is Fortran or Fortran 77).  The compiler
19774 and compilation flags are determined by the current language
19775 (@pxref{Language Choice}).
19776 @end defmac
19778 @defmac AC_TRY_CPP (@var{input}, @ovar{action-if-true}, @ovar{action-if-false})
19779 @acindex{TRY_CPP}
19780 Same as:
19782 @example
19783 AC_PREPROC_IFELSE(
19784   [AC_LANG_SOURCE([[@var{input}]])],
19785   [@var{action-if-true}],
19786   [@var{action-if-false}])
19787 @end example
19789 @noindent
19790 @xref{Running the Preprocessor}.
19792 This macro double quotes the @var{input}.
19793 @end defmac
19795 @defmac AC_TRY_LINK (@var{includes}, @var{function-body}, @
19796   @ovar{action-if-true}, @ovar{action-if-false})
19797 @acindex{TRY_LINK}
19798 Same as:
19800 @example
19801 AC_LINK_IFELSE(
19802   [AC_LANG_PROGRAM([[@var{includes}]],
19803      [[@var{function-body}]])],
19804   [@var{action-if-true}],
19805   [@var{action-if-false}])
19806 @end example
19808 @noindent
19809 @xref{Running the Compiler}.
19811 This macro double quotes both @var{includes} and @var{function-body}.
19813 Depending on the current language (@pxref{Language Choice}), create a
19814 test program to see whether a function whose body consists of
19815 @var{function-body} can be compiled and linked.  If the file compiles
19816 and links successfully, run shell commands @var{action-if-found},
19817 otherwise run @var{action-if-not-found}.
19819 This macro double quotes both @var{includes} and @var{function-body}.
19821 For C and C++, @var{includes} is any @code{#include} statements needed
19822 by the code in @var{function-body} (@var{includes} is ignored if
19823 the currently selected language is Fortran or Fortran 77).  The compiler
19824 and compilation flags are determined by the current language
19825 (@pxref{Language Choice}), and in addition @code{LDFLAGS} and
19826 @code{LIBS} are used for linking.
19827 @end defmac
19829 @defmac AC_TRY_LINK_FUNC (@var{function}, @ovar{action-if-found}, @
19830   @ovar{action-if-not-found})
19831 @acindex{TRY_LINK_FUNC}
19832 This macro is equivalent to
19833 @example
19834 AC_LINK_IFELSE([AC_LANG_CALL([], [@var{function}])],
19835   [@var{action-if-found}], [@var{action-if-not-found}])
19836 @end example
19837 @noindent
19838 @xref{AC_LINK_IFELSE}.
19839 @end defmac
19841 @defmac AC_TRY_RUN (@var{program}, @ovar{action-if-true}, @
19842   @ovar{action-if-false}, @ovar{action-if-cross-compiling})
19843 @acindex{TRY_RUN}
19844 Same as:
19846 @example
19847 AC_RUN_IFELSE(
19848   [AC_LANG_SOURCE([[@var{program}]])],
19849   [@var{action-if-true}],
19850   [@var{action-if-false}],
19851   [@var{action-if-cross-compiling}])
19852 @end example
19854 @noindent
19855 @xref{Runtime}.
19856 @end defmac
19858 @anchor{AC_TYPE_SIGNAL}
19859 @defmac AC_TYPE_SIGNAL
19860 @acindex{TYPE_SIGNAL}
19861 @cvindex RETSIGTYPE
19862 @hdrindex{signal.h}
19863 If @file{signal.h} declares @code{signal} as returning a pointer to a
19864 function returning @code{void}, define @code{RETSIGTYPE} to be
19865 @code{void}; otherwise, define it to be @code{int}.  These days, it is
19866 portable to assume C89, and that signal handlers return @code{void},
19867 without needing to use this macro or @code{RETSIGTYPE}.
19869 When targetting older K&R C, it is possible to define signal handlers as
19870 returning type @code{RETSIGTYPE}, and omit a return statement:
19872 @example
19873 @group
19874 RETSIGTYPE
19875 hup_handler ()
19877 @dots{}
19879 @end group
19880 @end example
19881 @end defmac
19883 @defmac AC_UID_T
19884 @acindex{UID_T}
19885 Replaced by @code{AC_TYPE_UID_T} (@pxref{AC_TYPE_UID_T}).
19886 @end defmac
19888 @defmac AC_UNISTD_H
19889 @acindex{UNISTD_H}
19890 Same as @samp{AC_CHECK_HEADERS([unistd.h])} (@pxref{AC_CHECK_HEADERS}).
19891 @end defmac
19893 @defmac AC_USG
19894 @acindex{USG}
19895 @cvindex USG
19896 Define @code{USG} if the @acronym{BSD} string functions are defined in
19897 @file{strings.h}.  You should no longer depend upon @code{USG}, but on
19898 @code{HAVE_STRING_H}; see @ref{Standard Symbols}.
19899 @end defmac
19901 @defmac AC_UTIME_NULL
19902 @acindex{UTIME_NULL}
19903 Replaced by @code{AC_FUNC_UTIME_NULL} (@pxref{AC_FUNC_UTIME_NULL}).
19904 @end defmac
19906 @defmac AC_VALIDATE_CACHED_SYSTEM_TUPLE (@ovar{cmd})
19907 @acindex{VALIDATE_CACHED_SYSTEM_TUPLE}
19908 If the cache file is inconsistent with the current host, target and
19909 build system types, it used to execute @var{cmd} or print a default
19910 error message.  This is now handled by default.
19911 @end defmac
19913 @defmac AC_VERBOSE (@var{result-description})
19914 @acindex{VERBOSE}
19915 Replaced by @code{AC_MSG_RESULT} (@pxref{AC_MSG_RESULT}).
19916 @end defmac
19918 @defmac AC_VFORK
19919 @acindex{VFORK}
19920 Replaced by @code{AC_FUNC_FORK} (@pxref{AC_FUNC_FORK}).
19921 @end defmac
19923 @defmac AC_VPRINTF
19924 @acindex{VPRINTF}
19925 Replaced by @code{AC_FUNC_VPRINTF} (@pxref{AC_FUNC_VPRINTF}).
19926 @end defmac
19928 @defmac AC_WAIT3
19929 @acindex{WAIT3}
19930 This macro was renamed @code{AC_FUNC_WAIT3}.  However, these days
19931 portable programs should use @code{waitpid}, not @code{wait3}, as
19932 @code{wait3} has been removed from Posix.
19933 @end defmac
19935 @defmac AC_WARN
19936 @acindex{WARN}
19937 Replaced by @code{AC_MSG_WARN} (@pxref{AC_MSG_WARN}).
19938 @end defmac
19940 @defmac AC_WITH (@var{package}, @var{action-if-given}, @
19941   @ovar{action-if-not-given})
19942 @acindex{WITH}
19943 This is an obsolete version of @code{AC_ARG_WITH} that does not
19944 support providing a help string (@pxref{AC_ARG_WITH}).
19945 @end defmac
19947 @defmac AC_WORDS_BIGENDIAN
19948 @acindex{WORDS_BIGENDIAN}
19949 Replaced by @code{AC_C_BIGENDIAN} (@pxref{AC_C_BIGENDIAN}).
19950 @end defmac
19952 @defmac AC_XENIX_DIR
19953 @acindex{XENIX_DIR}
19954 @ovindex LIBS
19955 This macro used to add @option{-lx} to output variable @code{LIBS} if on
19956 Xenix.  Also, if @file{dirent.h} is being checked for, added
19957 @option{-ldir} to @code{LIBS}.  Now it is merely an alias of
19958 @code{AC_HEADER_DIRENT} instead, plus some code to detect whether
19959 running @sc{xenix} on which you should not depend:
19961 @example
19962 AC_MSG_CHECKING([for Xenix])
19963 AC_EGREP_CPP([yes],
19964 [#if defined M_XENIX && !defined M_UNIX
19965   yes
19966 #endif],
19967              [AC_MSG_RESULT([yes]); XENIX=yes],
19968              [AC_MSG_RESULT([no]); XENIX=])
19969 @end example
19970 @noindent
19971 Don't use this macro, the dignified means to check the nature of the
19972 host is using @code{AC_CANONICAL_HOST} (@pxref{Canonicalizing}).
19973 @end defmac
19975 @defmac AC_YYTEXT_POINTER
19976 @acindex{YYTEXT_POINTER}
19977 This macro was renamed @code{AC_DECL_YYTEXT}, which in turn was
19978 integrated into @code{AC_PROG_LEX} (@pxref{AC_PROG_LEX}).
19979 @end defmac
19981 @node Autoconf 1
19982 @section Upgrading From Version 1
19983 @cindex Upgrading autoconf
19984 @cindex Autoconf upgrading
19986 Autoconf version 2 is mostly backward compatible with version 1.
19987 However, it introduces better ways to do some things, and doesn't
19988 support some of the ugly things in version 1.  So, depending on how
19989 sophisticated your @file{configure.ac} files are, you might have to do
19990 some manual work in order to upgrade to version 2.  This chapter points
19991 out some problems to watch for when upgrading.  Also, perhaps your
19992 @command{configure} scripts could benefit from some of the new features in
19993 version 2; the changes are summarized in the file @file{NEWS} in the
19994 Autoconf distribution.
19996 @menu
19997 * Changed File Names::          Files you might rename
19998 * Changed Makefiles::           New things to put in @file{Makefile.in}
19999 * Changed Macros::              Macro calls you might replace
20000 * Changed Results::             Changes in how to check test results
20001 * Changed Macro Writing::       Better ways to write your own macros
20002 @end menu
20004 @node Changed File Names
20005 @subsection Changed File Names
20007 If you have an @file{aclocal.m4} installed with Autoconf (as opposed to
20008 in a particular package's source directory), you must rename it to
20009 @file{acsite.m4}.  @xref{autoconf Invocation}.
20011 If you distribute @file{install.sh} with your package, rename it to
20012 @file{install-sh} so @command{make} builtin rules don't inadvertently
20013 create a file called @file{install} from it.  @code{AC_PROG_INSTALL}
20014 looks for the script under both names, but it is best to use the new name.
20016 If you were using @file{config.h.top}, @file{config.h.bot}, or
20017 @file{acconfig.h}, you still can, but you have less clutter if you
20018 use the @code{AH_} macros.  @xref{Autoheader Macros}.
20020 @node Changed Makefiles
20021 @subsection Changed Makefiles
20023 Add @samp{@@CFLAGS@@}, @samp{@@CPPFLAGS@@}, and @samp{@@LDFLAGS@@} in
20024 your @file{Makefile.in} files, so they can take advantage of the values
20025 of those variables in the environment when @command{configure} is run.
20026 Doing this isn't necessary, but it's a convenience for users.
20028 Also add @samp{@@configure_input@@} in a comment to each input file for
20029 @code{AC_OUTPUT}, so that the output files contain a comment saying
20030 they were produced by @command{configure}.  Automatically selecting the
20031 right comment syntax for all the kinds of files that people call
20032 @code{AC_OUTPUT} on became too much work.
20034 Add @file{config.log} and @file{config.cache} to the list of files you
20035 remove in @code{distclean} targets.
20037 If you have the following in @file{Makefile.in}:
20039 @example
20040 prefix = /usr/local
20041 exec_prefix = $(prefix)
20042 @end example
20044 @noindent
20045 you must change it to:
20047 @example
20048 prefix = @@prefix@@
20049 exec_prefix = @@exec_prefix@@
20050 @end example
20052 @noindent
20053 The old behavior of replacing those variables without @samp{@@}
20054 characters around them has been removed.
20056 @node Changed Macros
20057 @subsection Changed Macros
20059 Many of the macros were renamed in Autoconf version 2.  You can still
20060 use the old names, but the new ones are clearer, and it's easier to find
20061 the documentation for them.  @xref{Obsolete Macros}, for a table showing the
20062 new names for the old macros.  Use the @command{autoupdate} program to
20063 convert your @file{configure.ac} to using the new macro names.
20064 @xref{autoupdate Invocation}.
20066 Some macros have been superseded by similar ones that do the job better,
20067 but are not call-compatible.  If you get warnings about calling obsolete
20068 macros while running @command{autoconf}, you may safely ignore them, but
20069 your @command{configure} script generally works better if you follow
20070 the advice that is printed about what to replace the obsolete macros with.  In
20071 particular, the mechanism for reporting the results of tests has
20072 changed.  If you were using @command{echo} or @code{AC_VERBOSE} (perhaps
20073 via @code{AC_COMPILE_CHECK}), your @command{configure} script's output
20074 looks better if you switch to @code{AC_MSG_CHECKING} and
20075 @code{AC_MSG_RESULT}.  @xref{Printing Messages}.  Those macros work best
20076 in conjunction with cache variables.  @xref{Caching Results}.
20080 @node Changed Results
20081 @subsection Changed Results
20083 If you were checking the results of previous tests by examining the
20084 shell variable @code{DEFS}, you need to switch to checking the values of
20085 the cache variables for those tests.  @code{DEFS} no longer exists while
20086 @command{configure} is running; it is only created when generating output
20087 files.  This difference from version 1 is because properly quoting the
20088 contents of that variable turned out to be too cumbersome and
20089 inefficient to do every time @code{AC_DEFINE} is called.  @xref{Cache
20090 Variable Names}.
20092 For example, here is a @file{configure.ac} fragment written for Autoconf
20093 version 1:
20095 @example
20096 AC_HAVE_FUNCS(syslog)
20097 case "$DEFS" in
20098 *-DHAVE_SYSLOG*) ;;
20099 *) # syslog is not in the default libraries.  See if it's in some other.
20100   saved_LIBS="$LIBS"
20101   for lib in bsd socket inet; do
20102     AC_CHECKING(for syslog in -l$lib)
20103     LIBS="-l$lib $saved_LIBS"
20104     AC_HAVE_FUNCS(syslog)
20105     case "$DEFS" in
20106     *-DHAVE_SYSLOG*) break ;;
20107     *) ;;
20108     esac
20109     LIBS="$saved_LIBS"
20110   done ;;
20111 esac
20112 @end example
20114 Here is a way to write it for version 2:
20116 @example
20117 AC_CHECK_FUNCS([syslog])
20118 if test $ac_cv_func_syslog = no; then
20119   # syslog is not in the default libraries.  See if it's in some other.
20120   for lib in bsd socket inet; do
20121     AC_CHECK_LIB([$lib], [syslog], [AC_DEFINE([HAVE_SYSLOG])
20122       LIBS="-l$lib $LIBS"; break])
20123   done
20125 @end example
20127 If you were working around bugs in @code{AC_DEFINE_UNQUOTED} by adding
20128 backslashes before quotes, you need to remove them.  It now works
20129 predictably, and does not treat quotes (except back quotes) specially.
20130 @xref{Setting Output Variables}.
20132 All of the Boolean shell variables set by Autoconf macros now use
20133 @samp{yes} for the true value.  Most of them use @samp{no} for false,
20134 though for backward compatibility some use the empty string instead.  If
20135 you were relying on a shell variable being set to something like 1 or
20136 @samp{t} for true, you need to change your tests.
20138 @node Changed Macro Writing
20139 @subsection Changed Macro Writing
20141 When defining your own macros, you should now use @code{AC_DEFUN}
20142 instead of @code{define}.  @code{AC_DEFUN} automatically calls
20143 @code{AC_PROVIDE} and ensures that macros called via @code{AC_REQUIRE}
20144 do not interrupt other macros, to prevent nested @samp{checking@dots{}}
20145 messages on the screen.  There's no actual harm in continuing to use the
20146 older way, but it's less convenient and attractive.  @xref{Macro
20147 Definitions}.
20149 You probably looked at the macros that came with Autoconf as a guide for
20150 how to do things.  It would be a good idea to take a look at the new
20151 versions of them, as the style is somewhat improved and they take
20152 advantage of some new features.
20154 If you were doing tricky things with undocumented Autoconf internals
20155 (macros, variables, diversions), check whether you need to change
20156 anything to account for changes that have been made.  Perhaps you can
20157 even use an officially supported technique in version 2 instead of
20158 kludging.  Or perhaps not.
20160 To speed up your locally written feature tests, add caching to them.
20161 See whether any of your tests are of general enough usefulness to
20162 encapsulate them into macros that you can share.
20165 @node Autoconf 2.13
20166 @section Upgrading From Version 2.13
20167 @cindex Upgrading autoconf
20168 @cindex Autoconf upgrading
20170 The introduction of the previous section (@pxref{Autoconf 1}) perfectly
20171 suits this section@enddots{}
20173 @quotation
20174 Autoconf version 2.50 is mostly backward compatible with version 2.13.
20175 However, it introduces better ways to do some things, and doesn't
20176 support some of the ugly things in version 2.13.  So, depending on how
20177 sophisticated your @file{configure.ac} files are, you might have to do
20178 some manual work in order to upgrade to version 2.50.  This chapter
20179 points out some problems to watch for when upgrading.  Also, perhaps
20180 your @command{configure} scripts could benefit from some of the new
20181 features in version 2.50; the changes are summarized in the file
20182 @file{NEWS} in the Autoconf distribution.
20183 @end quotation
20185 @menu
20186 * Changed Quotation::           Broken code which used to work
20187 * New Macros::                  Interaction with foreign macros
20188 * Hosts and Cross-Compilation::  Bugward compatibility kludges
20189 * AC_LIBOBJ vs LIBOBJS::        LIBOBJS is a forbidden token
20190 * AC_FOO_IFELSE vs AC_TRY_FOO::  A more generic scheme for testing sources
20191 @end menu
20193 @node Changed Quotation
20194 @subsection Changed Quotation
20196 The most important changes are invisible to you: the implementation of
20197 most macros have completely changed.  This allowed more factorization of
20198 the code, better error messages, a higher uniformity of the user's
20199 interface etc.  Unfortunately, as a side effect, some construct which
20200 used to (miraculously) work might break starting with Autoconf 2.50.
20201 The most common culprit is bad quotation.
20203 For instance, in the following example, the message is not properly
20204 quoted:
20206 @example
20207 AC_INIT
20208 AC_CHECK_HEADERS(foo.h, ,
20209   AC_MSG_ERROR(cannot find foo.h, bailing out))
20210 AC_OUTPUT
20211 @end example
20213 @noindent
20214 Autoconf 2.13 simply ignores it:
20216 @example
20217 $ @kbd{autoconf-2.13; ./configure --silent}
20218 creating cache ./config.cache
20219 configure: error: cannot find foo.h
20221 @end example
20223 @noindent
20224 while Autoconf 2.50 produces a broken @file{configure}:
20226 @example
20227 $ @kbd{autoconf-2.50; ./configure --silent}
20228 configure: error: cannot find foo.h
20229 ./configure: exit: bad non-numeric arg `bailing'
20230 ./configure: exit: bad non-numeric arg `bailing'
20232 @end example
20234 The message needs to be quoted, and the @code{AC_MSG_ERROR} invocation
20235 too!
20237 @example
20238 AC_INIT([Example], [1.0], [bug-example@@example.org])
20239 AC_CHECK_HEADERS([foo.h], [],
20240   [AC_MSG_ERROR([cannot find foo.h, bailing out])])
20241 AC_OUTPUT
20242 @end example
20244 Many many (and many more) Autoconf macros were lacking proper quotation,
20245 including no less than@dots{} @code{AC_DEFUN} itself!
20247 @example
20248 $ @kbd{cat configure.in}
20249 AC_DEFUN([AC_PROG_INSTALL],
20250 [# My own much better version
20252 AC_INIT
20253 AC_PROG_INSTALL
20254 AC_OUTPUT
20255 $ @kbd{autoconf-2.13}
20256 autoconf: Undefined macros:
20257 ***BUG in Autoconf--please report*** AC_FD_MSG
20258 ***BUG in Autoconf--please report*** AC_EPI
20259 configure.in:1:AC_DEFUN([AC_PROG_INSTALL],
20260 configure.in:5:AC_PROG_INSTALL
20261 $ @kbd{autoconf-2.50}
20263 @end example
20266 @node New Macros
20267 @subsection New Macros
20269 @cindex undefined macro
20270 @cindex @code{_m4_divert_diversion}
20272 While Autoconf was relatively dormant in the late 1990s, Automake
20273 provided Autoconf-like macros for a while.  Starting with Autoconf 2.50
20274 in 2001, Autoconf provided
20275 versions of these macros, integrated in the @code{AC_} namespace,
20276 instead of @code{AM_}.  But in order to ease the upgrading via
20277 @command{autoupdate}, bindings to such @code{AM_} macros are provided.
20279 Unfortunately older versions of Automake (e.g., Automake 1.4)
20280 did not quote the names of these macros.
20281 Therefore, when @command{m4} finds something like
20282 @samp{AC_DEFUN(AM_TYPE_PTRDIFF_T, @dots{})} in @file{aclocal.m4},
20283 @code{AM_TYPE_PTRDIFF_T} is
20284 expanded, replaced with its Autoconf definition.
20286 Fortunately Autoconf catches pre-@code{AC_INIT} expansions, and
20287 complains, in its own words:
20289 @example
20290 $ @kbd{cat configure.ac}
20291 AC_INIT([Example], [1.0], [bug-example@@example.org])
20292 AM_TYPE_PTRDIFF_T
20293 $ @kbd{aclocal-1.4}
20294 $ @kbd{autoconf}
20295 aclocal.m4:17: error: m4_defn: undefined macro: _m4_divert_diversion
20296 aclocal.m4:17: the top level
20297 autom4te: m4 failed with exit status: 1
20299 @end example
20301 Modern versions of Automake no longer define most of these
20302 macros, and properly quote the names of the remaining macros.
20303 If you must use an old Automake, do not depend upon macros from Automake
20304 as it is simply not its job
20305 to provide macros (but the one it requires itself):
20307 @example
20308 $ @kbd{cat configure.ac}
20309 AC_INIT([Example], [1.0], [bug-example@@example.org])
20310 AM_TYPE_PTRDIFF_T
20311 $ @kbd{rm aclocal.m4}
20312 $ @kbd{autoupdate}
20313 autoupdate: `configure.ac' is updated
20314 $ @kbd{cat configure.ac}
20315 AC_INIT([Example], [1.0], [bug-example@@example.org])
20316 AC_CHECK_TYPES([ptrdiff_t])
20317 $ @kbd{aclocal-1.4}
20318 $ @kbd{autoconf}
20320 @end example
20323 @node Hosts and Cross-Compilation
20324 @subsection Hosts and Cross-Compilation
20325 @cindex Cross compilation
20327 Based on the experience of compiler writers, and after long public
20328 debates, many aspects of the cross-compilation chain have changed:
20330 @itemize @minus
20331 @item
20332 the relationship between the build, host, and target architecture types,
20334 @item
20335 the command line interface for specifying them to @command{configure},
20337 @item
20338 the variables defined in @command{configure},
20340 @item
20341 the enabling of cross-compilation mode.
20342 @end itemize
20344 @sp 1
20346 The relationship between build, host, and target have been cleaned up:
20347 the chain of default is now simply: target defaults to host, host to
20348 build, and build to the result of @command{config.guess}.  Nevertheless,
20349 in order to ease the transition from 2.13 to 2.50, the following
20350 transition scheme is implemented.  @emph{Do not rely on it}, as it will
20351 be completely disabled in a couple of releases (we cannot keep it, as it
20352 proves to cause more problems than it cures).
20354 They all default to the result of running @command{config.guess}, unless
20355 you specify either @option{--build} or @option{--host}.  In this case,
20356 the default becomes the system type you specified.  If you specify both,
20357 and they're different, @command{configure} enters cross compilation
20358 mode, so it doesn't run any tests that require execution.
20360 Hint: if you mean to override the result of @command{config.guess},
20361 prefer @option{--build} over @option{--host}.  In the future,
20362 @option{--host} will not override the name of the build system type.
20363 Whenever you specify @option{--host}, be sure to specify @option{--build}
20364 too.
20366 @sp 1
20368 For backward compatibility, @command{configure} accepts a system
20369 type as an option by itself.  Such an option overrides the
20370 defaults for build, host, and target system types.  The following
20371 configure statement configures a cross toolchain that runs on
20372 Net@acronym{BSD}/alpha but generates code for @acronym{GNU} Hurd/sparc,
20373 which is also the build platform.
20375 @example
20376 ./configure --host=alpha-netbsd sparc-gnu
20377 @end example
20379 @sp 1
20381 In Autoconf 2.13 and before, the variables @code{build}, @code{host},
20382 and @code{target} had a different semantics before and after the
20383 invocation of @code{AC_CANONICAL_BUILD} etc.  Now, the argument of
20384 @option{--build} is strictly copied into @code{build_alias}, and is left
20385 empty otherwise.  After the @code{AC_CANONICAL_BUILD}, @code{build} is
20386 set to the canonicalized build type.  To ease the transition, before,
20387 its contents is the same as that of @code{build_alias}.  Do @emph{not}
20388 rely on this broken feature.
20390 For consistency with the backward compatibility scheme exposed above,
20391 when @option{--host} is specified but @option{--build} isn't, the build
20392 system is assumed to be the same as @option{--host}, and
20393 @samp{build_alias} is set to that value.  Eventually, this
20394 historically incorrect behavior will go away.
20396 @sp 1
20398 The former scheme to enable cross-compilation proved to cause more harm
20399 than good, in particular, it used to be triggered too easily, leaving
20400 regular end users puzzled in front of cryptic error messages.
20401 @command{configure} could even enter cross-compilation mode only
20402 because the compiler was not functional.  This is mainly because
20403 @command{configure} used to try to detect cross-compilation, instead of
20404 waiting for an explicit flag from the user.
20406 Now, @command{configure} enters cross-compilation mode if and only if
20407 @option{--host} is passed.
20409 That's the short documentation.  To ease the transition between 2.13 and
20410 its successors, a more complicated scheme is implemented.  @emph{Do not
20411 rely on the following}, as it will be removed in the near future.
20413 If you specify @option{--host}, but not @option{--build}, when
20414 @command{configure} performs the first compiler test it tries to run
20415 an executable produced by the compiler.  If the execution fails, it
20416 enters cross-compilation mode.  This is fragile.  Moreover, by the time
20417 the compiler test is performed, it may be too late to modify the
20418 build-system type: other tests may have already been performed.
20419 Therefore, whenever you specify @option{--host}, be sure to specify
20420 @option{--build} too.
20422 @example
20423 ./configure --build=i686-pc-linux-gnu --host=m68k-coff
20424 @end example
20426 @noindent
20427 enters cross-compilation mode.  The former interface, which
20428 consisted in setting the compiler to a cross-compiler without informing
20429 @command{configure} is obsolete.  For instance, @command{configure}
20430 fails if it can't run the code generated by the specified compiler if you
20431 configure as follows:
20433 @example
20434 ./configure CC=m68k-coff-gcc
20435 @end example
20438 @node AC_LIBOBJ vs LIBOBJS
20439 @subsection @code{AC_LIBOBJ} vs.@: @code{LIBOBJS}
20441 Up to Autoconf 2.13, the replacement of functions was triggered via the
20442 variable @code{LIBOBJS}.  Since Autoconf 2.50, the macro
20443 @code{AC_LIBOBJ} should be used instead (@pxref{Generic Functions}).
20444 Starting at Autoconf 2.53, the use of @code{LIBOBJS} is an error.
20446 This change is mandated by the unification of the @acronym{GNU} Build System
20447 components.  In particular, the various fragile techniques used to parse
20448 a @file{configure.ac} are all replaced with the use of traces.  As a
20449 consequence, any action must be traceable, which obsoletes critical
20450 variable assignments.  Fortunately, @code{LIBOBJS} was the only problem,
20451 and it can even be handled gracefully (read, ``without your having to
20452 change something'').
20454 There were two typical uses of @code{LIBOBJS}: asking for a replacement
20455 function, and adjusting @code{LIBOBJS} for Automake and/or Libtool.
20457 @sp 1
20459 As for function replacement, the fix is immediate: use
20460 @code{AC_LIBOBJ}.  For instance:
20462 @example
20463 LIBOBJS="$LIBOBJS fnmatch.o"
20464 LIBOBJS="$LIBOBJS malloc.$ac_objext"
20465 @end example
20467 @noindent
20468 should be replaced with:
20470 @example
20471 AC_LIBOBJ([fnmatch])
20472 AC_LIBOBJ([malloc])
20473 @end example
20475 @sp 1
20477 @ovindex LIBOBJDIR
20478 When used with Automake 1.10 or newer, a suitable value for
20479 @code{LIBOBJDIR} is set so that the @code{LIBOBJS} and @code{LTLIBOBJS}
20480 can be referenced from any @file{Makefile.am}.  Even without Automake,
20481 arranging for @code{LIBOBJDIR} to be set correctly enables
20482 referencing @code{LIBOBJS} and @code{LTLIBOBJS} in another directory.
20483 The @code{LIBOBJDIR} feature is experimental.
20486 @node AC_FOO_IFELSE vs AC_TRY_FOO
20487 @subsection @code{AC_FOO_IFELSE} vs.@: @code{AC_TRY_FOO}
20489 Since Autoconf 2.50, internal codes uses @code{AC_PREPROC_IFELSE},
20490 @code{AC_COMPILE_IFELSE}, @code{AC_LINK_IFELSE}, and
20491 @code{AC_RUN_IFELSE} on one hand and @code{AC_LANG_SOURCES},
20492 and @code{AC_LANG_PROGRAM} on the other hand instead of the deprecated
20493 @code{AC_TRY_CPP}, @code{AC_TRY_COMPILE}, @code{AC_TRY_LINK}, and
20494 @code{AC_TRY_RUN}.  The motivations where:
20495 @itemize @minus
20496 @item
20497 a more consistent interface: @code{AC_TRY_COMPILE} etc.@: were double
20498 quoting their arguments;
20500 @item
20501 the combinatoric explosion is solved by decomposing on the one hand the
20502 generation of sources, and on the other hand executing the program;
20504 @item
20505 this scheme helps supporting more languages than plain C and C++.
20506 @end itemize
20508 In addition to the change of syntax, the philosophy has changed too:
20509 while emphasis was put on speed at the expense of accuracy, today's
20510 Autoconf promotes accuracy of the testing framework at, ahem@dots{}, the
20511 expense of speed.
20514 As a perfect example of what is @emph{not} to be done, here is how to
20515 find out whether a header file contains a particular declaration, such
20516 as a typedef, a structure, a structure member, or a function.  Use
20517 @code{AC_EGREP_HEADER} instead of running @code{grep} directly on the
20518 header file; on some systems the symbol might be defined in another
20519 header file that the file you are checking includes.
20521 As a (bad) example, here is how you should not check for C preprocessor
20522 symbols, either defined by header files or predefined by the C
20523 preprocessor: using @code{AC_EGREP_CPP}:
20525 @example
20526 @group
20527 AC_EGREP_CPP(yes,
20528 [#ifdef _AIX
20529   yes
20530 #endif
20531 ], is_aix=yes, is_aix=no)
20532 @end group
20533 @end example
20535 The above example, properly written would (i) use
20536 @code{AC_LANG_PROGRAM}, and (ii) run the compiler:
20538 @example
20539 @group
20540 AC_COMPILE_IFELSE([AC_LANG_PROGRAM(
20541 [[#ifndef _AIX
20542  error: This isn't AIX!
20543 #endif
20544 ]])],
20545                    [is_aix=yes],
20546                    [is_aix=no])
20547 @end group
20548 @end example
20551 @c ============================= Generating Test Suites with Autotest
20553 @node Using Autotest
20554 @chapter Generating Test Suites with Autotest
20556 @cindex Autotest
20558 @display
20559 @strong{N.B.: This section describes an experimental feature which will
20560 be part of Autoconf in a forthcoming release.  Although we believe
20561 Autotest is stabilizing, this documentation describes an interface which
20562 might change in the future: do not depend upon Autotest without
20563 subscribing to the Autoconf mailing lists.}
20564 @end display
20566 It is paradoxical that portable projects depend on nonportable tools
20567 to run their test suite.  Autoconf by itself is the paragon of this
20568 problem: although it aims at perfectly portability, up to 2.13 its
20569 test suite was using Deja@acronym{GNU}, a rich and complex testing
20570 framework, but which is far from being standard on Posix systems.
20571 Worse yet, it was likely to be missing on the most fragile platforms,
20572 the very platforms that are most likely to torture Autoconf and
20573 exhibit deficiencies.
20575 To circumvent this problem, many package maintainers have developed their
20576 own testing framework, based on simple shell scripts whose sole outputs
20577 are exit status values describing whether the test succeeded.  Most of
20578 these tests share common patterns, and this can result in lots of
20579 duplicated code and tedious maintenance.
20581 Following exactly the same reasoning that yielded to the inception of
20582 Autoconf, Autotest provides a test suite generation framework, based on
20583 M4 macros building a portable shell script.  The suite itself is
20584 equipped with automatic logging and tracing facilities which greatly
20585 diminish the interaction with bug reporters, and simple timing reports.
20587 Autoconf itself has been using Autotest for years, and we do attest that
20588 it has considerably improved the strength of the test suite and the
20589 quality of bug reports.  Other projects are known to use some generation
20590 of Autotest, such as Bison, Free Recode, Free Wdiff, @acronym{GNU} Tar, each of
20591 them with different needs, and this usage has validated Autotest as a general
20592 testing framework.
20594 Nonetheless, compared to Deja@acronym{GNU}, Autotest is inadequate for
20595 interactive tool testing, which is probably its main limitation.
20597 @menu
20598 * Using an Autotest Test Suite::  Autotest and the user
20599 * Writing Testsuites::          Autotest macros
20600 * testsuite Invocation::        Running @command{testsuite} scripts
20601 * Making testsuite Scripts::    Using autom4te to create @command{testsuite}
20602 @end menu
20604 @node Using an Autotest Test Suite
20605 @section Using an Autotest Test Suite
20607 @menu
20608 * testsuite Scripts::           The concepts of Autotest
20609 * Autotest Logs::               Their contents
20610 @end menu
20612 @node testsuite Scripts
20613 @subsection @command{testsuite} Scripts
20615 @cindex @command{testsuite}
20617 Generating testing or validation suites using Autotest is rather easy.
20618 The whole validation suite is held in a file to be processed through
20619 @command{autom4te}, itself using @acronym{GNU} M4 under the scene, to
20620 produce a stand-alone Bourne shell script which then gets distributed.
20621 Neither @command{autom4te} nor @acronym{GNU} M4 are needed at
20622 the installer's end.
20624 @cindex test group
20625 Each test of the validation suite should be part of some test group.  A
20626 @dfn{test group} is a sequence of interwoven tests that ought to be
20627 executed together, usually because one test in the group creates data
20628 files than a later test in the same group needs to read.  Complex test
20629 groups make later debugging more tedious.  It is much better to
20630 keep only a few tests per test group.  Ideally there is only one test
20631 per test group.
20633 For all but the simplest packages, some file such as @file{testsuite.at}
20634 does not fully hold all test sources, as these are often easier to
20635 maintain in separate files.  Each of these separate files holds a single
20636 test group, or a sequence of test groups all addressing some common
20637 functionality in the package.  In such cases, @file{testsuite.at}
20638 merely initializes the validation suite, and sometimes does elementary
20639 health checking, before listing include statements for all other test
20640 files.  The special file @file{package.m4}, containing the
20641 identification of the package, is automatically included if found.
20643 A convenient alternative consists in moving all the global issues
20644 (local Autotest macros, elementary health checking, and @code{AT_INIT}
20645 invocation) into the file @code{local.at}, and making
20646 @file{testsuite.at} be a simple list of @code{m4_include} of sub test
20647 suites.  In such case, generating the whole test suite or pieces of it
20648 is only a matter of choosing the @command{autom4te} command line
20649 arguments.
20651 The validation scripts that Autotest produces are by convention called
20652 @command{testsuite}.  When run, @command{testsuite} executes each test
20653 group in turn, producing only one summary line per test to say if that
20654 particular test succeeded or failed.  At end of all tests, summarizing
20655 counters get printed.  One debugging directory is left for each test
20656 group which failed, if any: such directories are named
20657 @file{testsuite.dir/@var{nn}}, where @var{nn} is the sequence number of
20658 the test group, and they include:
20660 @itemize @bullet
20661 @item a debugging script named @file{run} which reruns the test in
20662 @dfn{debug mode} (@pxref{testsuite Invocation}).  The automatic generation
20663 of debugging scripts has the purpose of easing the chase for bugs.
20665 @item all the files created with @code{AT_DATA}
20667 @item a log of the run, named @file{testsuite.log}
20668 @end itemize
20670 In the ideal situation, none of the tests fail, and consequently no
20671 debugging directory is left behind for validation.
20673 It often happens in practice that individual tests in the validation
20674 suite need to get information coming out of the configuration process.
20675 Some of this information, common for all validation suites, is provided
20676 through the file @file{atconfig}, automatically created by
20677 @code{AC_CONFIG_TESTDIR}.  For configuration informations which your
20678 testing environment specifically needs, you might prepare an optional
20679 file named @file{atlocal.in}, instantiated by @code{AC_CONFIG_FILES}.
20680 The configuration process produces @file{atconfig} and @file{atlocal}
20681 out of these two input files, and these two produced files are
20682 automatically read by the @file{testsuite} script.
20684 Here is a diagram showing the relationship between files.
20686 @noindent
20687 Files used in preparing a software package for distribution:
20689 @example
20690                 [package.m4] -->.
20691                                  \
20692 subfile-1.at ->.  [local.at] ---->+
20693     ...         \                  \
20694 subfile-i.at ---->-- testsuite.at -->-- autom4te* -->testsuite
20695     ...         /
20696 subfile-n.at ->'
20697 @end example
20699 @noindent
20700 Files used in configuring a software package:
20702 @example
20703                                      .--> atconfig
20704                                     /
20705 [atlocal.in] -->  config.status* --<
20706                                     \
20707                                      `--> [atlocal]
20708 @end example
20710 @noindent
20711 Files created during the test suite execution:
20713 @example
20714 atconfig -->.                    .--> testsuite.log
20715              \                  /
20716               >-- testsuite* --<
20717              /                  \
20718 [atlocal] ->'                    `--> [testsuite.dir]
20719 @end example
20722 @node Autotest Logs
20723 @subsection Autotest Logs
20725 When run, the test suite creates a log file named after itself, e.g., a
20726 test suite named @command{testsuite} creates @file{testsuite.log}.  It
20727 contains a lot of information, usually more than maintainers actually
20728 need, but therefore most of the time it contains all that is needed:
20730 @table @asis
20731 @item command line arguments
20732 @c akim s/to consist in/to consist of/
20733 A bad but unfortunately widespread habit consists of
20734 setting environment variables before the command, such as in
20735 @samp{CC=my-home-grown-cc ./testsuite}.  The test suite does not
20736 know this change, hence (i) it cannot report it to you, and (ii)
20737 it cannot preserve the value of @code{CC} for subsequent runs.
20738 Autoconf faced exactly the same problem, and solved it by asking
20739 users to pass the variable definitions as command line arguments.
20740 Autotest requires this rule, too, but has no means to enforce it; the log
20741 then contains a trace of the variables that were changed by the user.
20743 @item @file{ChangeLog} excerpts
20744 The topmost lines of all the @file{ChangeLog} files found in the source
20745 hierarchy.  This is especially useful when bugs are reported against
20746 development versions of the package, since the version string does not
20747 provide sufficient information to know the exact state of the sources
20748 the user compiled.  Of course, this relies on the use of a
20749 @file{ChangeLog}.
20751 @item build machine
20752 Running a test suite in a cross-compile environment is not an easy task,
20753 since it would mean having the test suite run on a machine @var{build},
20754 while running programs on a machine @var{host}.  It is much simpler to
20755 run both the test suite and the programs on @var{host}, but then, from
20756 the point of view of the test suite, there remains a single environment,
20757 @var{host} = @var{build}.  The log contains relevant information on the
20758 state of the build machine, including some important environment
20759 variables.
20760 @c FIXME: How about having an M4sh macro to say `hey, log the value
20761 @c of `@dots{}'?  This would help both Autoconf and Autotest.
20763 @item tested programs
20764 The absolute file name and answers to @option{--version} of the tested
20765 programs (see @ref{Writing Testsuites}, @code{AT_TESTED}).
20767 @item configuration log
20768 The contents of @file{config.log}, as created by @command{configure},
20769 are appended.  It contains the configuration flags and a detailed report
20770 on the configuration itself.
20771 @end table
20774 @node Writing Testsuites
20775 @section Writing @file{testsuite.at}
20777 The @file{testsuite.at} is a Bourne shell script making use of special
20778 Autotest M4 macros.  It often contains a call to @code{AT_INIT} near
20779 its beginning followed by one call to @code{m4_include} per source file
20780 for tests.  Each such included file, or the remainder of
20781 @file{testsuite.at} if include files are not used, contain a sequence of
20782 test groups.  Each test group begins with a call to @code{AT_SETUP},
20783 then an arbitrary number of shell commands or calls to @code{AT_CHECK},
20784 and then completes with a call to @code{AT_CLEANUP}.  Multiple test
20785 groups can be categorized by a call to @code{AT_BANNER}.
20787 @defmac AT_INIT (@ovar{name})
20788 @atindex{INIT}
20789 @c FIXME: Not clear, plus duplication of the information.
20790 Initialize Autotest.  Giving a @var{name} to the test suite is
20791 encouraged if your package includes several test suites.  In any case,
20792 the test suite always displays the package name and version.  It also
20793 inherits the package bug report address.
20794 @end defmac
20796 @defmac AT_COPYRIGHT (@var{copyright-notice})
20797 @atindex{COPYRIGHT}
20798 @cindex Copyright Notice
20799 State that, in addition to the Free Software Foundation's copyright on
20800 the Autotest macros, parts of your test suite are covered by
20801 @var{copyright-notice}.
20803 The @var{copyright-notice} shows up in both the head of
20804 @command{testsuite} and in @samp{testsuite --version}.
20805 @end defmac
20807 @defmac AT_TESTED (@var{executables})
20808 @atindex{TESTED}
20809 Log the file name and answer to @option{--version} of each program in
20810 space-separated list @var{executables}.  Several invocations register
20811 new executables, in other words, don't fear registering one program
20812 several times.
20813 @end defmac
20815 Autotest test suites rely on @env{PATH} to find the tested program.
20816 This avoids the need to generate absolute names of the various tools, and
20817 makes it possible to test installed programs.  Therefore, knowing which
20818 programs are being exercised is crucial to understanding problems in
20819 the test suite itself, or its occasional misuses.  It is a good idea to
20820 also subscribe foreign programs you depend upon, to avoid incompatible
20821 diagnostics.
20823 @sp 1
20825 @defmac AT_BANNER (@var{test-category-name})
20826 @atindex{BANNER}
20827 This macro identifies the start of a category of related test groups.
20828 When the resulting @file{testsuite} is invoked with more than one test
20829 group to run, its output will include a banner containing
20830 @var{test-category-name} prior to any tests run from that category.  The
20831 banner should be no more than about 40 or 50 characters.  A blank banner
20832 will not print, effectively ending a category and letting subsequent
20833 test groups behave as though they are uncategorized when run in
20834 isolation.
20835 @end defmac
20837 @defmac AT_SETUP (@var{test-group-name})
20838 @atindex{SETUP}
20839 This macro starts a group of related tests, all to be executed in the
20840 same subshell.  It accepts a single argument, which holds a few words
20841 (no more than about 30 or 40 characters) quickly describing the purpose
20842 of the test group being started.  @var{test-group-name} must not expand
20843 to unbalanced quotes, although quadrigraphs can be used.
20844 @end defmac
20846 @defmac AT_KEYWORDS (@var{keywords})
20847 @atindex{KEYWORDS}
20848 Associate the space-separated list of @var{keywords} to the enclosing
20849 test group.  This makes it possible to run ``slices'' of the test suite.
20850 For instance, if some of your test groups exercise some @samp{foo}
20851 feature, then using @samp{AT_KEYWORDS(foo)} lets you run
20852 @samp{./testsuite -k foo} to run exclusively these test groups.  The
20853 @var{title} of the test group is automatically recorded to
20854 @code{AT_KEYWORDS}.
20856 Several invocations within a test group accumulate new keywords.  In
20857 other words, don't fear registering the same keyword several times in a
20858 test group.
20859 @end defmac
20861 @defmac AT_CAPTURE_FILE (@var{file})
20862 @atindex{CAPTURE_FILE}
20863 If the current test group fails, log the contents of @var{file}.
20864 Several identical calls within one test group have no additional effect.
20865 @end defmac
20867 @defmac AT_XFAIL_IF (@var{shell-condition})
20868 @atindex{XFAIL_IF}
20869 Determine whether the test is expected to fail because it is a known
20870 bug (for unsupported features, you should skip the test).
20871 @var{shell-condition} is a shell expression such as a @code{test}
20872 command; you can instantiate this macro many times from within the
20873 same test group, and one of the conditions is enough to turn
20874 the test into an expected failure.
20875 @end defmac
20877 @defmac AT_CLEANUP
20878 @atindex{CLEANUP}
20879 End the current test group.
20880 @end defmac
20882 @sp 1
20884 @defmac AT_DATA (@var{file}, @var{contents})
20885 @atindex{DATA}
20886 Initialize an input data @var{file} with given @var{contents}.  Of
20887 course, the @var{contents} have to be properly quoted between square
20888 brackets to protect against included commas or spurious M4
20889 expansion.  The contents must end with an end of line.  @var{file} must
20890 be a single shell word that expands into a single file name.
20891 @end defmac
20893 @defmac AT_CHECK (@var{commands}, @dvar{status, 0}, @dvar{stdout, }, @
20894   @dvar{stderr, }, @ovar{run-if-fail}, @ovar{run-if-pass})
20895 @atindex{CHECK}
20896 Execute a test by performing given shell @var{commands}.  These commands
20897 should normally exit with @var{status}, while producing expected
20898 @var{stdout} and @var{stderr} contents.  If @var{commands} exit with
20899 status 77, then the whole test group is skipped.  Otherwise, if this test
20900 fails, run shell commands @var{run-if-fail} or, if this test passes, run shell
20901 commands @var{run-if-pass}.
20903 This macro must be invoked in between @code{AT_SETUP} and @code{AT_CLEANUP}.
20905 @c Previously, we had this:
20906 @c  The @var{commands} @emph{must not} redirect the standard output, nor the
20907 @c  standard error.
20908 @c to prevent trigerring the double redirect bug on Ultrix, see
20909 @c `File Descriptors'.  This was too restricting, and Ultrix is pretty
20910 @c much dead, so we dropped the limitation; the obvious workaround on
20911 @c Ultrix is to use a working shell there.
20913 If @var{status}, or @var{stdout}, or @var{stderr} is @samp{ignore}, then
20914 the corresponding value is not checked.
20916 The special value @samp{expout} for @var{stdout} means the expected
20917 output of the @var{commands} is the content of the file @file{expout}.
20918 If @var{stdout} is @samp{stdout}, then the standard output of the
20919 @var{commands} is available for further tests in the file @file{stdout}.
20920 Similarly for @var{stderr} with @samp{experr} and @samp{stderr}.
20921 @end defmac
20924 @node testsuite Invocation
20925 @section Running @command{testsuite} Scripts
20926 @cindex @command{testsuite}
20928 Autotest test suites support the following arguments:
20930 @table @option
20931 @item --help
20932 @itemx -h
20933 Display the list of options and exit successfully.
20935 @item --version
20936 @itemx -V
20937 Display the version of the test suite and exit successfully.
20939 @item --directory=@var{dir}
20940 @itemx -C @var{dir}
20941 Change the current directory to @var{dir} before creating any files.
20942 Useful for running the testsuite in a subdirectory from a top-level
20943 Makefile.
20945 @item --clean
20946 @itemx -c
20947 Remove all the files the test suite might have created and exit.  Meant
20948 for @code{clean} Make targets.
20950 @item --list
20951 @itemx -l
20952 List all the tests (or only the selection), including their possible
20953 keywords.
20954 @end table
20956 @sp 1
20958 By default all tests are performed (or described with
20959 @option{--list}) in the default environment first silently, then
20960 verbosely, but the environment, set of tests, and verbosity level can be
20961 tuned:
20963 @table @samp
20964 @item @var{variable}=@var{value}
20965 Set the environment @var{variable} to @var{value}.  Use this rather
20966 than @samp{FOO=foo ./testsuite} as debugging scripts would then run in a
20967 different environment.
20969 @cindex @code{AUTOTEST_PATH}
20970 The variable @code{AUTOTEST_PATH} specifies the testing path to prepend
20971 to @env{PATH}.  Relative directory names (not starting with
20972 @samp{/}) are considered to be relative to the top level of the
20973 package being built.  All directories are made absolute, first
20974 starting from the top level @emph{build} tree, then from the
20975 @emph{source} tree.  For instance @samp{./testsuite
20976 AUTOTEST_PATH=tests:bin} for a @file{/src/foo-1.0} source package built
20977 in @file{/tmp/foo} results in @samp{/tmp/foo/tests:/tmp/foo/bin} and
20978 then @samp{/src/foo-1.0/tests:/src/foo-1.0/bin} being prepended to
20979 @env{PATH}.
20981 @item @var{number}
20982 @itemx @var{number}-@var{number}
20983 @itemx @var{number}-
20984 @itemx -@var{number}
20985 Add the corresponding test groups, with obvious semantics, to the
20986 selection.
20988 @item --keywords=@var{keywords}
20989 @itemx -k @var{keywords}
20990 Add to the selection the test groups with title or keywords (arguments
20991 to @code{AT_SETUP} or @code{AT_KEYWORDS}) that match @emph{all} keywords
20992 of the comma separated list @var{keywords}, case-insensitively.  Use
20993 @samp{!} immediately before the keyword to invert the selection for this
20994 keyword.  By default, the keywords match whole words; enclose them in
20995 @samp{.*} to also match parts of words.
20997 For example, running
20999 @example
21000 @kbd{./testsuite -k 'autoupdate,.*FUNC.*'}
21001 @end example
21003 @noindent
21004 selects all tests tagged @samp{autoupdate} @emph{and} with tags
21005 containing @samp{FUNC} (as in @samp{AC_CHECK_FUNC}, @samp{AC_FUNC_ALLOCA},
21006 etc.), while
21008 @example
21009 @kbd{./testsuite -k '!autoupdate' -k '.*FUNC.*'}
21010 @end example
21012 @noindent
21013 selects all tests not tagged @samp{autoupdate} @emph{or} with tags
21014 containing @samp{FUNC}.
21016 @item --errexit
21017 @itemx -e
21018 If any test fails, immediately abort testing.  It implies
21019 @option{--debug}: post test group clean up, and top-level logging
21020 are inhibited.  This option is meant for the full test
21021 suite, it is not really useful for generated debugging scripts.
21023 @item --verbose
21024 @itemx -v
21025 Force more verbosity in the detailed output of what is being done.  This
21026 is the default for debugging scripts.
21028 @item --debug
21029 @itemx -d
21030 Do not remove the files after a test group was performed ---but they are
21031 still removed @emph{before}, therefore using this option is sane when
21032 running several test groups.  Create debugging scripts.  Do not
21033 overwrite the top-level
21034 log (in order to preserve supposedly existing full log file).  This is
21035 the default for debugging scripts, but it can also be useful to debug
21036 the testsuite itself.
21038 @item --trace
21039 @itemx -x
21040 Trigger shell tracing of the test groups.
21041 @end table
21044 @node Making testsuite Scripts
21045 @section Making @command{testsuite} Scripts
21047 For putting Autotest into movement, you need some configuration and
21048 makefile machinery.  We recommend, at least if your package uses deep or
21049 shallow hierarchies, that you use @file{tests/} as the name of the
21050 directory holding all your tests and their makefile.  Here is a
21051 check list of things to do.
21053 @itemize @minus
21055 @item
21056 @cindex @file{package.m4}
21057 Make sure to create the file @file{package.m4}, which defines the
21058 identity of the package.  It must define @code{AT_PACKAGE_STRING}, the
21059 full signature of the package, and @code{AT_PACKAGE_BUGREPORT}, the
21060 address to which bug reports should be sent.  For sake of completeness,
21061 we suggest that you also define @code{AT_PACKAGE_NAME},
21062 @code{AT_PACKAGE_TARNAME}, and @code{AT_PACKAGE_VERSION}.
21063 @xref{Initializing configure}, for a description of these variables.  We
21064 suggest the following makefile excerpt:
21066 @smallexample
21067 # The `:;' works around a Bash 3.2 bug when the output is not writeable.
21068 $(srcdir)/package.m4: $(top_srcdir)/configure.ac
21069         :;@{ \
21070           echo '# Signature of the current package.' && \
21071           echo 'm4_define([AT_PACKAGE_NAME],      [@@PACKAGE_NAME@@])' && \
21072           echo 'm4_define([AT_PACKAGE_TARNAME],   [@@PACKAGE_TARNAME@@])' && \
21073           echo 'm4_define([AT_PACKAGE_VERSION],   [@@PACKAGE_VERSION@@])' && \
21074           echo 'm4_define([AT_PACKAGE_STRING],    [@@PACKAGE_STRING@@])' && \
21075           echo 'm4_define([AT_PACKAGE_BUGREPORT], [@@PACKAGE_BUGREPORT@@])'; \
21076         @} >'$(srcdir)/package.m4'
21077 @end smallexample
21079 @noindent
21080 Be sure to distribute @file{package.m4} and to put it into the source
21081 hierarchy: the test suite ought to be shipped!
21083 @item
21084 Invoke @code{AC_CONFIG_TESTDIR}.
21086 @defmac AC_CONFIG_TESTDIR (@var{directory}, @dvar{test-path, directory})
21087 @acindex{CONFIG_TESTDIR}
21088 An Autotest test suite is to be configured in @var{directory}.  This
21089 macro requires the instantiation of @file{@var{directory}/atconfig} from
21090 @file{@var{directory}/atconfig.in}, and sets the default
21091 @code{AUTOTEST_PATH} to @var{test-path} (@pxref{testsuite Invocation}).
21092 @end defmac
21094 @item
21095 Still within @file{configure.ac}, as appropriate, ensure that some
21096 @code{AC_CONFIG_FILES} command includes substitution for
21097 @file{tests/atlocal}.
21099 @item
21100 The @file{tests/Makefile.in} should be modified so the validation in
21101 your package is triggered by @samp{make check}.  An example is provided
21102 below.
21103 @end itemize
21105 With Automake, here is a minimal example about how to link @samp{make
21106 check} with a validation suite.
21108 @example
21109 EXTRA_DIST = testsuite.at $(TESTSUITE) atlocal.in
21110 TESTSUITE = $(srcdir)/testsuite
21112 check-local: atconfig atlocal $(TESTSUITE)
21113         $(SHELL) '$(TESTSUITE)' $(TESTSUITEFLAGS)
21115 installcheck-local: atconfig atlocal $(TESTSUITE)
21116         $(SHELL) '$(TESTSUITE)' AUTOTEST_PATH='$(bindir)' \
21117           $(TESTSUITEFLAGS)
21119 clean-local:
21120         test ! -f '$(TESTSUITE)' || \
21121          $(SHELL) '$(TESTSUITE)' --clean
21123 AUTOTEST = $(AUTOM4TE) --language=autotest
21124 $(TESTSUITE): $(srcdir)/testsuite.at
21125         $(AUTOTEST) -I '$(srcdir)' -o $@@.tmp $@@.at
21126         mv $@@.tmp $@@
21127 @end example
21129 You might want to list explicitly the dependencies, i.e., the list of
21130 the files @file{testsuite.at} includes.
21132 If you don't use Automake, you might need to add lines inspired from the
21133 following:
21135 @example
21136 subdir = tests
21138 atconfig: $(top_builddir)/config.status
21139         cd $(top_builddir) && \
21140            $(SHELL) ./config.status $(subdir)/$@@
21142 atlocal: $(srcdir)/atlocal.in $(top_builddir)/config.status
21143         cd $(top_builddir) && \
21144            $(SHELL) ./config.status $(subdir)/$@@
21145 @end example
21147 @noindent
21148 and manage to have @code{$(EXTRA_DIST)} distributed.
21150 If you use Automake, however, you don't need to add a rule to generate
21151 @file{atlocal}.
21153 With all this in place, and if you have not initialized @samp{TESTSUITEFLAGS}
21154 within your makefile, you can fine-tune test suite execution with this
21155 variable, for example:
21157 @example
21158 make check TESTSUITEFLAGS='-v -d -x 75 -k AC_PROG_CC CFLAGS=-g'
21159 @end example
21163 @c =============================== Frequent Autoconf Questions, with answers
21165 @node FAQ
21166 @chapter Frequent Autoconf Questions, with answers
21168 Several questions about Autoconf come up occasionally.  Here some of them
21169 are addressed.
21171 @menu
21172 * Distributing::                Distributing @command{configure} scripts
21173 * Why GNU M4::                  Why not use the standard M4?
21174 * Bootstrapping::               Autoconf and @acronym{GNU} M4 require each other?
21175 * Why Not Imake::               Why @acronym{GNU} uses @command{configure} instead of Imake
21176 * Defining Directories::        Passing @code{datadir} to program
21177 * Autom4te Cache::              What is it?  Can I remove it?
21178 * Present But Cannot Be Compiled::  Compiler and Preprocessor Disagree
21179 @end menu
21181 @node Distributing
21182 @section Distributing @command{configure} Scripts
21183 @cindex License
21185 @display
21186 What are the restrictions on distributing @command{configure}
21187 scripts that Autoconf generates?  How does that affect my
21188 programs that use them?
21189 @end display
21191 There are no restrictions on how the configuration scripts that Autoconf
21192 produces may be distributed or used.  In Autoconf version 1, they were
21193 covered by the @acronym{GNU} General Public License.  We still encourage
21194 software authors to distribute their work under terms like those of the
21195 @acronym{GPL}, but doing so is not required to use Autoconf.
21197 Of the other files that might be used with @command{configure},
21198 @file{config.h.in} is under whatever copyright you use for your
21199 @file{configure.ac}.  @file{config.sub} and @file{config.guess} have an
21200 exception to the @acronym{GPL} when they are used with an Autoconf-generated
21201 @command{configure} script, which permits you to distribute them under the
21202 same terms as the rest of your package.  @file{install-sh} is from the X
21203 Consortium and is not copyrighted.
21205 @node Why GNU M4
21206 @section Why Require @acronym{GNU} M4?
21208 @display
21209 Why does Autoconf require @acronym{GNU} M4?
21210 @end display
21212 Many M4 implementations have hard-coded limitations on the size and
21213 number of macros that Autoconf exceeds.  They also lack several
21214 builtin macros that it would be difficult to get along without in a
21215 sophisticated application like Autoconf, including:
21217 @example
21218 m4_builtin
21219 m4_indir
21220 m4_bpatsubst
21221 __file__
21222 __line__
21223 @end example
21225 Autoconf requires version 1.4.5 or later of @acronym{GNU} M4.
21227 Since only software maintainers need to use Autoconf, and since @acronym{GNU}
21228 M4 is simple to configure and install, it seems reasonable to require
21229 @acronym{GNU} M4 to be installed also.  Many maintainers of @acronym{GNU} and
21230 other free software already have most of the @acronym{GNU} utilities
21231 installed, since they prefer them.
21233 @node Bootstrapping
21234 @section How Can I Bootstrap?
21235 @cindex Bootstrap
21237 @display
21238 If Autoconf requires @acronym{GNU} M4 and @acronym{GNU} M4 has an Autoconf
21239 @command{configure} script, how do I bootstrap?  It seems like a chicken
21240 and egg problem!
21241 @end display
21243 This is a misunderstanding.  Although @acronym{GNU} M4 does come with a
21244 @command{configure} script produced by Autoconf, Autoconf is not required
21245 in order to run the script and install @acronym{GNU} M4.  Autoconf is only
21246 required if you want to change the M4 @command{configure} script, which few
21247 people have to do (mainly its maintainer).
21249 @node Why Not Imake
21250 @section Why Not Imake?
21251 @cindex Imake
21253 @display
21254 Why not use Imake instead of @command{configure} scripts?
21255 @end display
21257 Several people have written addressing this question, so I include
21258 adaptations of their explanations here.
21260 The following answer is based on one written by Richard Pixley:
21262 @quotation
21263 Autoconf generated scripts frequently work on machines that it has
21264 never been set up to handle before.  That is, it does a good job of
21265 inferring a configuration for a new system.  Imake cannot do this.
21267 Imake uses a common database of host specific data.  For X11, this makes
21268 sense because the distribution is made as a collection of tools, by one
21269 central authority who has control over the database.
21271 @acronym{GNU} tools are not released this way.  Each @acronym{GNU} tool has a
21272 maintainer; these maintainers are scattered across the world.  Using a
21273 common database would be a maintenance nightmare.  Autoconf may appear
21274 to be this kind of database, but in fact it is not.  Instead of listing
21275 host dependencies, it lists program requirements.
21277 If you view the @acronym{GNU} suite as a collection of native tools, then the
21278 problems are similar.  But the @acronym{GNU} development tools can be
21279 configured as cross tools in almost any host+target permutation.  All of
21280 these configurations can be installed concurrently.  They can even be
21281 configured to share host independent files across hosts.  Imake doesn't
21282 address these issues.
21284 Imake templates are a form of standardization.  The @acronym{GNU} coding
21285 standards address the same issues without necessarily imposing the same
21286 restrictions.
21287 @end quotation
21290 Here is some further explanation, written by Per Bothner:
21292 @quotation
21293 One of the advantages of Imake is that it easy to generate large
21294 makefiles using the @samp{#include} and macro mechanisms of @command{cpp}.
21295 However, @code{cpp} is not programmable: it has limited conditional
21296 facilities, and no looping.  And @code{cpp} cannot inspect its
21297 environment.
21299 All of these problems are solved by using @code{sh} instead of
21300 @code{cpp}.  The shell is fully programmable, has macro substitution,
21301 can execute (or source) other shell scripts, and can inspect its
21302 environment.
21303 @end quotation
21306 Paul Eggert elaborates more:
21308 @quotation
21309 With Autoconf, installers need not assume that Imake itself is already
21310 installed and working well.  This may not seem like much of an advantage
21311 to people who are accustomed to Imake.  But on many hosts Imake is not
21312 installed or the default installation is not working well, and requiring
21313 Imake to install a package hinders the acceptance of that package on
21314 those hosts.  For example, the Imake template and configuration files
21315 might not be installed properly on a host, or the Imake build procedure
21316 might wrongly assume that all source files are in one big directory
21317 tree, or the Imake configuration might assume one compiler whereas the
21318 package or the installer needs to use another, or there might be a
21319 version mismatch between the Imake expected by the package and the Imake
21320 supported by the host.  These problems are much rarer with Autoconf,
21321 where each package comes with its own independent configuration
21322 processor.
21324 Also, Imake often suffers from unexpected interactions between
21325 @command{make} and the installer's C preprocessor.  The fundamental problem
21326 here is that the C preprocessor was designed to preprocess C programs,
21327 not makefiles.  This is much less of a problem with Autoconf,
21328 which uses the general-purpose preprocessor M4, and where the
21329 package's author (rather than the installer) does the preprocessing in a
21330 standard way.
21331 @end quotation
21334 Finally, Mark Eichin notes:
21336 @quotation
21337 Imake isn't all that extensible, either.  In order to add new features to
21338 Imake, you need to provide your own project template, and duplicate most
21339 of the features of the existing one.  This means that for a sophisticated
21340 project, using the vendor-provided Imake templates fails to provide any
21341 leverage---since they don't cover anything that your own project needs
21342 (unless it is an X11 program).
21344 On the other side, though:
21346 The one advantage that Imake has over @command{configure}:
21347 @file{Imakefile} files tend to be much shorter (likewise, less redundant)
21348 than @file{Makefile.in} files.  There is a fix to this, however---at least
21349 for the Kerberos V5 tree, we've modified things to call in common
21350 @file{post.in} and @file{pre.in} makefile fragments for the
21351 entire tree.  This means that a lot of common things don't have to be
21352 duplicated, even though they normally are in @command{configure} setups.
21353 @end quotation
21356 @node Defining Directories
21357 @section How Do I @code{#define} Installation Directories?
21359 @display
21360 My program needs library files, installed in @code{datadir} and
21361 similar.  If I use
21363 @example
21364 AC_DEFINE_UNQUOTED([DATADIR], [$datadir],
21365   [Define to the read-only architecture-independent
21366    data directory.])
21367 @end example
21369 @noindent
21370 I get
21372 @example
21373 #define DATADIR "$@{prefix@}/share"
21374 @end example
21375 @end display
21377 As already explained, this behavior is on purpose, mandated by the
21378 @acronym{GNU} Coding Standards, see @ref{Installation Directory
21379 Variables}.  There are several means to achieve a similar goal:
21381 @itemize @minus
21382 @item
21383 Do not use @code{AC_DEFINE} but use your makefile to pass the
21384 actual value of @code{datadir} via compilation flags.
21385 @xref{Installation Directory Variables}, for the details.
21387 @item
21388 This solution can be simplified when compiling a program: you may either
21389 extend the @code{CPPFLAGS}:
21391 @example
21392 CPPFLAGS = -DDATADIR='"$(datadir)"' @@CPPFLAGS@@
21393 @end example
21395 @noindent
21396 If you are using Automake, you should use @code{AM_CPPFLAGS} instead:
21398 @example
21399 AM_CPPFLAGS = -DDATADIR='"$(datadir)"'
21400 @end example
21402 @noindent
21403 Alternatively, create a dedicated header file:
21405 @example
21406 DISTCLEANFILES = myprog-paths.h
21407 myprog-paths.h: Makefile
21408         echo '#define DATADIR "$(datadir)"' >$@@
21409 @end example
21411 @item
21412 Use @code{AC_DEFINE} but have @command{configure} compute the literal
21413 value of @code{datadir} and others.  Many people have wrapped macros to
21414 automate this task.  For instance, the macro @code{AC_DEFINE_DIR} from
21415 the @uref{http://autoconf-archive.cryp.to/, Autoconf Macro
21416 Archive}.
21418 This solution does not conform to the @acronym{GNU} Coding Standards.
21420 @item
21421 Note that all the previous solutions hard wire the absolute name of
21422 these directories in the executables, which is not a good property.  You
21423 may try to compute the names relative to @code{prefix}, and try to
21424 find @code{prefix} at runtime, this way your package is relocatable.
21425 @end itemize
21428 @node Autom4te Cache
21429 @section What is @file{autom4te.cache}?
21431 @display
21432 What is this directory @file{autom4te.cache}?  Can I safely remove it?
21433 @end display
21435 In the @acronym{GNU} Build System, @file{configure.ac} plays a central
21436 role and is read by many tools: @command{autoconf} to create
21437 @file{configure}, @command{autoheader} to create @file{config.h.in},
21438 @command{automake} to create @file{Makefile.in}, @command{autoscan} to
21439 check the completeness of @file{configure.ac}, @command{autoreconf} to
21440 check the @acronym{GNU} Build System components that are used.  To
21441 ``read @file{configure.ac}'' actually means to compile it with M4,
21442 which can be a long process for complex @file{configure.ac}.
21444 This is why all these tools, instead of running directly M4, invoke
21445 @command{autom4te} (@pxref{autom4te Invocation}) which, while answering to
21446 a specific demand, stores additional information in
21447 @file{autom4te.cache} for future runs.  For instance, if you run
21448 @command{autoconf}, behind the scenes, @command{autom4te} also
21449 stores information for the other tools, so that when you invoke
21450 @command{autoheader} or @command{automake} etc., reprocessing
21451 @file{configure.ac} is not needed.  The speed up is frequently 30%,
21452 and is increasing with the size of @file{configure.ac}.
21454 But it is and remains being simply a cache: you can safely remove it.
21456 @sp 1
21458 @display
21459 Can I permanently get rid of it?
21460 @end display
21462 The creation of this cache can be disabled from
21463 @file{~/.autom4te.cfg}, see @ref{Customizing autom4te}, for more
21464 details.  You should be aware that disabling the cache slows down the
21465 Autoconf test suite by 40%.  The more @acronym{GNU} Build System
21466 components are used, the more the cache is useful; for instance
21467 running @samp{autoreconf -f} on the Core Utilities is twice slower without
21468 the cache @emph{although @option{--force} implies that the cache is
21469 not fully exploited}, and eight times slower than without
21470 @option{--force}.
21473 @node Present But Cannot Be Compiled
21474 @section Header Present But Cannot Be Compiled
21476 The most important guideline to bear in mind when checking for
21477 features is to mimic as much as possible the intended use.
21478 Unfortunately, old versions of @code{AC_CHECK_HEADER} and
21479 @code{AC_CHECK_HEADERS} failed to follow this idea, and called
21480 the preprocessor, instead of the compiler, to check for headers.  As a
21481 result, incompatibilities between headers went unnoticed during
21482 configuration, and maintainers finally had to deal with this issue
21483 elsewhere.
21485 As of Autoconf 2.56 both checks are performed, and @command{configure}
21486 complains loudly if the compiler and the preprocessor do not agree.
21487 For the time being the result used is that of the preprocessor, to give
21488 maintainers time to adjust their @file{configure.ac}, but in the
21489 future, only the compiler will be considered.
21491 Consider the following example:
21493 @smallexample
21494 $ @kbd{cat number.h}
21495 typedef int number;
21496 $ @kbd{cat pi.h}
21497 const number pi = 3;
21498 $ @kbd{cat configure.ac}
21499 AC_INIT([Example], [1.0], [bug-example@@example.org])
21500 AC_CHECK_HEADERS([pi.h])
21501 $ @kbd{autoconf -Wall}
21502 $ @kbd{./configure}
21503 checking for gcc... gcc
21504 checking for C compiler default output file name... a.out
21505 checking whether the C compiler works... yes
21506 checking whether we are cross compiling... no
21507 checking for suffix of executables...
21508 checking for suffix of object files... o
21509 checking whether we are using the GNU C compiler... yes
21510 checking whether gcc accepts -g... yes
21511 checking for gcc option to accept ISO C89... none needed
21512 checking how to run the C preprocessor... gcc -E
21513 checking for grep that handles long lines and -e... grep
21514 checking for egrep... grep -E
21515 checking for ANSI C header files... yes
21516 checking for sys/types.h... yes
21517 checking for sys/stat.h... yes
21518 checking for stdlib.h... yes
21519 checking for string.h... yes
21520 checking for memory.h... yes
21521 checking for strings.h... yes
21522 checking for inttypes.h... yes
21523 checking for stdint.h... yes
21524 checking for unistd.h... yes
21525 checking pi.h usability... no
21526 checking pi.h presence... yes
21527 configure: WARNING: pi.h: present but cannot be compiled
21528 configure: WARNING: pi.h:     check for missing prerequisite headers?
21529 configure: WARNING: pi.h: see the Autoconf documentation
21530 configure: WARNING: pi.h:     section "Present But Cannot Be Compiled"
21531 configure: WARNING: pi.h: proceeding with the preprocessor's result
21532 configure: WARNING: pi.h: in the future, the compiler will take precedence
21533 configure: WARNING:     ## -------------------------------------- ##
21534 configure: WARNING:     ## Report this to bug-example@@example.org ##
21535 configure: WARNING:     ## -------------------------------------- ##
21536 checking for pi.h... yes
21537 @end smallexample
21539 @noindent
21540 The proper way the handle this case is using the fourth argument
21541 (@pxref{Generic Headers}):
21543 @example
21544 $ @kbd{cat configure.ac}
21545 AC_INIT([Example], [1.0], [bug-example@@example.org])
21546 AC_CHECK_HEADERS([number.h pi.h], [], [],
21547 [[#ifdef HAVE_NUMBER_H
21548 # include <number.h>
21549 #endif
21551 $ @kbd{autoconf -Wall}
21552 $ @kbd{./configure}
21553 checking for gcc... gcc
21554 checking for C compiler default output... a.out
21555 checking whether the C compiler works... yes
21556 checking whether we are cross compiling... no
21557 checking for suffix of executables...
21558 checking for suffix of object files... o
21559 checking whether we are using the GNU C compiler... yes
21560 checking whether gcc accepts -g... yes
21561 checking for gcc option to accept ANSI C... none needed
21562 checking for number.h... yes
21563 checking for pi.h... yes
21564 @end example
21566 See @ref{Particular Headers}, for a list of headers with their
21567 prerequisite.
21569 @c ===================================================== History of Autoconf.
21571 @node History
21572 @chapter History of Autoconf
21573 @cindex History of autoconf
21575 You may be wondering, Why was Autoconf originally written?  How did it
21576 get into its present form?  (Why does it look like gorilla spit?)  If
21577 you're not wondering, then this chapter contains no information useful
21578 to you, and you might as well skip it.  If you @emph{are} wondering,
21579 then let there be light@enddots{}
21581 @menu
21582 * Genesis::                     Prehistory and naming of @command{configure}
21583 * Exodus::                      The plagues of M4 and Perl
21584 * Leviticus::                   The priestly code of portability arrives
21585 * Numbers::                     Growth and contributors
21586 * Deuteronomy::                 Approaching the promises of easy configuration
21587 @end menu
21589 @node Genesis
21590 @section Genesis
21592 In June 1991 I was maintaining many of the @acronym{GNU} utilities for the
21593 Free Software Foundation.  As they were ported to more platforms and
21594 more programs were added, the number of @option{-D} options that users
21595 had to select in the makefile (around 20) became burdensome.
21596 Especially for me---I had to test each new release on a bunch of
21597 different systems.  So I wrote a little shell script to guess some of
21598 the correct settings for the fileutils package, and released it as part
21599 of fileutils 2.0.  That @command{configure} script worked well enough that
21600 the next month I adapted it (by hand) to create similar @command{configure}
21601 scripts for several other @acronym{GNU} utilities packages.  Brian Berliner
21602 also adapted one of my scripts for his @acronym{CVS} revision control system.
21604 Later that summer, I learned that Richard Stallman and Richard Pixley
21605 were developing similar scripts to use in the @acronym{GNU} compiler tools;
21606 so I adapted my @command{configure} scripts to support their evolving
21607 interface: using the file name @file{Makefile.in} as the templates;
21608 adding @samp{+srcdir}, the first option (of many); and creating
21609 @file{config.status} files.
21611 @node Exodus
21612 @section Exodus
21614 As I got feedback from users, I incorporated many improvements, using
21615 Emacs to search and replace, cut and paste, similar changes in each of
21616 the scripts.  As I adapted more @acronym{GNU} utilities packages to use
21617 @command{configure} scripts, updating them all by hand became impractical.
21618 Rich Murphey, the maintainer of the @acronym{GNU} graphics utilities, sent me
21619 mail saying that the @command{configure} scripts were great, and asking if
21620 I had a tool for generating them that I could send him.  No, I thought,
21621 but I should!  So I started to work out how to generate them.  And the
21622 journey from the slavery of hand-written @command{configure} scripts to the
21623 abundance and ease of Autoconf began.
21625 Cygnus @command{configure}, which was being developed at around that time,
21626 is table driven; it is meant to deal mainly with a discrete number of
21627 system types with a small number of mainly unguessable features (such as
21628 details of the object file format).  The automatic configuration system
21629 that Brian Fox had developed for Bash takes a similar approach.  For
21630 general use, it seems to me a hopeless cause to try to maintain an
21631 up-to-date database of which features each variant of each operating
21632 system has.  It's easier and more reliable to check for most features on
21633 the fly---especially on hybrid systems that people have hacked on
21634 locally or that have patches from vendors installed.
21636 I considered using an architecture similar to that of Cygnus
21637 @command{configure}, where there is a single @command{configure} script that
21638 reads pieces of @file{configure.in} when run.  But I didn't want to have
21639 to distribute all of the feature tests with every package, so I settled
21640 on having a different @command{configure} made from each
21641 @file{configure.in} by a preprocessor.  That approach also offered more
21642 control and flexibility.
21644 I looked briefly into using the Metaconfig package, by Larry Wall,
21645 Harlan Stenn, and Raphael Manfredi, but I decided not to for several
21646 reasons.  The @command{Configure} scripts it produces are interactive,
21647 which I find quite inconvenient; I didn't like the ways it checked for
21648 some features (such as library functions); I didn't know that it was
21649 still being maintained, and the @command{Configure} scripts I had
21650 seen didn't work on many modern systems (such as System V R4 and NeXT);
21651 it wasn't flexible in what it could do in response to a feature's
21652 presence or absence; I found it confusing to learn; and it was too big
21653 and complex for my needs (I didn't realize then how much Autoconf would
21654 eventually have to grow).
21656 I considered using Perl to generate my style of @command{configure}
21657 scripts, but decided that M4 was better suited to the job of simple
21658 textual substitutions: it gets in the way less, because output is
21659 implicit.  Plus, everyone already has it.  (Initially I didn't rely on
21660 the @acronym{GNU} extensions to M4.)  Also, some of my friends at the
21661 University of Maryland had recently been putting M4 front ends on
21662 several programs, including @code{tvtwm}, and I was interested in trying
21663 out a new language.
21665 @node Leviticus
21666 @section Leviticus
21668 Since my @command{configure} scripts determine the system's capabilities
21669 automatically, with no interactive user intervention, I decided to call
21670 the program that generates them Autoconfig.  But with a version number
21671 tacked on, that name would be too long for old Unix file systems,
21672 so I shortened it to Autoconf.
21674 In the fall of 1991 I called together a group of fellow questers after
21675 the Holy Grail of portability (er, that is, alpha testers) to give me
21676 feedback as I encapsulated pieces of my handwritten scripts in M4 macros
21677 and continued to add features and improve the techniques used in the
21678 checks.  Prominent among the testers were Fran@,{c}ois Pinard, who came up
21679 with the idea of making an Autoconf shell script to run M4
21680 and check for unresolved macro calls; Richard Pixley, who suggested
21681 running the compiler instead of searching the file system to find
21682 include files and symbols, for more accurate results; Karl Berry, who
21683 got Autoconf to configure @TeX{} and added the macro index to the
21684 documentation; and Ian Lance Taylor, who added support for creating a C
21685 header file as an alternative to putting @option{-D} options in a
21686 makefile, so he could use Autoconf for his @acronym{UUCP} package.
21687 The alpha testers cheerfully adjusted their files again and again as the
21688 names and calling conventions of the Autoconf macros changed from
21689 release to release.  They all contributed many specific checks, great
21690 ideas, and bug fixes.
21692 @node Numbers
21693 @section Numbers
21695 In July 1992, after months of alpha testing, I released Autoconf 1.0,
21696 and converted many @acronym{GNU} packages to use it.  I was surprised by how
21697 positive the reaction to it was.  More people started using it than I
21698 could keep track of, including people working on software that wasn't
21699 part of the @acronym{GNU} Project (such as TCL, FSP, and Kerberos V5).
21700 Autoconf continued to improve rapidly, as many people using the
21701 @command{configure} scripts reported problems they encountered.
21703 Autoconf turned out to be a good torture test for M4 implementations.
21704 Unix M4 started to dump core because of the length of the
21705 macros that Autoconf defined, and several bugs showed up in @acronym{GNU}
21706 M4 as well.  Eventually, we realized that we needed to use some
21707 features that only @acronym{GNU} M4 has.  4.3@acronym{BSD} M4, in
21708 particular, has an impoverished set of builtin macros; the System V
21709 version is better, but still doesn't provide everything we need.
21711 More development occurred as people put Autoconf under more stresses
21712 (and to uses I hadn't anticipated).  Karl Berry added checks for X11.
21713 david zuhn contributed C++ support.  Fran@,{c}ois Pinard made it diagnose
21714 invalid arguments.  Jim Blandy bravely coerced it into configuring
21715 @acronym{GNU} Emacs, laying the groundwork for several later improvements.
21716 Roland McGrath got it to configure the @acronym{GNU} C Library, wrote the
21717 @command{autoheader} script to automate the creation of C header file
21718 templates, and added a @option{--verbose} option to @command{configure}.
21719 Noah Friedman added the @option{--autoconf-dir} option and
21720 @code{AC_MACRODIR} environment variable.  (He also coined the term
21721 @dfn{autoconfiscate} to mean ``adapt a software package to use
21722 Autoconf''.)  Roland and Noah improved the quoting protection in
21723 @code{AC_DEFINE} and fixed many bugs, especially when I got sick of
21724 dealing with portability problems from February through June, 1993.
21726 @node Deuteronomy
21727 @section Deuteronomy
21729 A long wish list for major features had accumulated, and the effect of
21730 several years of patching by various people had left some residual
21731 cruft.  In April 1994, while working for Cygnus Support, I began a major
21732 revision of Autoconf.  I added most of the features of the Cygnus
21733 @command{configure} that Autoconf had lacked, largely by adapting the
21734 relevant parts of Cygnus @command{configure} with the help of david zuhn
21735 and Ken Raeburn.  These features include support for using
21736 @file{config.sub}, @file{config.guess}, @option{--host}, and
21737 @option{--target}; making links to files; and running @command{configure}
21738 scripts in subdirectories.  Adding these features enabled Ken to convert
21739 @acronym{GNU} @code{as}, and Rob Savoye to convert Deja@acronym{GNU}, to using
21740 Autoconf.
21742 I added more features in response to other peoples' requests.  Many
21743 people had asked for @command{configure} scripts to share the results of
21744 the checks between runs, because (particularly when configuring a large
21745 source tree, like Cygnus does) they were frustratingly slow.  Mike
21746 Haertel suggested adding site-specific initialization scripts.  People
21747 distributing software that had to unpack on MS-DOS asked for a way to
21748 override the @file{.in} extension on the file names, which produced file
21749 names like @file{config.h.in} containing two dots.  Jim Avera did an
21750 extensive examination of the problems with quoting in @code{AC_DEFINE}
21751 and @code{AC_SUBST}; his insights led to significant improvements.
21752 Richard Stallman asked that compiler output be sent to @file{config.log}
21753 instead of @file{/dev/null}, to help people debug the Emacs
21754 @command{configure} script.
21756 I made some other changes because of my dissatisfaction with the quality
21757 of the program.  I made the messages showing results of the checks less
21758 ambiguous, always printing a result.  I regularized the names of the
21759 macros and cleaned up coding style inconsistencies.  I added some
21760 auxiliary utilities that I had developed to help convert source code
21761 packages to use Autoconf.  With the help of Fran@,{c}ois Pinard, I made
21762 the macros not interrupt each others' messages.  (That feature revealed
21763 some performance bottlenecks in @acronym{GNU} M4, which he hastily
21764 corrected!)  I reorganized the documentation around problems people want
21765 to solve.  And I began a test suite, because experience had shown that
21766 Autoconf has a pronounced tendency to regress when we change it.
21768 Again, several alpha testers gave invaluable feedback, especially
21769 Fran@,{c}ois Pinard, Jim Meyering, Karl Berry, Rob Savoye, Ken Raeburn,
21770 and Mark Eichin.
21772 Finally, version 2.0 was ready.  And there was much rejoicing.  (And I
21773 have free time again.  I think.  Yeah, right.)
21776 @c ========================================================== Appendices
21779 @node GNU Free Documentation License
21780 @appendix GNU Free Documentation License
21782 @include fdl.texi
21784 @node Indices
21785 @appendix Indices
21787 @menu
21788 * Environment Variable Index::  Index of environment variables used
21789 * Output Variable Index::       Index of variables set in output files
21790 * Preprocessor Symbol Index::   Index of C preprocessor symbols defined
21791 * Autoconf Macro Index::        Index of Autoconf macros
21792 * M4 Macro Index::              Index of M4, M4sugar, and M4sh macros
21793 * Autotest Macro Index::        Index of Autotest macros
21794 * Program & Function Index::    Index of those with portability problems
21795 * Concept Index::               General index
21796 @end menu
21798 @node Environment Variable Index
21799 @appendixsec Environment Variable Index
21801 This is an alphabetical list of the environment variables that Autoconf
21802 checks.
21804 @printindex ev
21806 @node Output Variable Index
21807 @appendixsec Output Variable Index
21809 This is an alphabetical list of the variables that Autoconf can
21810 substitute into files that it creates, typically one or more
21811 makefiles.  @xref{Setting Output Variables}, for more information
21812 on how this is done.
21814 @printindex ov
21816 @node Preprocessor Symbol Index
21817 @appendixsec Preprocessor Symbol Index
21819 This is an alphabetical list of the C preprocessor symbols that the
21820 Autoconf macros define.  To work with Autoconf, C source code needs to
21821 use these names in @code{#if} or @code{#ifdef} directives.
21823 @printindex cv
21825 @node Autoconf Macro Index
21826 @appendixsec Autoconf Macro Index
21828 This is an alphabetical list of the Autoconf macros.
21829 @ifset shortindexflag
21830 To make the list easier to use, the macros are listed without their
21831 preceding @samp{AC_}.
21832 @end ifset
21834 @printindex AC
21836 @node M4 Macro Index
21837 @appendixsec M4 Macro Index
21839 This is an alphabetical list of the M4, M4sugar, and M4sh macros.
21840 @ifset shortindexflag
21841 To make the list easier to use, the macros are listed without their
21842 preceding @samp{m4_} or @samp{AS_}.
21843 @end ifset
21845 @printindex MS
21847 @node Autotest Macro Index
21848 @appendixsec Autotest Macro Index
21850 This is an alphabetical list of the Autotest macros.
21851 @ifset shortindexflag
21852 To make the list easier to use, the macros are listed without their
21853 preceding @samp{AT_}.
21854 @end ifset
21856 @printindex AT
21858 @node Program & Function Index
21859 @appendixsec Program and Function Index
21861 This is an alphabetical list of the programs and functions whose
21862 portability is discussed in this document.
21864 @printindex pr
21866 @node Concept Index
21867 @appendixsec Concept Index
21869 This is an alphabetical list of the files, tools, and concepts
21870 introduced in this document.
21872 @printindex cp
21874 @bye
21876 @c  LocalWords:  texinfo setfilename autoconf texi settitle setchapternewpage
21877 @c  LocalWords:  setcontentsaftertitlepage finalout ARG ovar varname dvar acx
21878 @c  LocalWords:  makeinfo dvi defcodeindex ev ov CPP cv Autotest mv defindex fn
21879 @c  LocalWords:  shortindexflag iftex ifset acindex ACindex ifclear ahindex fu
21880 @c  LocalWords:  asindex MSindex atindex ATindex auindex hdrindex prindex FIXME
21881 @c  LocalWords:  msindex alloca fnindex Aaarg indices FSF's dircategory ifnames
21882 @c  LocalWords:  direntry autoscan autoreconf autoheader autoupdate config FDs
21883 @c  LocalWords:  testsuite titlepage Elliston Demaille vskip filll ifnottex hmm
21884 @c  LocalWords:  insertcopying Autoconf's detailmenu Automake Libtool Posix ois
21885 @c  LocalWords:  Systemology Checkpointing Changequote INTERCAL changequote dfn
21886 @c  LocalWords:  Quadrigraphs builtins Shellology acconfig Bugward LIBOBJ Imake
21887 @c  LocalWords:  LIBOBJS IFELSE cindex flushright Pinard Metaconfig uref Simons
21888 @c  LocalWords:  distclean uninstall noindent versioning Tromey dir
21889 @c  LocalWords:  SAMS samp aclocal acsite underquoted emph itemx prepend SUBST
21890 @c  LocalWords:  evindex automake Gettext autopoint gettext symlink libtoolize
21891 @c  LocalWords:  defmac INIT tarname ovindex cvindex BUGREPORT PREREQ asis PROG
21892 @c  LocalWords:  SRCDIR srcdir globbing afterwards cmds foos fooo foooo init cd
21893 @c  LocalWords:  builddir timestamp src Imakefile chmod defvar CFLAGS CPPFLAGS
21894 @c  LocalWords:  CXXFLAGS DEFS DHAVE defvarx FCFLAGS FFLAGS LDFLAGS bindir GCC
21895 @c  LocalWords:  datadir datarootdir docdir dvidir htmldir libdir ifnothtml kbd
21896 @c  LocalWords:  includedir infodir libexecdir localedir localstatedir mandir
21897 @c  LocalWords:  oldincludedir pdfdir PDF psdir PostScript sbindir sysconfdir
21898 @c  LocalWords:  sharedstatedir DDATADIR sed tmp pkgdatadir VPATH conf unistd
21899 @c  LocalWords:  undef endif builtin FUNCS ifndef STACKSEG getb GETB YMP fubar
21900 @c  LocalWords:  PRE dest SUBDIRS subdirs fi struct STDC stdlib stddef INTTYPES
21901 @c  LocalWords:  inttypes STDINT stdint AWK AIX Solaris NeXT env EGREP FGREP yy
21902 @c  LocalWords:  LEXLIB YYTEXT lfl nonportable Automake's LN RANLIB byacc INETD
21903 @c  LocalWords:  inetd prog PROGS progs ranlib lmp lXt lX nsl gethostbyname UX
21904 @c  LocalWords:  NextStep isinf isnan glibc IRIX sunmath lm lsunmath pre sizeof
21905 @c  LocalWords:  ld inline malloc putenv setenv FreeBSD realloc SunOS MinGW
21906 @c  LocalWords:  snprintf vsnprintf sprintf vsprintf sscanf gcc strerror ifdef
21907 @c  LocalWords:  strnlen sysconf PAGESIZE unsetenv va fallback memcpy dst FUNC
21908 @c  LocalWords:  PowerPC GNUC libPW pragma Olibcalls CHOWN chown CLOSEDIR VFORK
21909 @c  LocalWords:  closedir FNMATCH fnmatch vfork FSEEKO LARGEFILE fseeko SVR sc
21910 @c  LocalWords:  largefile GETGROUPS getgroups GETLOADAVG DGUX UMAX NLIST KMEM
21911 @c  LocalWords:  SETGID getloadavg nlist GETMNTENT irix
21912 @c  LocalWords:  getmntent UnixWare GETPGRP getpgid getpgrp Posix's pid LSTAT
21913 @c  LocalWords:  lstat rpl MEMCMP memcmp OpenStep MBRTOWC mbrtowc MKTIME mktime
21914 @c  LocalWords:  localtime MMAP mmap OBSTACK obstack obstacks ARGTYPES timeval
21915 @c  LocalWords:  SETPGRP setpgrp defmacx Hurd SETVBUF setvbuf STRCOLL strcoll
21916 @c  LocalWords:  STRTOD strtod DECL STRFTIME strftime SCO UTIME utime VPRINTF
21917 @c  LocalWords:  DOPRNT vprintf doprnt sp unfixable LIBSOURCE LIBSOURCES Eggert
21918 @c  LocalWords:  linux netinet ia Tru XFree DIRENT NDIR dirent ndir multitable
21919 @c  LocalWords:  NAMLEN strlen namlen MKDEV SYSMACROS makedev RESOLV resolv DNS
21920 @c  LocalWords:  inet structs NAMESER arpa NETDB netdb UTekV UTS GCC's kB
21921 @c  LocalWords:  STDBOOL BOOL stdbool conformant cplusplus bool Bool stdarg tm
21922 @c  LocalWords:  ctype strchr strrchr rindex bcopy memmove memchr WEXITSTATUS
21923 @c  LocalWords:  WIFEXITED TIOCGWINSZ GWINSZ termios preprocess preprocessable
21924 @c  LocalWords:  DECLS strdup calloc BLKSIZE blksize RDEV rdev TZNAME tzname pw
21925 @c  LocalWords:  passwd gecos pwd MBSTATE mbstate wchar RETSIGTYPE hup UID uid
21926 @c  LocalWords:  gid ptrdiff uintmax EXEEXT OBJEXT Ae conftest AXP str
21927 @c  LocalWords:  ALIGNOF WERROR Werror cpp HP's WorkShop egcs un fied stdc CXX
21928 @c  LocalWords:  varargs BIGENDIAN Endianness SPARC endianness grep'ed CONST FC
21929 @c  LocalWords:  const STRINGIZE stringizing PARAMS unprotoize protos KCC cxx
21930 @c  LocalWords:  xlC aCC CXXCPP FREEFORM xlf FLIBS FCLIBS ish SRCEXT XTRA LFS
21931 @c  LocalWords:  ISC lcposix MINIX Minix conditionalized inlines hw dD confdefs
21932 @c  LocalWords:  fputs stdout PREPROC ar UFS HFS QNX realtime fstype STATVFS se
21933 @c  LocalWords:  statvfs STATFS statfs func machfile hdr lelf raboof DEFUN GTK
21934 @c  LocalWords:  GTKMM Grmph ified ine defn baz EOF qar Ahhh changecom algol io
21935 @c  LocalWords:  changeword quadrigraphs quadrigraph dnl SGI atoi overquoting
21936 @c  LocalWords:  Aas Wcross sep args namespace undefine bpatsubst popdef dquote
21937 @c  LocalWords:  bregexp Overquote overquotation meisch maisch meische maische
21938 @c  LocalWords:  miscian DIRNAME dirname MKDIR CATFILE XMKMF TRAVOLTA celsius
21939 @c  LocalWords:  EMX emxos Emacsen Korn DYNIX subshell posix Ksh ksh Pdksh Zsh
21940 @c  LocalWords:  pdksh zsh Allbery Lipe Kubota UWS zorglub stderr eval esac lfn
21941 @c  LocalWords:  drivespec Posixy DJGPP doschk prettybird LPT pfew Zsh's yu yaa
21942 @c  LocalWords:  yM uM aM firebird IP subdir misparses ok Unpatched abc bc zA
21943 @c  LocalWords:  CDPATH DUALCASE LINENO prepass Subshells lineno NULLCMD cmp wc
21944 @c  LocalWords:  MAILPATH scanset arg NetBSD Almquist printf expr cp
21945 @c  LocalWords:  Oliva awk Aaaaarg cmd regex xfoo GNV OpenVMS VM
21946 @c  LocalWords:  sparc Proulx nbar nfoo maxdepth acdilrtu TWG mc
21947 @c  LocalWords:  mkdir exe uname OpenBSD Fileutils mktemp umask TMPDIR guid os
21948 @c  LocalWords:  fooXXXXXX Unicos utimes hpux hppa unescaped
21949 @c  LocalWords:  pmake DOS's gmake ifoo DESTDIR autoconfiscated pc coff mips gg
21950 @c  LocalWords:  dec ultrix cpu wildcards rpcc rdtsc powerpc readline
21951 @c  LocalWords:  withval vxworks gless localcache usr LOFF loff CYGWIN Cygwin
21952 @c  LocalWords:  cygwin SIGLIST siglist SYSNDIR SYSDIR ptx lseq rusage elif MSC
21953 @c  LocalWords:  lfoo POUNDBANG lsun NIS getpwnam SYSCALLS RSH INTL lintl aix
21954 @c  LocalWords:  intl lx ldir syslog bsd EPI toolchain netbsd objext de KNR nn
21955 @c  LocalWords:  fication LTLIBOBJS Wdiff TESTDIR atconfig atlocal akim XFAIL
21956 @c  LocalWords:  ChangeLog prepended errexit smallexample TESTSUITEFLAGS GPL er
21957 @c  LocalWords:  installcheck autotest indir Pixley Bothner Eichin Kerberos adl
21958 @c  LocalWords:  DISTCLEANFILES preprocessor's fileutils Stallman Murphey Stenn
21959 @c  LocalWords:  Manfredi Autoconfig TCL FSP david zuhn Blandy MACRODIR Raeburn
21960 @c  LocalWords:  autoconfiscate Savoye Haertel Avera Meyering fdl appendixsec
21961 @c  LocalWords:  printindex american LIBOBJDIR LibdirTest ERLCFLAGS OBJCFLAGS
21962 @c  LocalWords:  VER Gnulib online xyes strcpy TYPEOF typeof OBJC objcc objc ln
21963 @c  LocalWords:  GOBJC OTP ERLC erl valloc decr dumpdef errprint incr
21964 @c  LocalWords:  esyscmd len maketemp pushdef substr syscmd sysval translit txt
21965 @c  LocalWords:  sinclude foreach myvar tolower toupper uniq BASENAME STDIN
21966 @c  LocalWords:  Dynix descrips basename aname cname macroexpands xno xcheck
21967 @c  LocalWords:  LIBREADLINE lreadline lncurses libreadline
21969 @c Local Variables:
21970 @c fill-column: 72
21971 @c ispell-local-dictionary: "american"
21972 @c indent-tabs-mode: nil
21973 @c whitespace-check-buffer-indent: nil
21974 @c End: