Fix off-by-one bug in _m4_shiftn.
[autoconf.git] / doc / autoconf.texi
blobb996356942e0a0ba385e040329d7253c1607f1a3
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 --debug
1339 @itemx -d
1340 Don't remove temporary files.
1342 @item --include=@var{dir}
1343 @itemx -I @var{dir}
1344 Append @var{dir} to the include path.  Multiple invocations accumulate.
1346 @item --prepend-include=@var{dir}
1347 @itemx -B @var{dir}
1348 Prepend @var{dir} to the include path.  Multiple invocations accumulate.
1349 @end table
1351 @node ifnames Invocation
1352 @section Using @command{ifnames} to List Conditionals
1353 @cindex @command{ifnames}
1355 @command{ifnames} can help you write @file{configure.ac} for a software
1356 package.  It prints the identifiers that the package already uses in C
1357 preprocessor conditionals.  If a package has already been set up to have
1358 some portability, @command{ifnames} can thus help you figure out what its
1359 @command{configure} needs to check for.  It may help fill in some gaps in a
1360 @file{configure.ac} generated by @command{autoscan} (@pxref{autoscan
1361 Invocation}).
1363 @command{ifnames} scans all of the C source files named on the command line
1364 (or the standard input, if none are given) and writes to the standard
1365 output a sorted list of all the identifiers that appear in those files
1366 in @code{#if}, @code{#elif}, @code{#ifdef}, or @code{#ifndef}
1367 directives.  It prints each identifier on a line, followed by a
1368 space-separated list of the files in which that identifier occurs.
1370 @noindent
1371 @command{ifnames} accepts the following options:
1373 @table @option
1374 @item --help
1375 @itemx -h
1376 Print a summary of the command line options and exit.
1378 @item --version
1379 @itemx -V
1380 Print the version number of Autoconf and exit.
1381 @end table
1383 @node autoconf Invocation
1384 @section Using @command{autoconf} to Create @command{configure}
1385 @cindex @command{autoconf}
1387 To create @command{configure} from @file{configure.ac}, run the
1388 @command{autoconf} program with no arguments.  @command{autoconf} processes
1389 @file{configure.ac} with the M4 macro processor, using the
1390 Autoconf macros.  If you give @command{autoconf} an argument, it reads that
1391 file instead of @file{configure.ac} and writes the configuration script
1392 to the standard output instead of to @command{configure}.  If you give
1393 @command{autoconf} the argument @option{-}, it reads from the standard
1394 input instead of @file{configure.ac} and writes the configuration script
1395 to the standard output.
1397 The Autoconf macros are defined in several files.  Some of the files are
1398 distributed with Autoconf; @command{autoconf} reads them first.  Then it
1399 looks for the optional file @file{acsite.m4} in the directory that
1400 contains the distributed Autoconf macro files, and for the optional file
1401 @file{aclocal.m4} in the current directory.  Those files can contain
1402 your site's or the package's own Autoconf macro definitions
1403 (@pxref{Writing Autoconf Macros}, for more information).  If a macro is
1404 defined in more than one of the files that @command{autoconf} reads, the
1405 last definition it reads overrides the earlier ones.
1407 @command{autoconf} accepts the following options:
1409 @table @option
1410 @item --help
1411 @itemx -h
1412 Print a summary of the command line options and exit.
1414 @item --version
1415 @itemx -V
1416 Print the version number of Autoconf and exit.
1418 @item --verbose
1419 @itemx -v
1420 Report processing steps.
1422 @item --debug
1423 @itemx -d
1424 Don't remove the temporary files.
1426 @item --force
1427 @itemx -f
1428 Remake @file{configure} even if newer than its input files.
1430 @item --include=@var{dir}
1431 @itemx -I @var{dir}
1432 Append @var{dir} to the include path.  Multiple invocations accumulate.
1434 @item --prepend-include=@var{dir}
1435 @itemx -B @var{dir}
1436 Prepend @var{dir} to the include path.  Multiple invocations accumulate.
1438 @item --output=@var{file}
1439 @itemx -o @var{file}
1440 Save output (script or trace) to @var{file}.  The file @option{-} stands
1441 for the standard output.
1443 @item --warnings=@var{category}
1444 @itemx -W @var{category}
1445 @evindex WARNINGS
1446 Report the warnings related to @var{category} (which can actually be a
1447 comma separated list).  @xref{Reporting Messages}, macro
1448 @code{AC_DIAGNOSE}, for a comprehensive list of categories.  Special
1449 values include:
1451 @table @samp
1452 @item all
1453 report all the warnings
1455 @item none
1456 report none
1458 @item error
1459 treats warnings as errors
1461 @item no-@var{category}
1462 disable warnings falling into @var{category}
1463 @end table
1465 Warnings about @samp{syntax} are enabled by default, and the environment
1466 variable @env{WARNINGS}, a comma separated list of categories, is
1467 honored as well.  Passing @option{-W @var{category}} actually behaves as if
1468 you had passed @option{--warnings syntax,$WARNINGS,@var{category}}.  If
1469 you want to disable the defaults and @env{WARNINGS}, but (for example)
1470 enable the warnings about obsolete constructs, you would use @option{-W
1471 none,obsolete}.
1473 @cindex Back trace
1474 @cindex Macro invocation stack
1475 Because @command{autoconf} uses @command{autom4te} behind the scenes, it
1476 displays a back trace for errors, but not for warnings; if you want
1477 them, just pass @option{-W error}.  @xref{autom4te Invocation}, for some
1478 examples.
1480 @item --trace=@var{macro}[:@var{format}]
1481 @itemx -t @var{macro}[:@var{format}]
1482 Do not create the @command{configure} script, but list the calls to
1483 @var{macro} according to the @var{format}.  Multiple @option{--trace}
1484 arguments can be used to list several macros.  Multiple @option{--trace}
1485 arguments for a single macro are not cumulative; instead, you should
1486 just make @var{format} as long as needed.
1488 The @var{format} is a regular string, with newlines if desired, and
1489 several special escape codes.  It defaults to @samp{$f:$l:$n:$%}; see
1490 @ref{autom4te Invocation}, for details on the @var{format}.
1492 @item --initialization
1493 @itemx -i
1494 By default, @option{--trace} does not trace the initialization of the
1495 Autoconf macros (typically the @code{AC_DEFUN} definitions).  This
1496 results in a noticeable speedup, but can be disabled by this option.
1497 @end table
1500 It is often necessary to check the content of a @file{configure.ac}
1501 file, but parsing it yourself is extremely fragile and error-prone.  It
1502 is suggested that you rely upon @option{--trace} to scan
1503 @file{configure.ac}.  For instance, to find the list of variables that
1504 are substituted, use:
1506 @example
1507 @group
1508 $ @kbd{autoconf -t AC_SUBST}
1509 configure.ac:2:AC_SUBST:ECHO_C
1510 configure.ac:2:AC_SUBST:ECHO_N
1511 configure.ac:2:AC_SUBST:ECHO_T
1512 @i{More traces deleted}
1513 @end group
1514 @end example
1516 @noindent
1517 The example below highlights the difference between @samp{$@@},
1518 @samp{$*}, and @samp{$%}.
1520 @example
1521 @group
1522 $ @kbd{cat configure.ac}
1523 AC_DEFINE(This, is, [an
1524 [example]])
1525 $ @kbd{autoconf -t 'AC_DEFINE:@@: $@@}
1526 *: $*
1527 %: $%'
1528 @@: [This],[is],[an
1529 [example]]
1530 *: This,is,an
1531 [example]
1532 %: This:is:an [example]
1533 @end group
1534 @end example
1536 @noindent
1537 The @var{format} gives you a lot of freedom:
1539 @example
1540 @group
1541 $ @kbd{autoconf -t 'AC_SUBST:$$ac_subst@{"$1"@} = "$f:$l";'}
1542 $ac_subst@{"ECHO_C"@} = "configure.ac:2";
1543 $ac_subst@{"ECHO_N"@} = "configure.ac:2";
1544 $ac_subst@{"ECHO_T"@} = "configure.ac:2";
1545 @i{More traces deleted}
1546 @end group
1547 @end example
1549 @noindent
1550 A long @var{separator} can be used to improve the readability of complex
1551 structures, and to ease their parsing (for instance when no single
1552 character is suitable as a separator):
1554 @example
1555 @group
1556 $ @kbd{autoconf -t 'AM_MISSING_PROG:$@{|:::::|@}*'}
1557 ACLOCAL|:::::|aclocal|:::::|$missing_dir
1558 AUTOCONF|:::::|autoconf|:::::|$missing_dir
1559 AUTOMAKE|:::::|automake|:::::|$missing_dir
1560 @i{More traces deleted}
1561 @end group
1562 @end example
1564 @node autoreconf Invocation
1565 @section Using @command{autoreconf} to Update @command{configure} Scripts
1566 @cindex @command{autoreconf}
1568 Installing the various components of the @acronym{GNU} Build System can be
1569 tedious: running @command{autopoint} for Gettext, @command{automake} for
1570 @file{Makefile.in} etc.@: in each directory.  It may be needed either
1571 because some tools such as @command{automake} have been updated on your
1572 system, or because some of the sources such as @file{configure.ac} have
1573 been updated, or finally, simply in order to install the @acronym{GNU} Build
1574 System in a fresh tree.
1576 @command{autoreconf} runs @command{autoconf}, @command{autoheader},
1577 @command{aclocal}, @command{automake}, @command{libtoolize}, and
1578 @command{autopoint} (when appropriate) repeatedly to update the
1579 @acronym{GNU} Build System in the specified directories and their
1580 subdirectories (@pxref{Subdirectories}).  By default, it only remakes
1581 those files that are older than their sources.  The environment variables
1582 @env{AUTOCONF}, @env{AUTOHEADER}, @env{AUTOMAKE}, @env{ACLOCAL},
1583 @env{AUTOPOINT}, @env{LIBTOOLIZE}, @env{M4}, and @env{MAKE} may be used
1584 to override the invocation of the respective tools.
1586 If you install a new version of some tool, you can make
1587 @command{autoreconf} remake @emph{all} of the files by giving it the
1588 @option{--force} option.
1590 @xref{Automatic Remaking}, for Make rules to automatically
1591 rebuild @command{configure} scripts when their source files change.  That
1592 method handles the timestamps of configuration header templates
1593 properly, but does not pass @option{--autoconf-dir=@var{dir}} or
1594 @option{--localdir=@var{dir}}.
1596 @cindex Gettext
1597 @cindex @command{autopoint}
1598 Gettext supplies the @command{autopoint} command to add translation
1599 infrastructure to a source package.  If you use @command{autopoint},
1600 your @file{configure.ac} should invoke both @code{AM_GNU_GETTEXT} and
1601 @code{AM_GNU_GETTEXT_VERSION(@var{gettext-version})}.  @xref{autopoint
1602 Invocation, , Invoking the @code{autopoint} Program, gettext,
1603 @acronym{GNU} @code{gettext} utilities}, for further details.
1605 @noindent
1606 @command{autoreconf} accepts the following options:
1608 @table @option
1609 @item --help
1610 @itemx -h
1611 Print a summary of the command line options and exit.
1613 @item --version
1614 @itemx -V
1615 Print the version number of Autoconf and exit.
1617 @item --verbose
1618 @itemx -V
1619 Print the name of each directory @command{autoreconf} examines and the
1620 commands it runs.  If given two or more times, pass @option{--verbose}
1621 to subordinate tools that support it.
1623 @item --debug
1624 @itemx -d
1625 Don't remove the temporary files.
1627 @item --force
1628 @itemx -f
1629 Remake even @file{configure} scripts and configuration headers that are
1630 newer than their input files (@file{configure.ac} and, if present,
1631 @file{aclocal.m4}).
1633 @item --install
1634 @itemx -i
1635 Install the missing auxiliary files in the package.  By default, files
1636 are copied; this can be changed with @option{--symlink}.
1638 If deemed appropriate, this option triggers calls to
1639 @samp{automake --add-missing},
1640 @samp{libtoolize}, @samp{autopoint}, etc.
1642 @item --no-recursive
1643 Do not rebuild files in subdirectories to configure (see @ref{Subdirectories},
1644 macro @code{AC_CONFIG_SUBDIRS}).
1646 @item --symlink
1647 @itemx -s
1648 When used with @option{--install}, install symbolic links to the missing
1649 auxiliary files instead of copying them.
1651 @item --make
1652 @itemx -m
1653 When the directories were configured, update the configuration by
1654 running @samp{./config.status --recheck && ./config.status}, and then
1655 run @samp{make}.
1657 @item --include=@var{dir}
1658 @itemx -I @var{dir}
1659 Append @var{dir} to the include path.  Multiple invocations accumulate.
1660 Passed on to @command{autoconf} and @command{autoheader} internally.
1662 @item --prepend-include=@var{dir}
1663 @itemx -B @var{dir}
1664 Prepend @var{dir} to the include path.  Multiple invocations accumulate.
1665 Passed on to @command{autoconf} and @command{autoheader} internally.
1667 @item --warnings=@var{category}
1668 @itemx -W @var{category}
1669 @evindex WARNINGS
1670 Report the warnings related to @var{category} (which can actually be a
1671 comma separated list).
1673 @table @samp
1674 @item cross
1675 related to cross compilation issues.
1677 @item obsolete
1678 report the uses of obsolete constructs.
1680 @item portability
1681 portability issues
1683 @item syntax
1684 dubious syntactic constructs.
1686 @item all
1687 report all the warnings
1689 @item none
1690 report none
1692 @item error
1693 treats warnings as errors
1695 @item no-@var{category}
1696 disable warnings falling into @var{category}
1697 @end table
1699 Warnings about @samp{syntax} are enabled by default, and the environment
1700 variable @env{WARNINGS}, a comma separated list of categories, is
1701 honored as well.  Passing @option{-W @var{category}} actually behaves as if
1702 you had passed @option{--warnings syntax,$WARNINGS,@var{category}}.  If
1703 you want to disable the defaults and @env{WARNINGS}, but (for example)
1704 enable the warnings about obsolete constructs, you would use @option{-W
1705 none,obsolete}.
1706 @end table
1708 If you want @command{autoreconf} to pass flags that are not listed here
1709 on to @command{aclocal}, set @code{ACLOCAL_AMFLAGS} in your @file{Makefile.am}.
1710 Due to a limitation in the Autoconf implementation these flags currently
1711 must be set on a single line in @file{Makefile.am}, without any
1712 backslash-newlines.
1714 @c ========================================= Initialization and Output Files.
1716 @node Setup
1717 @chapter Initialization and Output Files
1719 Autoconf-generated @command{configure} scripts need some information about
1720 how to initialize, such as how to find the package's source files and
1721 about the output files to produce.  The following sections describe the
1722 initialization and the creation of output files.
1724 @menu
1725 * Initializing configure::      Option processing etc.
1726 * Versioning::                  Dealing with Autoconf versions
1727 * Notices::                     Copyright, version numbers in @command{configure}
1728 * Input::                       Where Autoconf should find files
1729 * Output::                      Outputting results from the configuration
1730 * Configuration Actions::       Preparing the output based on results
1731 * Configuration Files::         Creating output files
1732 * Makefile Substitutions::      Using output variables in makefiles
1733 * Configuration Headers::       Creating a configuration header file
1734 * Configuration Commands::      Running arbitrary instantiation commands
1735 * Configuration Links::         Links depending on the configuration
1736 * Subdirectories::              Configuring independent packages together
1737 * Default Prefix::              Changing the default installation prefix
1738 @end menu
1740 @node Initializing configure
1741 @section Initializing @command{configure}
1743 Every @command{configure} script must call @code{AC_INIT} before doing
1744 anything else.  The only other required macro is @code{AC_OUTPUT}
1745 (@pxref{Output}).
1747 @anchor{AC_INIT}
1748 @defmac AC_INIT (@var{package}, @var{version}, @ovar{bug-report}, @
1749   @ovar{tarname})
1750 @acindex{INIT}
1751 Process any command-line arguments and perform various initializations
1752 and verifications.
1754 Set the name of the @var{package} and its @var{version}.  These are
1755 typically used in @option{--version} support, including that of
1756 @command{configure}.  The optional argument @var{bug-report} should be
1757 the email to which users should send bug reports.  The package
1758 @var{tarname} differs from @var{package}: the latter designates the full
1759 package name (e.g., @samp{GNU Autoconf}), while the former is meant for
1760 distribution tar ball names (e.g., @samp{autoconf}).  It defaults to
1761 @var{package} with @samp{GNU } stripped, lower-cased, and all characters
1762 other than alphanumerics and underscores are changed to @samp{-}.
1764 It is preferable that the arguments of @code{AC_INIT} be static, i.e.,
1765 there should not be any shell computation, but they can be computed by
1768 The following M4 macros (e.g., @code{AC_PACKAGE_NAME}), output variables
1769 (e.g., @code{PACKAGE_NAME}), and preprocessor symbols (e.g.,
1770 @code{PACKAGE_NAME}), are defined by @code{AC_INIT}:
1772 @table @asis
1773 @item @code{AC_PACKAGE_NAME}, @code{PACKAGE_NAME}
1774 @acindex{PACKAGE_NAME}
1775 @ovindex PACKAGE_NAME
1776 @cvindex PACKAGE_NAME
1777 Exactly @var{package}.
1779 @item @code{AC_PACKAGE_TARNAME}, @code{PACKAGE_TARNAME}
1780 @acindex{PACKAGE_TARNAME}
1781 @ovindex PACKAGE_TARNAME
1782 @cvindex PACKAGE_TARNAME
1783 Exactly @var{tarname}.
1785 @item @code{AC_PACKAGE_VERSION}, @code{PACKAGE_VERSION}
1786 @acindex{PACKAGE_VERSION}
1787 @ovindex PACKAGE_VERSION
1788 @cvindex PACKAGE_VERSION
1789 Exactly @var{version}.
1791 @item @code{AC_PACKAGE_STRING}, @code{PACKAGE_STRING}
1792 @acindex{PACKAGE_STRING}
1793 @ovindex PACKAGE_STRING
1794 @cvindex PACKAGE_STRING
1795 Exactly @samp{@var{package} @var{version}}.
1797 @item @code{AC_PACKAGE_BUGREPORT}, @code{PACKAGE_BUGREPORT}
1798 @acindex{PACKAGE_BUGREPORT}
1799 @ovindex PACKAGE_BUGREPORT
1800 @cvindex PACKAGE_BUGREPORT
1801 Exactly @var{bug-report}.
1802 @end table
1803 @end defmac
1805 If your @command{configure} script does its own option processing, it
1806 should inspect @samp{$@@} or @samp{$*} immediately after calling
1807 @code{AC_INIT}, because other Autoconf macros liberally use the
1808 @command{set} command to process strings, and this has the side effect
1809 of updating @samp{$@@} and @samp{$*}.  However, we suggest that you use
1810 standard macros like @code{AC_ARG_ENABLE} instead of attempting to
1811 implement your own option processing.  @xref{Site Configuration}.
1813 @node Versioning
1814 @section Dealing with Autoconf versions
1815 @cindex Autoconf version
1816 @cindex version, Autoconf
1818 The following optional macros can be used to help choose the minimum
1819 version of Autoconf that can successfully compile a given
1820 @file{configure.ac}.
1822 @defmac AC_PREREQ (@var{version})
1823 @acindex{PREREQ}
1824 @cindex Version
1825 Ensure that a recent enough version of Autoconf is being used.  If the
1826 version of Autoconf being used to create @command{configure} is
1827 earlier than @var{version}, print an error message to the standard
1828 error output and exit with failure (exit status is 63).  For example:
1830 @example
1831 AC_PREREQ([@value{VERSION}])
1832 @end example
1834 This macro is the only macro that may be used before @code{AC_INIT}, but
1835 for consistency, you are invited not to do so.
1836 @end defmac
1838 @defmac AC_AUTOCONF_VERSION
1839 @acindex{AUTOCONF_VERSION}
1840 This macro was introduced in Autoconf 2.62.  It identifies the version
1841 of Autoconf that is currently parsing the input file, in a format
1842 suitable for @code{m4_version_compare} (@pxref{m4_version_compare}); in
1843 other words, for this release of Autoconf, its value is
1844 @samp{@value{VERSION}}.  One potential use of this macro is for writing
1845 conditional fallbacks based on when a feature was added to Autoconf,
1846 rather than using @code{AC_PREREQ} to require the newer version of
1847 Autoconf.  However, remember that the Autoconf philosophy favors feature
1848 checks over version checks.
1850 You should not expand this macro directly; use
1851 @samp{m4_defn([AC_AUTOCONF_VERSION])} instead.  This is because some
1852 users might
1853 have a beta version of Autoconf installed, with arbitrary letters
1854 included in its version string.  This means it is possible for the
1855 version string to contain the name of a defined macro, such that
1856 expanding @code{AC_AUTOCONF_VERSION} would trigger the expansion of that
1857 macro during rescanning, and change the version string to be different
1858 than what you intended to check.
1859 @end defmac
1861 @node Notices
1862 @section Notices in @command{configure}
1863 @cindex Notices in @command{configure}
1865 The following macros manage version numbers for @command{configure}
1866 scripts.  Using them is optional.
1868 @defmac AC_COPYRIGHT (@var{copyright-notice})
1869 @acindex{COPYRIGHT}
1870 @cindex Copyright Notice
1871 State that, in addition to the Free Software Foundation's copyright on
1872 the Autoconf macros, parts of your @command{configure} are covered by the
1873 @var{copyright-notice}.
1875 The @var{copyright-notice} shows up in both the head of
1876 @command{configure} and in @samp{configure --version}.
1877 @end defmac
1880 @defmac AC_REVISION (@var{revision-info})
1881 @acindex{REVISION}
1882 @cindex Revision
1883 Copy revision stamp @var{revision-info} into the @command{configure}
1884 script, with any dollar signs or double-quotes removed.  This macro lets
1885 you put a revision stamp from @file{configure.ac} into @command{configure}
1886 without @acronym{RCS} or @acronym{CVS} changing it when you check in
1887 @command{configure}.  That way, you can determine easily which revision of
1888 @file{configure.ac} a particular @command{configure} corresponds to.
1890 For example, this line in @file{configure.ac}:
1892 @c The @w prevents RCS from changing the example in the manual.
1893 @example
1894 AC_REVISION([@w{$}Revision: 1.30 $])
1895 @end example
1897 @noindent
1898 produces this in @command{configure}:
1900 @example
1901 #!/bin/sh
1902 # From configure.ac Revision: 1.30
1903 @end example
1904 @end defmac
1907 @node Input
1908 @section Finding @command{configure} Input
1910 @anchor{AC_CONFIG_SRCDIR}
1911 @defmac AC_CONFIG_SRCDIR (@var{unique-file-in-source-dir})
1912 @acindex{CONFIG_SRCDIR}
1913 @var{unique-file-in-source-dir} is some file that is in the package's
1914 source directory; @command{configure} checks for this file's existence to
1915 make sure that the directory that it is told contains the source code in
1916 fact does.  Occasionally people accidentally specify the wrong directory
1917 with @option{--srcdir}; this is a safety check.  @xref{configure
1918 Invocation}, for more information.
1919 @end defmac
1922 @c FIXME: Remove definitively once --install explained.
1924 @c Small packages may store all their macros in @code{aclocal.m4}.  As the
1925 @c set of macros grows, or for maintenance reasons, a maintainer may prefer
1926 @c to split the macros in several files.  In this case, Autoconf must be
1927 @c told which files to load, and in which order.
1929 @c @defmac AC_INCLUDE (@var{file}@dots{})
1930 @c @acindex{INCLUDE}
1931 @c @c FIXME: There is no longer shell globbing.
1932 @c Read the macro definitions that appear in the listed files.  A list of
1933 @c space-separated file names or shell globbing patterns is expected.  The
1934 @c files are read in the order they're listed.
1936 @c Because the order of definition of macros is important (only the last
1937 @c definition of a macro is used), beware that it is @code{AC_INIT} that
1938 @c loads @file{acsite.m4} and @file{aclocal.m4}.  Note that
1939 @c @code{AC_INCLUDE}ing a file before @code{AC_INIT} or within
1940 @c @file{aclocal.m4} is different from doing so after @code{AC_INIT}: in
1941 @c the latter case, non-macro lines from included files may end up in the
1942 @c @file{configure} script, whereas in the former case, they'd be discarded
1943 @c just like any text that appear before @code{AC_INIT}.
1944 @c @end defmac
1946 Packages that do manual configuration or use the @command{install} program
1947 might need to tell @command{configure} where to find some other shell
1948 scripts by calling @code{AC_CONFIG_AUX_DIR}, though the default places
1949 it looks are correct for most cases.
1951 @defmac AC_CONFIG_AUX_DIR (@var{dir})
1952 @acindex{CONFIG_AUX_DIR}
1953 Use the auxiliary build tools (e.g., @file{install-sh},
1954 @file{config.sub}, @file{config.guess}, Cygnus @command{configure},
1955 Automake and Libtool scripts, etc.)@: that are in directory @var{dir}.
1956 These are auxiliary files used in configuration.  @var{dir} can be
1957 either absolute or relative to @file{@var{srcdir}}.  The default is
1958 @file{@var{srcdir}} or @file{@var{srcdir}/..} or
1959 @file{@var{srcdir}/../..}, whichever is the first that contains
1960 @file{install-sh}.  The other files are not checked for, so that using
1961 @code{AC_PROG_INSTALL} does not automatically require distributing the
1962 other auxiliary files.  It checks for @file{install.sh} also, but that
1963 name is obsolete because some @command{make} have a rule that creates
1964 @file{install} from it if there is no makefile.
1966 The auxiliary directory is commonly named @file{build-aux}.
1967 If you need portability to @acronym{DOS} variants, do not name the
1968 auxiliary directory @file{aux}.  @xref{File System Conventions}.
1969 @end defmac
1971 @defmac AC_REQUIRE_AUX_FILE (@var{file})
1972 @acindex{REQUIRE_AUX_FILE}
1973 Declares that @var{file} is expected in the directory defined above.  In
1974 Autoconf proper, this macro does nothing: its sole purpose is to be
1975 traced by third-party tools to produce a list of expected auxiliary
1976 files.  For instance it is called by macros like @code{AC_PROG_INSTALL}
1977 (@pxref{Particular Programs}) or @code{AC_CANONICAL_BUILD}
1978 (@pxref{Canonicalizing}) to register the auxiliary files they need.
1979 @end defmac
1981 Similarly, packages that use @command{aclocal} should declare where
1982 local macros can be found using @code{AC_CONFIG_MACRO_DIR}.
1984 @defmac AC_CONFIG_MACRO_DIR (@var{dir})
1985 @acindex{CONFIG_MACRO_DIR}
1986 Specify @var{dir} as the location of additional local Autoconf macros.
1987 This macro is intended for use by future versions of commands like
1988 @command{autoreconf} that trace macro calls.  It should be called
1989 directly from @file{configure.ac} so that tools that install macros for
1990 @command{aclocal} can find the macros' declarations.
1992 Note that if you use @command{aclocal} from Automake to generate
1993 @file{aclocal.m4}, you must also set @code{ACLOCAL_AMFLAGS = -I
1994 @var{dir}} in your top-level @file{Makefile.am}.  Due to a limitation in
1995 the Autoconf implementation of @command{autoreconf}, these include
1996 directives currently must be set on a single line in @file{Makefile.am},
1997 without any backslash-newlines.
1998 @end defmac
2001 @node Output
2002 @section Outputting Files
2003 @cindex Outputting files
2005 Every Autoconf script, e.g., @file{configure.ac}, should finish by
2006 calling @code{AC_OUTPUT}.  That is the macro that generates and runs
2007 @file{config.status}, which in turn creates the makefiles and any
2008 other files resulting from configuration.  This is the only required
2009 macro besides @code{AC_INIT} (@pxref{Input}).
2011 @anchor{AC_OUTPUT}
2012 @defmac AC_OUTPUT
2013 @acindex{OUTPUT}
2014 @cindex Instantiation
2015 Generate @file{config.status} and launch it.  Call this macro once, at
2016 the end of @file{configure.ac}.
2018 @file{config.status} performs all the configuration actions: all the
2019 output files (see @ref{Configuration Files}, macro
2020 @code{AC_CONFIG_FILES}), header files (see @ref{Configuration Headers},
2021 macro @code{AC_CONFIG_HEADERS}), commands (see @ref{Configuration
2022 Commands}, macro @code{AC_CONFIG_COMMANDS}), links (see
2023 @ref{Configuration Links}, macro @code{AC_CONFIG_LINKS}), subdirectories
2024 to configure (see @ref{Subdirectories}, macro @code{AC_CONFIG_SUBDIRS})
2025 are honored.
2027 The location of your @code{AC_OUTPUT} invocation is the exact point
2028 where configuration actions are taken: any code afterwards is
2029 executed by @command{configure} once @command{config.status} was run.  If
2030 you want to bind actions to @command{config.status} itself
2031 (independently of whether @command{configure} is being run), see
2032 @ref{Configuration Commands, , Running Arbitrary Configuration
2033 Commands}.
2034 @end defmac
2036 Historically, the usage of @code{AC_OUTPUT} was somewhat different.
2037 @xref{Obsolete Macros}, for a description of the arguments that
2038 @code{AC_OUTPUT} used to support.
2041 If you run @command{make} in subdirectories, you should run it using the
2042 @command{make} variable @code{MAKE}.  Most versions of @command{make} set
2043 @code{MAKE} to the name of the @command{make} program plus any options it
2044 was given.  (But many do not include in it the values of any variables
2045 set on the command line, so those are not passed on automatically.)
2046 Some old versions of @command{make} do not set this variable.  The
2047 following macro allows you to use it even with those versions.
2049 @anchor{AC_PROG_MAKE_SET}
2050 @defmac AC_PROG_MAKE_SET
2051 @acindex{PROG_MAKE_SET}
2052 @ovindex SET_MAKE
2053 If the Make command, @code{$MAKE} if set or else @samp{make}, predefines
2054 @code{$(MAKE)}, define output variable @code{SET_MAKE} to be empty.
2055 Otherwise, define @code{SET_MAKE} to a macro definition that sets
2056 @code{$(MAKE)}, such as @samp{MAKE=make}.  Calls @code{AC_SUBST} for
2057 @code{SET_MAKE}.
2058 @end defmac
2060 If you use this macro, place a line like this in each @file{Makefile.in}
2061 that runs @command{MAKE} on other directories:
2063 @example
2064 @@SET_MAKE@@
2065 @end example
2069 @node Configuration Actions
2070 @section Performing Configuration Actions
2071 @cindex Configuration actions
2073 @file{configure} is designed so that it appears to do everything itself,
2074 but there is actually a hidden slave: @file{config.status}.
2075 @file{configure} is in charge of examining your system, but it is
2076 @file{config.status} that actually takes the proper actions based on the
2077 results of @file{configure}.  The most typical task of
2078 @file{config.status} is to @emph{instantiate} files.
2080 This section describes the common behavior of the four standard
2081 instantiating macros: @code{AC_CONFIG_FILES}, @code{AC_CONFIG_HEADERS},
2082 @code{AC_CONFIG_COMMANDS} and @code{AC_CONFIG_LINKS}.  They all
2083 have this prototype:
2085 @c FIXME: Can't use @ovar here, Texinfo 4.0 goes lunatic and emits something
2086 @c awful.
2087 @example
2088 AC_CONFIG_FOOS(@var{tag}@dots{}, [@var{commands}], [@var{init-cmds}])
2089 @end example
2091 @noindent
2092 where the arguments are:
2094 @table @var
2095 @item tag@dots{}
2096 A blank-or-newline-separated list of tags, which are typically the names of
2097 the files to instantiate.
2099 You are encouraged to use literals as @var{tags}.  In particular, you
2100 should avoid
2102 @example
2103 @dots{} && my_foos="$my_foos fooo"
2104 @dots{} && my_foos="$my_foos foooo"
2105 AC_CONFIG_FOOS([$my_foos])
2106 @end example
2108 @noindent
2109 and use this instead:
2111 @example
2112 @dots{} && AC_CONFIG_FOOS([fooo])
2113 @dots{} && AC_CONFIG_FOOS([foooo])
2114 @end example
2116 The macros @code{AC_CONFIG_FILES} and @code{AC_CONFIG_HEADERS} use
2117 special @var{tag} values: they may have the form @samp{@var{output}} or
2118 @samp{@var{output}:@var{inputs}}.  The file @var{output} is instantiated
2119 from its templates, @var{inputs} (defaulting to @samp{@var{output}.in}).
2121 @samp{AC_CONFIG_FILES([Makefile:boiler/top.mk:boiler/bot.mk)]},
2122 for example, asks for
2123 the creation of the file @file{Makefile} that contains the expansion of the
2124 output variables in the concatenation of @file{boiler/top.mk} and
2125 @file{boiler/bot.mk}.
2127 The special value @samp{-} might be used to denote the standard output
2128 when used in @var{output}, or the standard input when used in the
2129 @var{inputs}.  You most probably don't need to use this in
2130 @file{configure.ac}, but it is convenient when using the command line
2131 interface of @file{./config.status}, see @ref{config.status Invocation},
2132 for more details.
2134 The @var{inputs} may be absolute or relative file names.  In the latter
2135 case they are first looked for in the build tree, and then in the source
2136 tree.
2138 @item commands
2139 Shell commands output literally into @file{config.status}, and
2140 associated with a tag that the user can use to tell @file{config.status}
2141 which the commands to run.  The commands are run each time a @var{tag}
2142 request is given to @file{config.status}, typically each time the file
2143 @file{@var{tag}} is created.
2145 The variables set during the execution of @command{configure} are
2146 @emph{not} available here: you first need to set them via the
2147 @var{init-cmds}.  Nonetheless the following variables are precomputed:
2149 @table @code
2150 @item srcdir
2151 The name of the top source directory, assuming that the working
2152 directory is the top build directory.  This
2153 is what the @command{configure} option @option{--srcdir} sets.
2155 @item ac_top_srcdir
2156 The name of the top source directory, assuming that the working
2157 directory is the current build directory.
2160 @item ac_top_build_prefix
2161 The name of the top build directory, assuming that the working
2162 directory is the current build directory.
2163 It can be empty, or else ends with a slash, so that you may concatenate
2166 @item ac_srcdir
2167 The name of the corresponding source directory, assuming that the
2168 working directory is the current build directory.
2169 @end table
2171 @noindent
2172 The @dfn{current} directory refers to the directory (or
2173 pseudo-directory) containing the input part of @var{tags}.  For
2174 instance, running
2176 @example
2177 AC_CONFIG_COMMANDS([deep/dir/out:in/in.in], [@dots{}], [@dots{}])
2178 @end example
2180 @noindent
2181  with @option{--srcdir=../package} produces the following values:
2183 @example
2184 # Argument of --srcdir
2185 srcdir='../package'
2186 # Reversing deep/dir
2187 ac_top_build_prefix='../../'
2188 # Concatenation of $ac_top_build_prefix and srcdir
2189 ac_top_srcdir='../../../package'
2190 # Concatenation of $ac_top_srcdir and deep/dir
2191 ac_srcdir='../../../package/deep/dir'
2192 @end example
2194 @noindent
2195 independently of @samp{in/in.in}.
2197 @item init-cmds
2198 Shell commands output @emph{unquoted} near the beginning of
2199 @file{config.status}, and executed each time @file{config.status} runs
2200 (regardless of the tag).  Because they are unquoted, for example,
2201 @samp{$var} is output as the value of @code{var}.  @var{init-cmds}
2202 is typically used by @file{configure} to give @file{config.status} some
2203 variables it needs to run the @var{commands}.
2205 You should be extremely cautious in your variable names: all the
2206 @var{init-cmds} share the same name space and may overwrite each other
2207 in unpredictable ways.  Sorry@enddots{}
2208 @end table
2210 All these macros can be called multiple times, with different
2211 @var{tag} values, of course!
2214 @node Configuration Files
2215 @section Creating Configuration Files
2216 @cindex Creating configuration files
2217 @cindex Configuration file creation
2219 Be sure to read the previous section, @ref{Configuration Actions}.
2221 @anchor{AC_CONFIG_FILES}
2222 @defmac AC_CONFIG_FILES (@var{file}@dots{}, @ovar{cmds}, @ovar{init-cmds})
2223 @acindex{CONFIG_FILES}
2224 Make @code{AC_OUTPUT} create each @file{@var{file}} by copying an input
2225 file (by default @file{@var{file}.in}), substituting the output variable
2226 values.
2227 @c Before we used to have this feature, which was later rejected
2228 @c because it complicates the writing of makefiles:
2229 @c If the file would be unchanged, it is left untouched, to preserve
2230 @c timestamp.
2231 This macro is one of the instantiating macros; see @ref{Configuration
2232 Actions}.  @xref{Makefile Substitutions}, for more information on using
2233 output variables.  @xref{Setting Output Variables}, for more information
2234 on creating them.  This macro creates the directory that the file is in
2235 if it doesn't exist.  Usually, makefiles are created this way,
2236 but other files, such as @file{.gdbinit}, can be specified as well.
2238 Typical calls to @code{AC_CONFIG_FILES} look like this:
2240 @example
2241 AC_CONFIG_FILES([Makefile src/Makefile man/Makefile X/Imakefile])
2242 AC_CONFIG_FILES([autoconf], [chmod +x autoconf])
2243 @end example
2245 You can override an input file name by appending to @var{file} a
2246 colon-separated list of input files.  Examples:
2248 @example
2249 AC_CONFIG_FILES([Makefile:boiler/top.mk:boiler/bot.mk]
2250                 [lib/Makefile:boiler/lib.mk])
2251 @end example
2253 @noindent
2254 Doing this allows you to keep your file names acceptable to
2255 @acronym{DOS} variants, or
2256 to prepend and/or append boilerplate to the file.
2257 @end defmac
2261 @node Makefile Substitutions
2262 @section Substitutions in Makefiles
2263 @cindex Substitutions in makefiles
2264 @cindex Makefile substitutions
2266 Each subdirectory in a distribution that contains something to be
2267 compiled or installed should come with a file @file{Makefile.in}, from
2268 which @command{configure} creates a file @file{Makefile} in that directory.
2269 To create @file{Makefile}, @command{configure} performs a simple variable
2270 substitution, replacing occurrences of @samp{@@@var{variable}@@} in
2271 @file{Makefile.in} with the value that @command{configure} has determined
2272 for that variable.  Variables that are substituted into output files in
2273 this way are called @dfn{output variables}.  They are ordinary shell
2274 variables that are set in @command{configure}.  To make @command{configure}
2275 substitute a particular variable into the output files, the macro
2276 @code{AC_SUBST} must be called with that variable name as an argument.
2277 Any occurrences of @samp{@@@var{variable}@@} for other variables are
2278 left unchanged.  @xref{Setting Output Variables}, for more information
2279 on creating output variables with @code{AC_SUBST}.
2281 A software package that uses a @command{configure} script should be
2282 distributed with a file @file{Makefile.in}, but no makefile; that
2283 way, the user has to properly configure the package for the local system
2284 before compiling it.
2286 @xref{Makefile Conventions, , Makefile Conventions, standards, The
2287 @acronym{GNU} Coding Standards}, for more information on what to put in
2288 makefiles.
2290 @menu
2291 * Preset Output Variables::     Output variables that are always set
2292 * Installation Directory Variables::  Other preset output variables
2293 * Changed Directory Variables:: Warnings about @file{datarootdir}
2294 * Build Directories::           Supporting multiple concurrent compiles
2295 * Automatic Remaking::          Makefile rules for configuring
2296 @end menu
2298 @node Preset Output Variables
2299 @subsection Preset Output Variables
2300 @cindex Output variables
2302 Some output variables are preset by the Autoconf macros.  Some of the
2303 Autoconf macros set additional output variables, which are mentioned in
2304 the descriptions for those macros.  @xref{Output Variable Index}, for a
2305 complete list of output variables.  @xref{Installation Directory
2306 Variables}, for the list of the preset ones related to installation
2307 directories.  Below are listed the other preset ones.  They all are
2308 precious variables (@pxref{Setting Output Variables},
2309 @code{AC_ARG_VAR}).
2311 @c Just say no to ASCII sorting!  We're humans, not computers.
2312 @c These variables are listed as they would be in a dictionary:
2313 @c actor
2314 @c Actress
2315 @c actress
2317 @defvar CFLAGS
2318 @ovindex CFLAGS
2319 Debugging and optimization options for the C compiler.  If it is not set
2320 in the environment when @command{configure} runs, the default value is set
2321 when you call @code{AC_PROG_CC} (or empty if you don't).  @command{configure}
2322 uses this variable when compiling or linking programs to test for C features.
2324 If a compiler option affects only the behavior of the preprocessor
2325 (e.g., @option{-D @var{name}}), it should be put into @code{CPPFLAGS}
2326 instead.  If it affects only the linker (e.g., @option{-L
2327 @var{directory}}), it should be put into @code{LDFLAGS} instead.  If it
2328 affects only the compiler proper, @code{CFLAGS} is the natural home for
2329 it.  If an option affects multiple phases of the compiler, though,
2330 matters get tricky.  One approach to put such options directly into
2331 @code{CC}, e.g., @code{CC='gcc -m64'}.  Another is to put them into both
2332 @code{CPPFLAGS} and @code{LDFLAGS}, but not into @code{CFLAGS}.
2334 @end defvar
2336 @defvar configure_input
2337 @ovindex configure_input
2338 A comment saying that the file was generated automatically by
2339 @command{configure} and giving the name of the input file.
2340 @code{AC_OUTPUT} adds a comment line containing this variable to the top
2341 of every makefile it creates.  For other files, you should
2342 reference this variable in a comment at the top of each input file.  For
2343 example, an input shell script should begin like this:
2345 @example
2346 #!/bin/sh
2347 # @@configure_input@@
2348 @end example
2350 @noindent
2351 The presence of that line also reminds people editing the file that it
2352 needs to be processed by @command{configure} in order to be used.
2353 @end defvar
2355 @defvar CPPFLAGS
2356 @ovindex CPPFLAGS
2357 Preprocessor options for the C, C++, and Objective C preprocessors and
2358 compilers.  If
2359 it is not set in the environment when @command{configure} runs, the default
2360 value is empty.  @command{configure} uses this variable when preprocessing
2361 or compiling programs to test for C, C++, and Objective C features.
2363 This variable's contents should contain options like @option{-I},
2364 @option{-D}, and @option{-U} that affect only the behavior of the
2365 preprocessor.  Please see the explanation of @code{CFLAGS} for what you
2366 can do if an option affects other phases of the compiler as well.
2368 Currently, @command{configure} always links as part of a single
2369 invocation of the compiler that also preprocesses and compiles, so it
2370 uses this variable also when linking programs.  However, it is unwise to
2371 depend on this behavior because the @acronym{GNU} coding standards do
2372 not require it and many packages do not use @code{CPPFLAGS} when linking
2373 programs.
2375 @xref{Special Chars in Variables}, for limitations that @code{CPPFLAGS}
2376 might run into.
2377 @end defvar
2379 @defvar CXXFLAGS
2380 @ovindex CXXFLAGS
2381 Debugging and optimization options for the C++ compiler.  It acts like
2382 @code{CFLAGS}, but for C++ instead of C.
2383 @end defvar
2385 @defvar DEFS
2386 @ovindex DEFS
2387 @option{-D} options to pass to the C compiler.  If @code{AC_CONFIG_HEADERS}
2388 is called, @command{configure} replaces @samp{@@DEFS@@} with
2389 @option{-DHAVE_CONFIG_H} instead (@pxref{Configuration Headers}).  This
2390 variable is not defined while @command{configure} is performing its tests,
2391 only when creating the output files.  @xref{Setting Output Variables}, for
2392 how to check the results of previous tests.
2393 @end defvar
2395 @defvar ECHO_C
2396 @defvarx ECHO_N
2397 @defvarx ECHO_T
2398 @ovindex ECHO_C
2399 @ovindex ECHO_N
2400 @ovindex ECHO_T
2401 How does one suppress the trailing newline from @command{echo} for
2402 question-answer message pairs?  These variables provide a way:
2404 @example
2405 echo $ECHO_N "And the winner is... $ECHO_C"
2406 sleep 100000000000
2407 echo "$@{ECHO_T@}dead."
2408 @end example
2410 @noindent
2411 Some old and uncommon @command{echo} implementations offer no means to
2412 achieve this, in which case @code{ECHO_T} is set to tab.  You might not
2413 want to use it.
2414 @end defvar
2416 @defvar ERLCFLAGS
2417 @ovindex ERLCFLAGS
2418 Debugging and optimization options for the Erlang compiler.  If it is not set
2419 in the environment when @command{configure} runs, the default value is empty.
2420 @command{configure} uses this variable when compiling
2421 programs to test for Erlang features.
2422 @end defvar
2424 @defvar FCFLAGS
2425 @ovindex FCFLAGS
2426 Debugging and optimization options for the Fortran compiler.  If it
2427 is not set in the environment when @command{configure} runs, the default
2428 value is set when you call @code{AC_PROG_FC} (or empty if you don't).
2429 @command{configure} uses this variable when compiling or linking
2430 programs to test for Fortran features.
2431 @end defvar
2433 @defvar FFLAGS
2434 @ovindex FFLAGS
2435 Debugging and optimization options for the Fortran 77 compiler.  If it
2436 is not set in the environment when @command{configure} runs, the default
2437 value is set when you call @code{AC_PROG_F77} (or empty if you don't).
2438 @command{configure} uses this variable when compiling or linking
2439 programs to test for Fortran 77 features.
2440 @end defvar
2442 @defvar LDFLAGS
2443 @ovindex LDFLAGS
2444 Options for the linker.  If it is not set
2445 in the environment when @command{configure} runs, the default value is empty.
2446 @command{configure} uses this variable when linking programs to test for
2447 C, C++, Objective C, and Fortran features.
2449 This variable's contents should contain options like @option{-s} and
2450 @option{-L} that affect only the behavior of the linker.  Please see the
2451 explanation of @code{CFLAGS} for what you can do if an option also
2452 affects other phases of the compiler.
2454 Don't use this variable to pass library names
2455 (@option{-l}) to the linker; use @code{LIBS} instead.
2456 @end defvar
2458 @defvar LIBS
2459 @ovindex LIBS
2460 @option{-l} options to pass to the linker.  The default value is empty,
2461 but some Autoconf macros may prepend extra libraries to this variable if
2462 those libraries are found and provide necessary functions, see
2463 @ref{Libraries}.  @command{configure} uses this variable when linking
2464 programs to test for C, C++, and Fortran features.
2465 @end defvar
2467 @defvar OBJCFLAGS
2468 @ovindex OBJCFLAGS
2469 Debugging and optimization options for the Objective C compiler.  It
2470 acts like @code{CFLAGS}, but for Objective C instead of C.
2471 @end defvar
2473 @defvar builddir
2474 @ovindex builddir
2475 Rigorously equal to @samp{.}.  Added for symmetry only.
2476 @end defvar
2478 @defvar abs_builddir
2479 @ovindex abs_builddir
2480 Absolute name of @code{builddir}.
2481 @end defvar
2483 @defvar top_builddir
2484 @ovindex top_builddir
2485 The relative name of the top level of the current build tree.  In the
2486 top-level directory, this is the same as @code{builddir}.
2487 @end defvar
2489 @defvar top_build_prefix
2490 @ovindex top_build_prefix
2491 The relative name of the top level of the current build tree with final
2492 slash if nonemtpy.  This is the same as @code{top_builddir}, except that
2493 it contains of zero of more runs of @code{../}, so it should not be
2494 appended with a slash for concatenation.  This helps for @command{make}
2495 implementations that otherwise do not treat @file{./file} and @file{file}
2496 as equal in the toplevel build directory.
2497 @end defvar
2499 @defvar abs_top_builddir
2500 @ovindex abs_top_builddir
2501 Absolute name of @code{top_builddir}.
2502 @end defvar
2504 @defvar srcdir
2505 @ovindex srcdir
2506 The name of the directory that contains the source code for
2507 that makefile.
2508 @end defvar
2510 @defvar abs_srcdir
2511 @ovindex abs_srcdir
2512 Absolute name of @code{srcdir}.
2513 @end defvar
2515 @defvar top_srcdir
2516 @ovindex top_srcdir
2517 The name of the top-level source code directory for the
2518 package.  In the top-level directory, this is the same as @code{srcdir}.
2519 @end defvar
2521 @defvar abs_top_srcdir
2522 @ovindex abs_top_srcdir
2523 Absolute name of @code{top_srcdir}.
2524 @end defvar
2526 @node Installation Directory Variables
2527 @subsection Installation Directory Variables
2528 @cindex Installation directories
2529 @cindex Directories, installation
2531 The following variables specify the directories for
2532 package installation, see @ref{Directory Variables, , Variables for
2533 Installation Directories, standards, The @acronym{GNU} Coding
2534 Standards}, for more information.  Each variable corresponds to an
2535 argument of @command{configure}; trailing slashes are stripped so that
2536 expressions such as @samp{$@{prefix@}/lib} expand with only one slash
2537 between directory names.  See the end of this section for
2538 details on when and how to use these variables.
2540 @defvar bindir
2541 @ovindex bindir
2542 The directory for installing executables that users run.
2543 @end defvar
2545 @defvar datadir
2546 @ovindex datadir
2547 The directory for installing idiosyncratic read-only
2548 architecture-independent data.
2549 @end defvar
2551 @defvar datarootdir
2552 @ovindex datarootdir
2553 The root of the directory tree for read-only architecture-independent
2554 data files.
2555 @end defvar
2557 @defvar docdir
2558 @ovindex docdir
2559 The directory for installing documentation files (other than Info and
2560 man).
2561 @end defvar
2563 @defvar dvidir
2564 @ovindex dvidir
2565 The directory for installing documentation files in DVI format.
2566 @end defvar
2568 @defvar exec_prefix
2569 @ovindex exec_prefix
2570 The installation prefix for architecture-dependent files.  By default
2571 it's the same as @var{prefix}.  You should avoid installing anything
2572 directly to @var{exec_prefix}.  However, the default value for
2573 directories containing architecture-dependent files should be relative
2574 to @var{exec_prefix}.
2575 @end defvar
2577 @defvar htmldir
2578 @ovindex htmldir
2579 The directory for installing HTML documentation.
2580 @end defvar
2582 @defvar includedir
2583 @ovindex includedir
2584 The directory for installing C header files.
2585 @end defvar
2587 @defvar infodir
2588 @ovindex infodir
2589 The directory for installing documentation in Info format.
2590 @end defvar
2592 @defvar libdir
2593 @ovindex libdir
2594 The directory for installing object code libraries.
2595 @end defvar
2597 @defvar libexecdir
2598 @ovindex libexecdir
2599 The directory for installing executables that other programs run.
2600 @end defvar
2602 @defvar localedir
2603 @ovindex localedir
2604 The directory for installing locale-dependent but
2605 architecture-independent data, such as message catalogs.  This directory
2606 usually has a subdirectory per locale.
2607 @end defvar
2609 @defvar localstatedir
2610 @ovindex localstatedir
2611 The directory for installing modifiable single-machine data.
2612 @end defvar
2614 @defvar mandir
2615 @ovindex mandir
2616 The top-level directory for installing documentation in man format.
2617 @end defvar
2619 @defvar oldincludedir
2620 @ovindex oldincludedir
2621 The directory for installing C header files for non-@acronym{GCC} compilers.
2622 @end defvar
2624 @defvar pdfdir
2625 @ovindex pdfdir
2626 The directory for installing PDF documentation.
2627 @end defvar
2629 @defvar prefix
2630 @ovindex prefix
2631 The common installation prefix for all files.  If @var{exec_prefix}
2632 is defined to a different value, @var{prefix} is used only for
2633 architecture-independent files.
2634 @end defvar
2636 @defvar psdir
2637 @ovindex psdir
2638 The directory for installing PostScript documentation.
2639 @end defvar
2641 @defvar sbindir
2642 @ovindex sbindir
2643 The directory for installing executables that system
2644 administrators run.
2645 @end defvar
2647 @defvar sharedstatedir
2648 @ovindex sharedstatedir
2649 The directory for installing modifiable architecture-independent data.
2650 @end defvar
2652 @defvar sysconfdir
2653 @ovindex sysconfdir
2654 The directory for installing read-only single-machine data.
2655 @end defvar
2658 Most of these variables have values that rely on @code{prefix} or
2659 @code{exec_prefix}.  It is deliberate that the directory output
2660 variables keep them unexpanded: typically @samp{@@datarootdir@@} is
2661 replaced by @samp{$@{prefix@}/share}, not @samp{/usr/local/share}, and
2662 @samp{@@datadir@@} is replaced by @samp{$@{datarootdir@}}.
2664 This behavior is mandated by the @acronym{GNU} coding standards, so that when
2665 the user runs:
2667 @table @samp
2668 @item make
2669 she can still specify a different prefix from the one specified to
2670 @command{configure}, in which case, if needed, the package should hard
2671 code dependencies corresponding to the make-specified prefix.
2673 @item make install
2674 she can specify a different installation location, in which case the
2675 package @emph{must} still depend on the location which was compiled in
2676 (i.e., never recompile when @samp{make install} is run).  This is an
2677 extremely important feature, as many people may decide to install all
2678 the files of a package grouped together, and then install links from
2679 the final locations to there.
2680 @end table
2682 In order to support these features, it is essential that
2683 @code{datarootdir} remains being defined as @samp{$@{prefix@}/share} to
2684 depend upon the current value of @code{prefix}.
2686 A corollary is that you should not use these variables except in
2687 makefiles.  For instance, instead of trying to evaluate @code{datadir}
2688 in @file{configure} and hard-coding it in makefiles using
2689 e.g., @samp{AC_DEFINE_UNQUOTED([DATADIR], ["$datadir"], [Data directory.])},
2690 you should add
2691 @option{-DDATADIR='$(datadir)'} to your makefile's definition of
2692 @code{CPPFLAGS} (@code{AM_CPPFLAGS} if you are also using Automake).
2694 Similarly, you should not rely on @code{AC_CONFIG_FILES} to replace
2695 @code{datadir} and friends in your shell scripts and other files; instead,
2696 let @command{make} manage their replacement.  For instance Autoconf
2697 ships templates of its shell scripts ending with @samp{.in}, and uses a
2698 makefile snippet similar to the following to build scripts like
2699 @command{autoheader} and @command{autom4te}:
2701 @example
2702 @group
2703 edit = sed \
2704         -e 's|@@datadir[@@]|$(pkgdatadir)|g' \
2705         -e 's|@@prefix[@@]|$(prefix)|g'
2706 @end group
2708 @group
2709 autoheader autom4te: Makefile
2710         rm -f $@@ $@@.tmp
2711         $(edit) '$(srcdir)/$@@.in' >$@@.tmp
2712         chmod +x $@@.tmp
2713         chmod a-w $@@.tmp
2714         mv $@@.tmp $@@
2715 @end group
2717 @group
2718 autoheader: $(srcdir)/autoheader.in
2719 autom4te: $(srcdir)/autom4te.in
2720 @end group
2721 @end example
2723 Some details are noteworthy:
2725 @table @asis
2726 @item @samp{@@datadir[@@]}
2727 The brackets prevent @command{configure} from replacing
2728 @samp{@@datadir@@} in the Sed expression itself.
2729 Brackets are preferable to a backslash here, since
2730 Posix says @samp{\@@} is not portable.
2732 @item @samp{$(pkgdatadir)}
2733 Don't use @samp{@@pkgdatadir@@}!  Use the matching makefile variable
2734 instead.
2736 @item @samp{/}
2737 Don't use @samp{/} in the Sed expressions that replace file names since
2738 most likely the
2739 variables you use, such as @samp{$(pkgdatadir)}, contain @samp{/}.
2740 Use a shell metacharacter instead, such as @samp{|}.
2742 @item special characters
2743 File names, file name components, and the value of @code{VPATH} should
2744 not contain shell metacharacters or white
2745 space.  @xref{Special Chars in Variables}.
2747 @item dependency on @file{Makefile}
2748 Since @code{edit} uses values that depend on the configuration specific
2749 values (@code{prefix}, etc.)@: and not only on @code{VERSION} and so forth,
2750 the output depends on @file{Makefile}, not @file{configure.ac}.
2752 @item @samp{$@@}
2753 The main rule is generic, and uses @samp{$@@} extensively to
2754 avoid the need for multiple copies of the rule.
2756 @item Separated dependencies and single suffix rules
2757 You can't use them!  The above snippet cannot be (portably) rewritten
2760 @example
2761 autoconf autoheader: Makefile
2762 @group
2763 .in:
2764         rm -f $@@ $@@.tmp
2765         $(edit) $< >$@@.tmp
2766         chmod +x $@@.tmp
2767         mv $@@.tmp $@@
2768 @end group
2769 @end example
2771 @xref{Single Suffix Rules}, for details.
2773 @item @samp{$(srcdir)}
2774 Be sure to specify the name of the source directory,
2775 otherwise the package won't support separated builds.
2776 @end table
2778 For the more specific installation of Erlang libraries, the following variables
2779 are defined:
2781 @defvar ERLANG_INSTALL_LIB_DIR
2782 @ovindex ERLANG_INSTALL_LIB_DIR
2783 @acindex{ERLANG_SUBST_INSTALL_LIB_DIR}
2784 The common parent directory of Erlang library installation directories.
2785 This variable is set by calling the @code{AC_ERLANG_SUBST_INSTALL_LIB_DIR}
2786 macro in @file{configure.ac}.
2787 @end defvar
2789 @defvar ERLANG_INSTALL_LIB_DIR_@var{library}
2790 @ovindex ERLANG_INSTALL_LIB_DIR_@var{library}
2791 @acindex{ERLANG_SUBST_INSTALL_LIB_SUBDIR}
2792 The installation directory for Erlang library @var{library}.
2793 This variable is set by calling the
2794 @samp{AC_ERLANG_SUBST_INSTALL_LIB_SUBDIR(@var{library}, @var{version}}
2795 macro in @file{configure.ac}.
2796 @end defvar
2798 @xref{Erlang Libraries}, for details.
2801 @node Changed Directory Variables
2802 @subsection Changed Directory Variables
2803 @cindex @file{datarootdir}
2805 In Autoconf 2.60, the set of directory variables has changed, and the
2806 defaults of some variables have been adjusted
2807 (@pxref{Installation Directory Variables}) to changes in the
2808 @acronym{GNU} Coding Standards.  Notably, @file{datadir}, @file{infodir}, and
2809 @file{mandir} are now expressed in terms of @file{datarootdir}.  If you are
2810 upgrading from an earlier Autoconf version, you may need to adjust your files
2811 to ensure that the directory variables are substituted correctly
2812 (@pxref{Defining Directories}), and that a definition of @file{datarootdir} is
2813 in place.  For example, in a @file{Makefile.in}, adding
2815 @example
2816 datarootdir = @@datarootdir@@
2817 @end example
2819 @noindent
2820 is usually sufficient.  If you use Automake to create @file{Makefile.in},
2821 it will add this for you.
2823 To help with the transition, Autoconf warns about files that seem to use
2824 @code{datarootdir} without defining it.  In some cases, it then expands
2825 the value of @code{$datarootdir} in substitutions of the directory
2826 variables.  The following example shows such a warning:
2828 @example
2829 $ @kbd{cat configure.ac}
2830 AC_INIT
2831 AC_CONFIG_FILES([Makefile])
2832 AC_OUTPUT
2833 $ @kbd{cat Makefile.in}
2834 prefix = @@prefix@@
2835 datadir = @@datadir@@
2836 $ @kbd{autoconf}
2837 $ @kbd{configure}
2838 configure: creating ./config.status
2839 config.status: creating Makefile
2840 config.status: WARNING:
2841                Makefile.in seems to ignore the --datarootdir setting
2842 $ @kbd{cat Makefile}
2843 prefix = /usr/local
2844 datadir = $@{prefix@}/share
2845 @end example
2847 Usually one can easily change the file to accommodate both older and newer
2848 Autoconf releases:
2850 @example
2851 $ @kbd{cat Makefile.in}
2852 prefix = @@prefix@@
2853 datarootdir = @@datarootdir@@
2854 datadir = @@datadir@@
2855 $ @kbd{configure}
2856 configure: creating ./config.status
2857 config.status: creating Makefile
2858 $ @kbd{cat Makefile}
2859 prefix = /usr/local
2860 datarootdir = $@{prefix@}/share
2861 datadir = $@{datarootdir@}
2862 @end example
2864 @acindex{DATAROOTDIR_CHECKED}
2865 In some cases, however, the checks may not be able to detect that a suitable
2866 initialization of @code{datarootdir} is in place, or they may fail to detect
2867 that such an initialization is necessary in the output file.  If, after
2868 auditing your package, there are still spurious @file{configure} warnings about
2869 @code{datarootdir}, you may add the line
2871 @example
2872 AC_DEFUN([AC_DATAROOTDIR_CHECKED])
2873 @end example
2875 @noindent
2876 to your @file{configure.ac} to disable the warnings.  This is an exception
2877 to the usual rule that you should not define a macro whose name begins with
2878 @code{AC_} (@pxref{Macro Names}).
2882 @node Build Directories
2883 @subsection Build Directories
2884 @cindex Build directories
2885 @cindex Directories, build
2887 You can support compiling a software package for several architectures
2888 simultaneously from the same copy of the source code.  The object files
2889 for each architecture are kept in their own directory.
2891 To support doing this, @command{make} uses the @code{VPATH} variable to
2892 find the files that are in the source directory.  @acronym{GNU} Make
2893 can do this.  Most other recent @command{make} programs can do this as
2894 well, though they may have difficulties and it is often simpler to
2895 recommend @acronym{GNU} @command{make} (@pxref{VPATH and Make}).  Older
2896 @command{make} programs do not support @code{VPATH}; when using them, the
2897 source code must be in the same directory as the object files.
2899 To support @code{VPATH}, each @file{Makefile.in} should contain two
2900 lines that look like:
2902 @example
2903 srcdir = @@srcdir@@
2904 VPATH = @@srcdir@@
2905 @end example
2907 Do not set @code{VPATH} to the value of another variable, for example
2908 @samp{VPATH = $(srcdir)}, because some versions of @command{make} do not do
2909 variable substitutions on the value of @code{VPATH}.
2911 @command{configure} substitutes the correct value for @code{srcdir} when
2912 it produces @file{Makefile}.
2914 Do not use the @command{make} variable @code{$<}, which expands to the
2915 file name of the file in the source directory (found with @code{VPATH}),
2916 except in implicit rules.  (An implicit rule is one such as @samp{.c.o},
2917 which tells how to create a @file{.o} file from a @file{.c} file.)  Some
2918 versions of @command{make} do not set @code{$<} in explicit rules; they
2919 expand it to an empty value.
2921 Instead, Make command lines should always refer to source
2922 files by prefixing them with @samp{$(srcdir)/}.  For example:
2924 @example
2925 time.info: time.texinfo
2926         $(MAKEINFO) '$(srcdir)/time.texinfo'
2927 @end example
2929 @node Automatic Remaking
2930 @subsection Automatic Remaking
2931 @cindex Automatic remaking
2932 @cindex Remaking automatically
2934 You can put rules like the following in the top-level @file{Makefile.in}
2935 for a package to automatically update the configuration information when
2936 you change the configuration files.  This example includes all of the
2937 optional files, such as @file{aclocal.m4} and those related to
2938 configuration header files.  Omit from the @file{Makefile.in} rules for
2939 any of these files that your package does not use.
2941 The @samp{$(srcdir)/} prefix is included because of limitations in the
2942 @code{VPATH} mechanism.
2944 The @file{stamp-} files are necessary because the timestamps of
2945 @file{config.h.in} and @file{config.h} are not changed if remaking
2946 them does not change their contents.  This feature avoids unnecessary
2947 recompilation.  You should include the file @file{stamp-h.in} your
2948 package's distribution, so that @command{make} considers
2949 @file{config.h.in} up to date.  Don't use @command{touch}
2950 (@pxref{Limitations of Usual Tools}); instead, use @command{echo} (using
2951 @command{date} would cause needless differences, hence @acronym{CVS}
2952 conflicts, etc.).
2954 @example
2955 @group
2956 $(srcdir)/configure: configure.ac aclocal.m4
2957         cd '$(srcdir)' && autoconf
2959 # autoheader might not change config.h.in, so touch a stamp file.
2960 $(srcdir)/config.h.in: stamp-h.in
2961 $(srcdir)/stamp-h.in: configure.ac aclocal.m4
2962         cd '$(srcdir)' && autoheader
2963         echo timestamp > '$(srcdir)/stamp-h.in'
2965 config.h: stamp-h
2966 stamp-h: config.h.in config.status
2967         ./config.status
2969 Makefile: Makefile.in config.status
2970         ./config.status
2972 config.status: configure
2973         ./config.status --recheck
2974 @end group
2975 @end example
2977 @noindent
2978 (Be careful if you copy these lines directly into your makefile, as you
2979 need to convert the indented lines to start with the tab character.)
2981 In addition, you should use
2983 @example
2984 AC_CONFIG_FILES([stamp-h], [echo timestamp > stamp-h])
2985 @end example
2987 @noindent
2988 so @file{config.status} ensures that @file{config.h} is considered up to
2989 date.  @xref{Output}, for more information about @code{AC_OUTPUT}.
2991 @xref{config.status Invocation}, for more examples of handling
2992 configuration-related dependencies.
2994 @node Configuration Headers
2995 @section Configuration Header Files
2996 @cindex Configuration Header
2997 @cindex @file{config.h}
2999 When a package contains more than a few tests that define C preprocessor
3000 symbols, the command lines to pass @option{-D} options to the compiler
3001 can get quite long.  This causes two problems.  One is that the
3002 @command{make} output is hard to visually scan for errors.  More
3003 seriously, the command lines can exceed the length limits of some
3004 operating systems.  As an alternative to passing @option{-D} options to
3005 the compiler, @command{configure} scripts can create a C header file
3006 containing @samp{#define} directives.  The @code{AC_CONFIG_HEADERS}
3007 macro selects this kind of output.  Though it can be called anywhere
3008 between @code{AC_INIT} and @code{AC_OUTPUT}, it is customary to call
3009 it right after @code{AC_INIT}.
3011 The package should @samp{#include} the configuration header file before
3012 any other header files, to prevent inconsistencies in declarations (for
3013 example, if it redefines @code{const}).
3015 To provide for VPATH builds, remember to pass the C compiler a @option{-I.}
3016 option (or @option{-I..}; whichever directory contains @file{config.h}).
3017 Even if you use @samp{#include "config.h"}, the preprocessor searches only
3018 the directory of the currently read file, i.e., the source directory, not
3019 the build directory.
3021 With the appropriate @option{-I} option, you can use
3022 @samp{#include <config.h>}.  Actually, it's a good habit to use it,
3023 because in the rare case when the source directory contains another
3024 @file{config.h}, the build directory should be searched first.
3027 @defmac AC_CONFIG_HEADERS (@var{header} @dots{}, @ovar{cmds}, @ovar{init-cmds})
3028 @acindex{CONFIG_HEADERS}
3029 @cvindex HAVE_CONFIG_H
3030 This macro is one of the instantiating macros; see @ref{Configuration
3031 Actions}.  Make @code{AC_OUTPUT} create the file(s) in the
3032 blank-or-newline-separated list @var{header} containing C preprocessor
3033 @code{#define} statements, and replace @samp{@@DEFS@@} in generated
3034 files with @option{-DHAVE_CONFIG_H} instead of the value of @code{DEFS}.
3035 The usual name for @var{header} is @file{config.h}.
3037 If @var{header} already exists and its contents are identical to what
3038 @code{AC_OUTPUT} would put in it, it is left alone.  Doing this allows
3039 making some changes in the configuration without needlessly causing
3040 object files that depend on the header file to be recompiled.
3042 Usually the input file is named @file{@var{header}.in}; however, you can
3043 override the input file name by appending to @var{header} a
3044 colon-separated list of input files.  For example, you might need to make
3045 the input file name acceptable to @acronym{DOS} variants:
3047 @example
3048 AC_CONFIG_HEADERS([config.h:config.hin])
3049 @end example
3051 @end defmac
3053 @defmac AH_HEADER
3054 @ahindex{HEADER}
3055 This macro is defined as the name of the first declared config header
3056 and undefined if no config headers have been declared up to this point.
3057 A third-party macro may, for example, require use of a config header
3058 without invoking AC_CONFIG_HEADERS twice, like this:
3060 @example
3061 AC_CONFIG_COMMANDS_PRE(
3062         [m4_ifndef([AH_HEADER], [AC_CONFIG_HEADERS([config.h])])])
3063 @end example
3065 @end defmac
3067 @xref{Configuration Actions}, for more details on @var{header}.
3069 @menu
3070 * Header Templates::            Input for the configuration headers
3071 * autoheader Invocation::       How to create configuration templates
3072 * Autoheader Macros::           How to specify CPP templates
3073 @end menu
3075 @node Header Templates
3076 @subsection Configuration Header Templates
3077 @cindex Configuration Header Template
3078 @cindex Header templates
3079 @cindex @file{config.h.in}
3081 Your distribution should contain a template file that looks as you want
3082 the final header file to look, including comments, with @code{#undef}
3083 statements which are used as hooks.  For example, suppose your
3084 @file{configure.ac} makes these calls:
3086 @example
3087 AC_CONFIG_HEADERS([conf.h])
3088 AC_CHECK_HEADERS([unistd.h])
3089 @end example
3091 @noindent
3092 Then you could have code like the following in @file{conf.h.in}.
3093 The @file{conf.h} created by @command{configure} defines @samp{HAVE_UNISTD_H}
3094 to 1, if and only if the system has @file{unistd.h}.
3096 @example
3097 @group
3098 /* Define as 1 if you have unistd.h.  */
3099 #undef HAVE_UNISTD_H
3100 @end group
3101 @end example
3103 The format of the template file is stricter than what the C preprocessor
3104 is required to accept.  A directive line should contain only whitespace,
3105 @samp{#undef}, and @samp{HAVE_UNISTD_H}.  The use of @samp{#define}
3106 instead of @samp{#undef}, or of comments on the same line as
3107 @samp{#undef}, is strongly discouraged.  Each hook should only be listed
3108 once.  Other preprocessor lines, such as @samp{#ifdef} or
3109 @samp{#include}, are copied verbatim from the template into the
3110 generated header.
3112 Since it is a tedious task to keep a template header up to date, you may
3113 use @command{autoheader} to generate it, see @ref{autoheader Invocation}.
3115 During the instantiation of the header, each @samp{#undef} line in the
3116 template file for each symbol defined by @samp{AC_DEFINE} is changed to an
3117 appropriate @samp{#define}. If the corresponding @samp{AC_DEFINE} has not
3118 been executed during the @command{configure} run, the @samp{#undef} line is
3119 commented out.  (This is important, e.g., for @samp{_POSIX_SOURCE}:
3120 on many systems, it can be implicitly defined by the compiler, and
3121 undefining it in the header would then break compilation of subsequent
3122 headers.)
3124 Currently, @emph{all} remaining @samp{#undef} lines in the header
3125 template are commented out, whether or not there was a corresponding
3126 @samp{AC_DEFINE} for the macro name; but this behavior is not guaranteed
3127 for future releases of Autoconf.
3129 Generally speaking, since you should not use @samp{#define}, and you
3130 cannot guarantee whether a @samp{#undef} directive in the header
3131 template will be converted to a @samp{#define} or commented out in the
3132 generated header file, the template file cannot be used for conditional
3133 definition effects.  Consequently, if you need to use the construct
3135 @example
3136 @group
3137 #ifdef THIS
3138 # define THAT
3139 #endif
3140 @end group
3141 @end example
3143 @noindent
3144 you must place it outside of the template.
3145 If you absolutely need to hook it to the config header itself, please put
3146 the directives to a separate file, and @samp{#include} that file from the
3147 config header template.  If you are using @command{autoheader}, you would
3148 probably use @samp{AH_BOTTOM} to append the @samp{#include} directive.
3151 @node autoheader Invocation
3152 @subsection Using @command{autoheader} to Create @file{config.h.in}
3153 @cindex @command{autoheader}
3155 The @command{autoheader} program can create a template file of C
3156 @samp{#define} statements for @command{configure} to use.
3157 It searches for the first invocation of @code{AC_CONFIG_HEADERS} in
3158 @file{configure} sources to determine the name of the template.
3159 (If the first call of @code{AC_CONFIG_HEADERS} specifies more than one
3160 input file name, @command{autoheader} uses the first one.)
3162 It is recommended that only one input file is used.  If you want to append
3163 a boilerplate code, it is preferable to use
3164 @samp{AH_BOTTOM([#include <conf_post.h>])}.
3165 File @file{conf_post.h} is not processed during the configuration then,
3166 which make things clearer.  Analogically, @code{AH_TOP} can be used to
3167 prepend a boilerplate code.
3169 In order to do its job, @command{autoheader} needs you to document all
3170 of the symbols that you might use.  Typically this is done via an
3171 @code{AC_DEFINE} or @code{AC_DEFINE_UNQUOTED} call whose first argument
3172 is a literal symbol and whose third argument describes the symbol
3173 (@pxref{Defining Symbols}).  Alternatively, you can use
3174 @code{AH_TEMPLATE} (@pxref{Autoheader Macros}), or you can supply a
3175 suitable input file for a subsequent configuration header file.
3176 Symbols defined by Autoconf's builtin tests are already documented properly;
3177 you need to document only those that you
3178 define yourself.
3180 You might wonder why @command{autoheader} is needed: after all, why
3181 would @command{configure} need to ``patch'' a @file{config.h.in} to
3182 produce a @file{config.h} instead of just creating @file{config.h} from
3183 scratch?  Well, when everything rocks, the answer is just that we are
3184 wasting our time maintaining @command{autoheader}: generating
3185 @file{config.h} directly is all that is needed.  When things go wrong,
3186 however, you'll be thankful for the existence of @command{autoheader}.
3188 The fact that the symbols are documented is important in order to
3189 @emph{check} that @file{config.h} makes sense.  The fact that there is a
3190 well-defined list of symbols that should be defined (or not) is
3191 also important for people who are porting packages to environments where
3192 @command{configure} cannot be run: they just have to @emph{fill in the
3193 blanks}.
3195 But let's come back to the point: the invocation of @command{autoheader}@dots{}
3197 If you give @command{autoheader} an argument, it uses that file instead
3198 of @file{configure.ac} and writes the header file to the standard output
3199 instead of to @file{config.h.in}.  If you give @command{autoheader} an
3200 argument of @option{-}, it reads the standard input instead of
3201 @file{configure.ac} and writes the header file to the standard output.
3203 @command{autoheader} accepts the following options:
3205 @table @option
3206 @item --help
3207 @itemx -h
3208 Print a summary of the command line options and exit.
3210 @item --version
3211 @itemx -V
3212 Print the version number of Autoconf and exit.
3214 @item --verbose
3215 @itemx -v
3216 Report processing steps.
3218 @item --debug
3219 @itemx -d
3220 Don't remove the temporary files.
3222 @item --force
3223 @itemx -f
3224 Remake the template file even if newer than its input files.
3226 @item --include=@var{dir}
3227 @itemx -I @var{dir}
3228 Append @var{dir} to the include path.  Multiple invocations accumulate.
3230 @item --prepend-include=@var{dir}
3231 @itemx -B @var{dir}
3232 Prepend @var{dir} to the include path.  Multiple invocations accumulate.
3234 @item --warnings=@var{category}
3235 @itemx -W @var{category}
3236 @evindex WARNINGS
3237 Report the warnings related to @var{category} (which can actually be a
3238 comma separated list).  Current categories include:
3240 @table @samp
3241 @item obsolete
3242 report the uses of obsolete constructs
3244 @item all
3245 report all the warnings
3247 @item none
3248 report none
3250 @item error
3251 treats warnings as errors
3253 @item no-@var{category}
3254 disable warnings falling into @var{category}
3255 @end table
3257 @end table
3261 @node Autoheader Macros
3262 @subsection Autoheader Macros
3263 @cindex Autoheader macros
3265 @command{autoheader} scans @file{configure.ac} and figures out which C
3266 preprocessor symbols it might define.  It knows how to generate
3267 templates for symbols defined by @code{AC_CHECK_HEADERS},
3268 @code{AC_CHECK_FUNCS} etc., but if you @code{AC_DEFINE} any additional
3269 symbol, you must define a template for it.  If there are missing
3270 templates, @command{autoheader} fails with an error message.
3272 The template for a @var{symbol} is created
3273 by @command{autoheader} from
3274 the @var{description} argument to an @code{AC_DEFINE};
3275 see @ref{Defining Symbols}.
3277 For special needs, you can use the following macros.
3280 @defmac AH_TEMPLATE (@var{key}, @var{description})
3281 @ahindex{TEMPLATE}
3282 Tell @command{autoheader} to generate a template for @var{key}.  This macro
3283 generates standard templates just like @code{AC_DEFINE} when a
3284 @var{description} is given.
3286 For example:
3288 @example
3289 AH_TEMPLATE([CRAY_STACKSEG_END],
3290             [Define to one of _getb67, GETB67, getb67
3291              for Cray-2 and Cray-YMP systems.  This
3292              function is required for alloca.c support
3293              on those systems.])
3294 @end example
3296 @noindent
3297 generates the following template, with the description properly
3298 justified.
3300 @example
3301 /* Define to one of _getb67, GETB67, getb67 for Cray-2 and
3302    Cray-YMP systems.  This function is required for alloca.c
3303    support on those systems.  */
3304 #undef CRAY_STACKSEG_END
3305 @end example
3306 @end defmac
3309 @defmac AH_VERBATIM (@var{key}, @var{template})
3310 @ahindex{VERBATIM}
3311 Tell @command{autoheader} to include the @var{template} as-is in the header
3312 template file.  This @var{template} is associated with the @var{key},
3313 which is used to sort all the different templates and guarantee their
3314 uniqueness.  It should be a symbol that can be defined via @code{AC_DEFINE}.
3315 @end defmac
3318 @defmac AH_TOP (@var{text})
3319 @ahindex{TOP}
3320 Include @var{text} at the top of the header template file.
3321 @end defmac
3324 @defmac AH_BOTTOM (@var{text})
3325 @ahindex{BOTTOM}
3326 Include @var{text} at the bottom of the header template file.
3327 @end defmac
3330 Please note that @var{text} gets included ``verbatim'' to the template file,
3331 not to the resulting config header, so it can easily get mangled when the
3332 template is processed.  There is rarely a need for something other than
3334 @example
3335 AH_BOTTOM([#include <custom.h>])
3336 @end example
3340 @node Configuration Commands
3341 @section Running Arbitrary Configuration Commands
3342 @cindex Configuration commands
3343 @cindex Commands for configuration
3345 You can execute arbitrary commands before, during, and after
3346 @file{config.status} is run.  The three following macros accumulate the
3347 commands to run when they are called multiple times.
3348 @code{AC_CONFIG_COMMANDS} replaces the obsolete macro
3349 @code{AC_OUTPUT_COMMANDS}; see @ref{Obsolete Macros}, for details.
3351 @anchor{AC_CONFIG_COMMANDS}
3352 @defmac AC_CONFIG_COMMANDS (@var{tag}@dots{}, @ovar{cmds}, @ovar{init-cmds})
3353 @acindex{CONFIG_COMMANDS}
3354 Specify additional shell commands to run at the end of
3355 @file{config.status}, and shell commands to initialize any variables
3356 from @command{configure}.  Associate the commands with @var{tag}.
3357 Since typically the @var{cmds} create a file, @var{tag} should
3358 naturally be the name of that file.  If needed, the directory hosting
3359 @var{tag} is created.  This macro is one of the instantiating macros;
3360 see @ref{Configuration Actions}.
3362 Here is an unrealistic example:
3363 @example
3364 fubar=42
3365 AC_CONFIG_COMMANDS([fubar],
3366                    [echo this is extra $fubar, and so on.],
3367                    [fubar=$fubar])
3368 @end example
3370 Here is a better one:
3371 @example
3372 AC_CONFIG_COMMANDS([timestamp], [date >timestamp])
3373 @end example
3374 @end defmac
3376 The following two macros look similar, but in fact they are not of the same
3377 breed: they are executed directly by @file{configure}, so you cannot use
3378 @file{config.status} to rerun them.
3380 @c Yet it is good to leave them here.  The user sees them together and
3381 @c decides which best fits their needs.
3383 @defmac AC_CONFIG_COMMANDS_PRE (@var{cmds})
3384 @acindex{CONFIG_COMMANDS_PRE}
3385 Execute the @var{cmds} right before creating @file{config.status}.
3387 This macro presents the last opportunity to call @code{AC_SUBST},
3388 @code{AC_DEFINE}, or @code{AC_CONFIG_FOOS} macros.
3389 @end defmac
3391 @defmac AC_CONFIG_COMMANDS_POST (@var{cmds})
3392 @acindex{CONFIG_COMMANDS_POST}
3393 Execute the @var{cmds} right after creating @file{config.status}.
3394 @end defmac
3399 @node Configuration Links
3400 @section Creating Configuration Links
3401 @cindex Configuration links
3402 @cindex Links for configuration
3404 You may find it convenient to create links whose destinations depend upon
3405 results of tests.  One can use @code{AC_CONFIG_COMMANDS} but the
3406 creation of relative symbolic links can be delicate when the package is
3407 built in a directory different from the source directory.
3409 @anchor{AC_CONFIG_LINKS}
3410 @defmac AC_CONFIG_LINKS (@var{dest}:@var{source}@dots{}, @ovar{cmds}, @
3411   @ovar{init-cmds})
3412 @acindex{CONFIG_LINKS}
3413 @cindex Links
3414 Make @code{AC_OUTPUT} link each of the existing files @var{source} to
3415 the corresponding link name @var{dest}.  Makes a symbolic link if
3416 possible, otherwise a hard link if possible, otherwise a copy.  The
3417 @var{dest} and @var{source} names should be relative to the top level
3418 source or build directory.  This macro is one of the instantiating
3419 macros; see @ref{Configuration Actions}.
3421 For example, this call:
3423 @example
3424 AC_CONFIG_LINKS([host.h:config/$machine.h
3425                 object.h:config/$obj_format.h])
3426 @end example
3428 @noindent
3429 creates in the current directory @file{host.h} as a link to
3430 @file{@var{srcdir}/config/$machine.h}, and @file{object.h} as a
3431 link to @file{@var{srcdir}/config/$obj_format.h}.
3433 The tempting value @samp{.} for @var{dest} is invalid: it makes it
3434 impossible for @samp{config.status} to guess the links to establish.
3436 One can then run:
3437 @example
3438 ./config.status host.h object.h
3439 @end example
3440 @noindent
3441 to create the links.
3442 @end defmac
3446 @node Subdirectories
3447 @section Configuring Other Packages in Subdirectories
3448 @cindex Configure subdirectories
3449 @cindex Subdirectory configure
3451 In most situations, calling @code{AC_OUTPUT} is sufficient to produce
3452 makefiles in subdirectories.  However, @command{configure} scripts
3453 that control more than one independent package can use
3454 @code{AC_CONFIG_SUBDIRS} to run @command{configure} scripts for other
3455 packages in subdirectories.
3457 @defmac AC_CONFIG_SUBDIRS (@var{dir} @dots{})
3458 @acindex{CONFIG_SUBDIRS}
3459 @ovindex subdirs
3460 Make @code{AC_OUTPUT} run @command{configure} in each subdirectory
3461 @var{dir} in the given blank-or-newline-separated list.  Each @var{dir} should
3462 be a literal, i.e., please do not use:
3464 @example
3465 if test "$package_foo_enabled" = yes; then
3466   $my_subdirs="$my_subdirs foo"
3468 AC_CONFIG_SUBDIRS([$my_subdirs])
3469 @end example
3471 @noindent
3472 because this prevents @samp{./configure --help=recursive} from
3473 displaying the options of the package @code{foo}.  Instead, you should
3474 write:
3476 @example
3477 if test "$package_foo_enabled" = yes; then
3478   AC_CONFIG_SUBDIRS([foo])
3480 @end example
3482 If a given @var{dir} is not found, an error is reported: if the
3483 subdirectory is optional, write:
3485 @example
3486 if test -d "$srcdir/foo"; then
3487   AC_CONFIG_SUBDIRS([foo])
3489 @end example
3491 @c NB: Yes, below we mean configure.in, not configure.ac.
3492 If a given @var{dir} contains @command{configure.gnu}, it is run instead
3493 of @command{configure}.  This is for packages that might use a
3494 non-Autoconf script @command{Configure}, which can't be called through a
3495 wrapper @command{configure} since it would be the same file on
3496 case-insensitive file systems.  Likewise, if a @var{dir} contains
3497 @file{configure.in} but no @command{configure}, the Cygnus
3498 @command{configure} script found by @code{AC_CONFIG_AUX_DIR} is used.
3500 The subdirectory @command{configure} scripts are given the same command
3501 line options that were given to this @command{configure} script, with minor
3502 changes if needed, which include:
3504 @itemize @minus
3505 @item
3506 adjusting a relative name for the cache file;
3508 @item
3509 adjusting a relative name for the source directory;
3511 @item
3512 propagating the current value of @code{$prefix}, including if it was
3513 defaulted, and if the default values of the top level and of the subdirectory
3514 @file{configure} differ.
3515 @end itemize
3517 This macro also sets the output variable @code{subdirs} to the list of
3518 directories @samp{@var{dir} @dots{}}.  Make rules can use
3519 this variable to determine which subdirectories to recurse into.
3521 This macro may be called multiple times.
3522 @end defmac
3524 @node Default Prefix
3525 @section Default Prefix
3526 @cindex Install prefix
3527 @cindex Prefix for install
3529 By default, @command{configure} sets the prefix for files it installs to
3530 @file{/usr/local}.  The user of @command{configure} can select a different
3531 prefix using the @option{--prefix} and @option{--exec-prefix} options.
3532 There are two ways to change the default: when creating
3533 @command{configure}, and when running it.
3535 Some software packages might want to install in a directory other than
3536 @file{/usr/local} by default.  To accomplish that, use the
3537 @code{AC_PREFIX_DEFAULT} macro.
3539 @defmac AC_PREFIX_DEFAULT (@var{prefix})
3540 @acindex{PREFIX_DEFAULT}
3541 Set the default installation prefix to @var{prefix} instead of
3542 @file{/usr/local}.
3543 @end defmac
3545 It may be convenient for users to have @command{configure} guess the
3546 installation prefix from the location of a related program that they
3547 have already installed.  If you wish to do that, you can call
3548 @code{AC_PREFIX_PROGRAM}.
3550 @anchor{AC_PREFIX_PROGRAM}
3551 @defmac AC_PREFIX_PROGRAM (@var{program})
3552 @acindex{PREFIX_PROGRAM}
3553 If the user did not specify an installation prefix (using the
3554 @option{--prefix} option), guess a value for it by looking for
3555 @var{program} in @env{PATH}, the way the shell does.  If @var{program}
3556 is found, set the prefix to the parent of the directory containing
3557 @var{program}, else default the prefix as described above
3558 (@file{/usr/local} or @code{AC_PREFIX_DEFAULT}).  For example, if
3559 @var{program} is @code{gcc} and the @env{PATH} contains
3560 @file{/usr/local/gnu/bin/gcc}, set the prefix to @file{/usr/local/gnu}.
3561 @end defmac
3565 @c ======================================================== Existing tests
3567 @node Existing Tests
3568 @chapter Existing Tests
3570 These macros test for particular system features that packages might
3571 need or want to use.  If you need to test for a kind of feature that
3572 none of these macros check for, you can probably do it by calling
3573 primitive test macros with appropriate arguments (@pxref{Writing
3574 Tests}).
3576 These tests print messages telling the user which feature they're
3577 checking for, and what they find.  They cache their results for future
3578 @command{configure} runs (@pxref{Caching Results}).
3580 Some of these macros set output variables.  @xref{Makefile
3581 Substitutions}, for how to get their values.  The phrase ``define
3582 @var{name}'' is used below as a shorthand to mean ``define the C
3583 preprocessor symbol @var{name} to the value 1''.  @xref{Defining
3584 Symbols}, for how to get those symbol definitions into your program.
3586 @menu
3587 * Common Behavior::             Macros' standard schemes
3588 * Alternative Programs::        Selecting between alternative programs
3589 * Files::                       Checking for the existence of files
3590 * Libraries::                   Library archives that might be missing
3591 * Library Functions::           C library functions that might be missing
3592 * Header Files::                Header files that might be missing
3593 * Declarations::                Declarations that may be missing
3594 * Structures::                  Structures or members that might be missing
3595 * Types::                       Types that might be missing
3596 * Compilers and Preprocessors::  Checking for compiling programs
3597 * System Services::             Operating system services
3598 * Posix Variants::              Special kludges for specific Posix variants
3599 * Erlang Libraries::            Checking for the existence of Erlang libraries
3600 @end menu
3602 @node Common Behavior
3603 @section Common Behavior
3604 @cindex Common autoconf behavior
3606 Much effort has been expended to make Autoconf easy to learn.  The most
3607 obvious way to reach this goal is simply to enforce standard interfaces
3608 and behaviors, avoiding exceptions as much as possible.  Because of
3609 history and inertia, unfortunately, there are still too many exceptions
3610 in Autoconf; nevertheless, this section describes some of the common
3611 rules.
3613 @menu
3614 * Standard Symbols::            Symbols defined by the macros
3615 * Default Includes::            Includes used by the generic macros
3616 @end menu
3618 @node Standard Symbols
3619 @subsection Standard Symbols
3620 @cindex Standard symbols
3622 All the generic macros that @code{AC_DEFINE} a symbol as a result of
3623 their test transform their @var{argument} values to a standard alphabet.
3624 First, @var{argument} is converted to upper case and any asterisks
3625 (@samp{*}) are each converted to @samp{P}.  Any remaining characters
3626 that are not alphanumeric are converted to underscores.
3628 For instance,
3630 @example
3631 AC_CHECK_TYPES([struct $Expensive*])
3632 @end example
3634 @noindent
3635 defines the symbol @samp{HAVE_STRUCT__EXPENSIVEP} if the check
3636 succeeds.
3639 @node Default Includes
3640 @subsection Default Includes
3641 @cindex Default includes
3642 @cindex Includes, default
3644 Several tests depend upon a set of header files.  Since these headers
3645 are not universally available, tests actually have to provide a set of
3646 protected includes, such as:
3648 @example
3649 @group
3650 #ifdef TIME_WITH_SYS_TIME
3651 # include <sys/time.h>
3652 # include <time.h>
3653 #else
3654 # ifdef HAVE_SYS_TIME_H
3655 #  include <sys/time.h>
3656 # else
3657 #  include <time.h>
3658 # endif
3659 #endif
3660 @end group
3661 @end example
3663 @noindent
3664 Unless you know exactly what you are doing, you should avoid using
3665 unconditional includes, and check the existence of the headers you
3666 include beforehand (@pxref{Header Files}).
3668 Most generic macros use the following macro to provide the default set
3669 of includes:
3671 @defmac AC_INCLUDES_DEFAULT (@ovar{include-directives})
3672 @acindex{INCLUDES_DEFAULT}
3673 Expand to @var{include-directives} if defined, otherwise to:
3675 @example
3676 @group
3677 #include <stdio.h>
3678 #ifdef HAVE_SYS_TYPES_H
3679 # include <sys/types.h>
3680 #endif
3681 #ifdef HAVE_SYS_STAT_H
3682 # include <sys/stat.h>
3683 #endif
3684 #ifdef STDC_HEADERS
3685 # include <stdlib.h>
3686 # include <stddef.h>
3687 #else
3688 # ifdef HAVE_STDLIB_H
3689 #  include <stdlib.h>
3690 # endif
3691 #endif
3692 #ifdef HAVE_STRING_H
3693 # if !defined STDC_HEADERS && defined HAVE_MEMORY_H
3694 #  include <memory.h>
3695 # endif
3696 # include <string.h>
3697 #endif
3698 #ifdef HAVE_STRINGS_H
3699 # include <strings.h>
3700 #endif
3701 #ifdef HAVE_INTTYPES_H
3702 # include <inttypes.h>
3703 #endif
3704 #ifdef HAVE_STDINT_H
3705 # include <stdint.h>
3706 #endif
3707 #ifdef HAVE_UNISTD_H
3708 # include <unistd.h>
3709 #endif
3710 @end group
3711 @end example
3713 If the default includes are used, then check for the presence of these
3714 headers and their compatibility, i.e., you don't need to run
3715 @code{AC_HEADER_STDC}, nor check for @file{stdlib.h} etc.
3717 These headers are checked for in the same order as they are included.
3718 For instance, on some systems @file{string.h} and @file{strings.h} both
3719 exist, but conflict.  Then @code{HAVE_STRING_H} is defined, not
3720 @code{HAVE_STRINGS_H}.
3721 @end defmac
3723 @node Alternative Programs
3724 @section Alternative Programs
3725 @cindex Programs, checking
3727 These macros check for the presence or behavior of particular programs.
3728 They are used to choose between several alternative programs and to
3729 decide what to do once one has been chosen.  If there is no macro
3730 specifically defined to check for a program you need, and you don't need
3731 to check for any special properties of it, then you can use one of the
3732 general program-check macros.
3734 @menu
3735 * Particular Programs::         Special handling to find certain programs
3736 * Generic Programs::            How to find other programs
3737 @end menu
3739 @node Particular Programs
3740 @subsection Particular Program Checks
3742 These macros check for particular programs---whether they exist, and
3743 in some cases whether they support certain features.
3745 @defmac AC_PROG_AWK
3746 @acindex{PROG_AWK}
3747 @ovindex AWK
3748 Check for @code{gawk}, @code{mawk}, @code{nawk}, and @code{awk}, in that
3749 order, and set output variable @code{AWK} to the first one that is found.
3750 It tries @code{gawk} first because that is reported to be the
3751 best implementation.
3752 @end defmac
3754 @defmac AC_PROG_GREP
3755 @acindex{PROG_GREP}
3756 @ovindex GREP
3757 Look for the best available @code{grep} or @code{ggrep} that accepts the
3758 longest input lines possible, and that supports multiple @option{-e} options.
3759 Set the output variable @code{GREP} to whatever is chosen.
3760 @xref{Limitations of Usual Tools}, for more information about
3761 portability problems with the @command{grep} command family.
3762 @end defmac
3764 @defmac AC_PROG_EGREP
3765 @acindex{PROG_EGREP}
3766 @ovindex EGREP
3767 Check whether @code{$GREP -E} works, or else look for the best available
3768 @code{egrep} or @code{gegrep} that accepts the longest input lines possible.
3769 Set the output variable @code{EGREP} to whatever is chosen.
3770 @end defmac
3772 @defmac AC_PROG_FGREP
3773 @acindex{PROG_FGREP}
3774 @ovindex FGREP
3775 Check whether @code{$GREP -F} works, or else look for the best available
3776 @code{fgrep} or @code{gfgrep} that accepts the longest input lines possible.
3777 Set the output variable @code{FGREP} to whatever is chosen.
3778 @end defmac
3780 @defmac AC_PROG_INSTALL
3781 @acindex{PROG_INSTALL}
3782 @ovindex INSTALL
3783 @ovindex INSTALL_PROGRAM
3784 @ovindex INSTALL_DATA
3785 @ovindex INSTALL_SCRIPT
3786 Set output variable @code{INSTALL} to the name of a @acronym{BSD}-compatible
3787 @command{install} program, if one is found in the current @env{PATH}.
3788 Otherwise, set @code{INSTALL} to @samp{@var{dir}/install-sh -c},
3789 checking the directories specified to @code{AC_CONFIG_AUX_DIR} (or its
3790 default directories) to determine @var{dir} (@pxref{Output}).  Also set
3791 the variables @code{INSTALL_PROGRAM} and @code{INSTALL_SCRIPT} to
3792 @samp{$@{INSTALL@}} and @code{INSTALL_DATA} to @samp{$@{INSTALL@} -m 644}.
3794 @samp{@@INSTALL@@} is special, as its value may vary for different
3795 configuration files.
3797 This macro screens out various instances of @command{install} known not to
3798 work.  It prefers to find a C program rather than a shell script, for
3799 speed.  Instead of @file{install-sh}, it can also use @file{install.sh},
3800 but that name is obsolete because some @command{make} programs have a rule
3801 that creates @file{install} from it if there is no makefile.  Further, this
3802 macro requires @command{install} to be able to install multiple files into a
3803 target directory in a single invocation.
3805 Autoconf comes with a copy of @file{install-sh} that you can use.  If
3806 you use @code{AC_PROG_INSTALL}, you must include either
3807 @file{install-sh} or @file{install.sh} in your distribution; otherwise
3808 @command{configure} produces an error message saying it can't find
3809 them---even if the system you're on has a good @command{install} program.
3810 This check is a safety measure to prevent you from accidentally leaving
3811 that file out, which would prevent your package from installing on
3812 systems that don't have a @acronym{BSD}-compatible @command{install} program.
3814 If you need to use your own installation program because it has features
3815 not found in standard @command{install} programs, there is no reason to use
3816 @code{AC_PROG_INSTALL}; just put the file name of your program into your
3817 @file{Makefile.in} files.
3818 @end defmac
3820 @defmac AC_PROG_MKDIR_P
3821 @acindex{PROG_MKDIR_P}
3822 @ovindex MKDIR_P
3823 Set output variable @code{MKDIR_P} to a program that ensures that for
3824 each argument, a directory named by this argument exists, creating it
3825 and its parent directories if needed, and without race conditions when
3826 two instances of the program attempt to make the same directory at
3827 nearly the same time.
3829 This macro uses the @samp{mkdir -p} command if possible.  Otherwise, it
3830 falls back on invoking @command{install-sh} with the @option{-d} option,
3831 so your package should
3832 contain @file{install-sh} as described under @code{AC_PROG_INSTALL}.
3833 An @file{install-sh} file that predates Autoconf 2.60 or Automake 1.10
3834 is vulnerable to race conditions, so if you want to support parallel
3835 installs from
3836 different packages into the same directory you need to make sure you
3837 have an up-to-date @file{install-sh}.  In particular, be careful about
3838 using @samp{autoreconf -if} if your Automake predates Automake 1.10.
3840 This macro is related to the @code{AS_MKDIR_P} macro (@pxref{Programming
3841 in M4sh}), but it sets an output variable intended for use in other
3842 files, whereas @code{AS_MKDIR_P} is intended for use in scripts like
3843 @command{configure}.  Also, @code{AS_MKDIR_P} does not accept options,
3844 but @code{MKDIR_P} supports the @option{-m} option, e.g., a makefile
3845 might invoke @code{$(MKDIR_P) -m 0 dir} to create an inaccessible
3846 directory, and conversely a makefile should use @code{$(MKDIR_P) --
3847 $(FOO)} if @var{FOO} might yield a value that begins with @samp{-}.
3848 Finally, @code{AS_MKDIR_P} does not check for race condition
3849 vulnerability, whereas @code{AC_PROG_MKDIR_P} does.
3851 @samp{@@MKDIR_P@@} is special, as its value may vary for different
3852 configuration files.
3853 @end defmac
3855 @anchor{AC_PROG_LEX}
3856 @defmac AC_PROG_LEX
3857 @acindex{PROG_LEX}
3858 @ovindex LEX
3859 @ovindex LEXLIB
3860 @cvindex YYTEXT_POINTER
3861 @ovindex LEX_OUTPUT_ROOT
3862 If @code{flex} is found, set output variable @code{LEX} to @samp{flex}
3863 and @code{LEXLIB} to @option{-lfl}, if that library is in a standard
3864 place.  Otherwise set @code{LEX} to @samp{lex} and @code{LEXLIB} to
3865 @option{-ll}.
3867 Define @code{YYTEXT_POINTER} if @code{yytext} defaults to @samp{char *} instead
3868 of to @samp{char []}.  Also set output variable @code{LEX_OUTPUT_ROOT} to
3869 the base of the file name that the lexer generates; usually
3870 @file{lex.yy}, but sometimes something else.  These results vary
3871 according to whether @code{lex} or @code{flex} is being used.
3873 You are encouraged to use Flex in your sources, since it is both more
3874 pleasant to use than plain Lex and the C source it produces is portable.
3875 In order to ensure portability, however, you must either provide a
3876 function @code{yywrap} or, if you don't use it (e.g., your scanner has
3877 no @samp{#include}-like feature), simply include a @samp{%noyywrap}
3878 statement in the scanner's source.  Once this done, the scanner is
3879 portable (unless @emph{you} felt free to use nonportable constructs) and
3880 does not depend on any library.  In this case, and in this case only, it
3881 is suggested that you use this Autoconf snippet:
3883 @example
3884 AC_PROG_LEX
3885 if test "$LEX" != flex; then
3886   LEX="$SHELL $missing_dir/missing flex"
3887   AC_SUBST([LEX_OUTPUT_ROOT], [lex.yy])
3888   AC_SUBST([LEXLIB], [''])
3890 @end example
3892 The shell script @command{missing} can be found in the Automake
3893 distribution.
3895 To ensure backward compatibility, Automake's @code{AM_PROG_LEX} invokes
3896 (indirectly) this macro twice, which causes an annoying but benign
3897 ``@code{AC_PROG_LEX} invoked multiple times'' warning.  Future versions
3898 of Automake will fix this issue; meanwhile, just ignore this message.
3900 As part of running the test, this macro may delete any file in the
3901 configuration directory named @file{lex.yy.c} or @file{lexyy.c}.
3902 @end defmac
3904 @anchor{AC_PROG_LN_S}
3905 @defmac AC_PROG_LN_S
3906 @acindex{PROG_LN_S}
3907 @ovindex LN_S
3908 If @samp{ln -s} works on the current file system (the operating system
3909 and file system support symbolic links), set the output variable
3910 @code{LN_S} to @samp{ln -s}; otherwise, if @samp{ln} works, set
3911 @code{LN_S} to @samp{ln}, and otherwise set it to @samp{cp -p}.
3913 If you make a link in a directory other than the current directory, its
3914 meaning depends on whether @samp{ln} or @samp{ln -s} is used.  To safely
3915 create links using @samp{$(LN_S)}, either find out which form is used
3916 and adjust the arguments, or always invoke @code{ln} in the directory
3917 where the link is to be created.
3919 In other words, it does not work to do:
3920 @example
3921 $(LN_S) foo /x/bar
3922 @end example
3924 Instead, do:
3926 @example
3927 (cd /x && $(LN_S) foo bar)
3928 @end example
3929 @end defmac
3931 @defmac AC_PROG_RANLIB
3932 @acindex{PROG_RANLIB}
3933 @ovindex RANLIB
3934 Set output variable @code{RANLIB} to @samp{ranlib} if @code{ranlib}
3935 is found, and otherwise to @samp{:} (do nothing).
3936 @end defmac
3938 @defmac AC_PROG_SED
3939 @acindex{PROG_SED}
3940 @ovindex SED
3941 Set output variable @code{SED} to a Sed implementation that conforms to
3942 Posix and does not have arbitrary length limits.  Report an error if no
3943 acceptable Sed is found.  @xref{Limitations of Usual Tools}, for more
3944 information about portability problems with Sed.
3945 @end defmac
3947 @defmac AC_PROG_YACC
3948 @acindex{PROG_YACC}
3949 @ovindex YACC
3950 If @code{bison} is found, set output variable @code{YACC} to @samp{bison
3951 -y}.  Otherwise, if @code{byacc} is found, set @code{YACC} to
3952 @samp{byacc}.  Otherwise set @code{YACC} to @samp{yacc}.
3953 @end defmac
3955 @node Generic Programs
3956 @subsection Generic Program and File Checks
3958 These macros are used to find programs not covered by the ``particular''
3959 test macros.  If you need to check the behavior of a program as well as
3960 find out whether it is present, you have to write your own test for it
3961 (@pxref{Writing Tests}).  By default, these macros use the environment
3962 variable @env{PATH}.  If you need to check for a program that might not
3963 be in the user's @env{PATH}, you can pass a modified path to use
3964 instead, like this:
3966 @example
3967 AC_PATH_PROG([INETD], [inetd], [/usr/libexec/inetd],
3968              [$PATH$PATH_SEPARATOR/usr/libexec$PATH_SEPARATOR]dnl
3969 [/usr/sbin$PATH_SEPARATOR/usr/etc$PATH_SEPARATOR/etc])
3970 @end example
3972 You are strongly encouraged to declare the @var{variable} passed to
3973 @code{AC_CHECK_PROG} etc.@: as precious, @xref{Setting Output Variables},
3974 @code{AC_ARG_VAR}, for more details.
3976 @anchor{AC_CHECK_PROG}
3977 @defmac AC_CHECK_PROG (@var{variable}, @var{prog-to-check-for}, @
3978   @var{value-if-found}, @ovar{value-if-not-found}, @dvar{path, $PATH}, @
3979   @ovar{reject})
3980 @acindex{CHECK_PROG}
3981 Check whether program @var{prog-to-check-for} exists in @var{path}.  If
3982 it is found, set @var{variable} to @var{value-if-found}, otherwise to
3983 @var{value-if-not-found}, if given.  Always pass over @var{reject} (an
3984 absolute file name) even if it is the first found in the search path; in
3985 that case, set @var{variable} using the absolute file name of the
3986 @var{prog-to-check-for} found that is not @var{reject}.  If
3987 @var{variable} was already set, do nothing.  Calls @code{AC_SUBST} for
3988 @var{variable}.
3989 @end defmac
3991 @anchor{AC_CHECK_PROGS}
3992 @defmac AC_CHECK_PROGS (@var{variable}, @var{progs-to-check-for}, @
3993   @ovar{value-if-not-found}, @dvar{path, $PATH})
3994 @acindex{CHECK_PROGS}
3995 Check for each program in the blank-separated list
3996 @var{progs-to-check-for} existing in the @var{path}.  If one is found, set
3997 @var{variable} to the name of that program.  Otherwise, continue
3998 checking the next program in the list.  If none of the programs in the
3999 list are found, set @var{variable} to @var{value-if-not-found}; if
4000 @var{value-if-not-found} is not specified, the value of @var{variable}
4001 is not changed.  Calls @code{AC_SUBST} for @var{variable}.
4002 @end defmac
4004 @defmac AC_CHECK_TARGET_TOOL (@var{variable}, @var{prog-to-check-for}, @
4005   @ovar{value-if-not-found}, @dvar{path, $PATH})
4006 @acindex{CHECK_TARGET_TOOL}
4007 Like @code{AC_CHECK_PROG}, but first looks for @var{prog-to-check-for}
4008 with a prefix of the target type as determined by
4009 @code{AC_CANONICAL_TARGET}, followed by a dash (@pxref{Canonicalizing}).
4010 If the tool cannot be found with a prefix, and if the build and target
4011 types are equal, then it is also searched for without a prefix.
4013 As noted in @ref{Specifying Names, , Specifying the system type}, the
4014 target is rarely specified, because most of the time it is the same
4015 as the host: it is the type of system for which any compiler tool in
4016 the package produces code.  What this macro looks for is,
4017 for example, @emph{a tool @r{(assembler, linker, etc.)}@: that the
4018 compiler driver @r{(@command{gcc} for the @acronym{GNU} C Compiler)}
4019 uses to produce objects, archives or executables}.
4020 @end defmac
4022 @defmac AC_CHECK_TOOL (@var{variable}, @var{prog-to-check-for}, @
4023   @ovar{value-if-not-found}, @dvar{path, $PATH})
4024 @acindex{CHECK_TOOL}
4025 Like @code{AC_CHECK_PROG}, but first looks for @var{prog-to-check-for}
4026 with a prefix of the host type as specified by @option{--host}, followed by a
4027 dash.  For example, if the user runs
4028 @samp{configure --build=x86_64-gnu --host=i386-gnu}, then this call:
4029 @example
4030 AC_CHECK_TOOL([RANLIB], [ranlib], [:])
4031 @end example
4032 @noindent
4033 sets @code{RANLIB} to @file{i386-gnu-ranlib} if that program exists in
4034 @var{path}, or otherwise to @samp{ranlib} if that program exists in
4035 @var{path}, or to @samp{:} if neither program exists.
4037 In the future, when cross-compiling this macro will @emph{only}
4038 accept program names that are prefixed with the host type.
4039 For more information, see @ref{Specifying Names, , Specifying the
4040 system type}.
4041 @end defmac
4043 @defmac AC_CHECK_TARGET_TOOLS (@var{variable}, @var{progs-to-check-for}, @
4044   @ovar{value-if-not-found}, @dvar{path, $PATH})
4045 @acindex{CHECK_TARGET_TOOLS}
4046 Like @code{AC_CHECK_TARGET_TOOL}, each of the tools in the list
4047 @var{progs-to-check-for} are checked with a prefix of the target type as
4048 determined by @code{AC_CANONICAL_TARGET}, followed by a dash
4049 (@pxref{Canonicalizing}).  If none of the tools can be found with a
4050 prefix, and if the build and target types are equal, then the first one
4051 without a prefix is used.  If a tool is found, set @var{variable} to
4052 the name of that program.  If none of the tools in the list are found,
4053 set @var{variable} to @var{value-if-not-found}; if @var{value-if-not-found}
4054 is not specified, the value of @var{variable} is not changed.  Calls
4055 @code{AC_SUBST} for @var{variable}.
4056 @end defmac
4058 @defmac AC_CHECK_TOOLS (@var{variable}, @var{progs-to-check-for}, @
4059   @ovar{value-if-not-found}, @dvar{path, $PATH})
4060 @acindex{CHECK_TOOLS}
4061 Like @code{AC_CHECK_TOOL}, each of the tools in the list
4062 @var{progs-to-check-for} are checked with a prefix of the host type as
4063 determined by @code{AC_CANONICAL_HOST}, followed by a dash
4064 (@pxref{Canonicalizing}).  If none of the tools can be found with a
4065 prefix, then the first one without a prefix is used.  If a tool is found,
4066 set @var{variable} to the name of that program.  If none of the tools in
4067 the list are found, set @var{variable} to @var{value-if-not-found}; if
4068 @var{value-if-not-found} is not specified, the value of @var{variable}
4069 is not changed.  Calls @code{AC_SUBST} for @var{variable}.
4071 In the future, when cross-compiling this macro will @emph{not}
4072 accept program names that are not prefixed with the host type.
4073 @end defmac
4075 @anchor{AC_PATH_PROG}
4076 @defmac AC_PATH_PROG (@var{variable}, @var{prog-to-check-for}, @
4077   @ovar{value-if-not-found}, @dvar{path, $PATH})
4078 @acindex{PATH_PROG}
4079 Like @code{AC_CHECK_PROG}, but set @var{variable} to the absolute
4080 name of @var{prog-to-check-for} if found.
4081 @end defmac
4083 @anchor{AC_PATH_PROGS}
4084 @defmac AC_PATH_PROGS (@var{variable}, @var{progs-to-check-for}, @
4085   @ovar{value-if-not-found}, @dvar{path, $PATH})
4086 @acindex{PATH_PROGS}
4087 Like @code{AC_CHECK_PROGS}, but if any of @var{progs-to-check-for}
4088 are found, set @var{variable} to the absolute name of the program
4089 found.
4090 @end defmac
4092 @defmac AC_PATH_PROGS_FEATURE_CHECK (@var{variable}, @
4093   @var{progs-to-check-for}, @var{feature-test}, @
4094   @ovar{action-if-not-found}, @dvar{path, $PATH})
4095 @acindex{PATH_PROGS_FEATURE_CHECK}
4096 This macro was introduced in Autoconf 2.62.  If @var{variable} is not
4097 empty, then set the cache variable @code{$ac_cv_path_@var{variable}} to
4098 its value.  Otherwise, check for each program in the blank-separated
4099 list @var{progs-to-check-for} existing in @var{path}.  For each program
4100 found, execute @var{feature-test} with @code{$ac_path_@var{variable}}
4101 set to the absolute name of the candidate program.  If no invocation of
4102 @var{feature-test} sets the shell variable
4103 @code{$ac_cv_path_@var{variable}}, then @var{action-if-not-found} is
4104 executed.  @var{feature-test} will be run even when
4105 @code{ac_cv_path_@var{variable}} is set, to provide the ability to
4106 choose a better candidate found later in @var{path}; to accept the
4107 current setting and bypass all futher checks, @var{feature-test} can
4108 execute @code{ac_path_@var{variable}_found=:}.
4110 Note that this macro has some subtle differences from
4111 @code{AC_CHECK_PROGS}.  It is designed to be run inside
4112 @code{AC_CACHE_VAL}, therefore, it should have no side effects.  In
4113 particular, @var{variable} is not set to the final value of
4114 @code{ac_cv_path_@var{variable}}, nor is @code{AC_SUBST} automatically
4115 run.  Also, on failure, any action can be performed, whereas
4116 @code{AC_CHECK_PROGS} only performs
4117 @code{@var{variable}=@var{value-if-not-found}}.
4119 Here is an example, similar to what Autoconf uses in its own configure
4120 script.  It will search for an implementation of @command{m4} that
4121 supports the @code{indir} builtin, even if it goes by the name
4122 @command{gm4} or is not the first implementation on @env{PATH}.
4124 @example
4125 AC_CACHE_CHECK([for m4 that supports indir], [ac_cv_path_M4],
4126   [AC_PATH_PROGS_FEATURE_CHECK([M4], [m4 gm4],
4127     [[m4out=`echo 'changequote([,])indir([divnum])' | $ac_path_M4`
4128       test "x$m4out" = x0 \
4129       && ac_cv_path_M4=$ac_path_M4 ac_path_M4_found=:]],
4130     [AC_MSG_ERROR([could not find m4 that supports indir])])])
4131 AC_SUBST([M4], [$ac_cv_path_M4])
4132 @end example
4133 @end defmac
4135 @defmac AC_PATH_TARGET_TOOL (@var{variable}, @var{prog-to-check-for}, @
4136   @ovar{value-if-not-found}, @dvar{path, $PATH})
4137 @acindex{PATH_TARGET_TOOL}
4138 Like @code{AC_CHECK_TARGET_TOOL}, but set @var{variable} to the absolute
4139 name of the program if it is found.
4140 @end defmac
4142 @defmac AC_PATH_TOOL (@var{variable}, @var{prog-to-check-for}, @
4143   @ovar{value-if-not-found}, @dvar{path, $PATH})
4144 @acindex{PATH_TOOL}
4145 Like @code{AC_CHECK_TOOL}, but set @var{variable} to the absolute
4146 name of the program if it is found.
4148 In the future, when cross-compiling this macro will @emph{not}
4149 accept program names that are not prefixed with the host type.
4150 @end defmac
4153 @node Files
4154 @section Files
4155 @cindex File, checking
4157 You might also need to check for the existence of files.  Before using
4158 these macros, ask yourself whether a runtime test might not be a better
4159 solution.  Be aware that, like most Autoconf macros, they test a feature
4160 of the host machine, and therefore, they die when cross-compiling.
4162 @defmac AC_CHECK_FILE (@var{file}, @ovar{action-if-found}, @
4163   @ovar{action-if-not-found})
4164 @acindex{CHECK_FILE}
4165 Check whether file @var{file} exists on the native system.  If it is
4166 found, execute @var{action-if-found}, otherwise do
4167 @var{action-if-not-found}, if given.
4168 @end defmac
4170 @defmac AC_CHECK_FILES (@var{files}, @ovar{action-if-found}, @
4171   @ovar{action-if-not-found})
4172 @acindex{CHECK_FILES}
4173 Executes @code{AC_CHECK_FILE} once for each file listed in @var{files}.
4174 Additionally, defines @samp{HAVE_@var{file}} (@pxref{Standard Symbols})
4175 for each file found.
4176 @end defmac
4179 @node Libraries
4180 @section Library Files
4181 @cindex Library, checking
4183 The following macros check for the presence of certain C, C++, or Fortran
4184 library archive files.
4186 @anchor{AC_CHECK_LIB}
4187 @defmac AC_CHECK_LIB (@var{library}, @var{function}, @
4188   @ovar{action-if-found}, @ovar{action-if-not-found}, @ovar{other-libraries})
4189 @acindex{CHECK_LIB}
4190 Test whether the library @var{library} is available by trying to link
4191 a test program that calls function @var{function} with the library.
4192 @var{function} should be a function provided by the library.
4193 Use the base
4194 name of the library; e.g., to check for @option{-lmp}, use @samp{mp} as
4195 the @var{library} argument.
4197 @var{action-if-found} is a list of shell commands to run if the link
4198 with the library succeeds; @var{action-if-not-found} is a list of shell
4199 commands to run if the link fails.  If @var{action-if-found} is not
4200 specified, the default action prepends @option{-l@var{library}} to
4201 @code{LIBS} and defines @samp{HAVE_LIB@var{library}} (in all
4202 capitals).  This macro is intended to support building @code{LIBS} in
4203 a right-to-left (least-dependent to most-dependent) fashion such that
4204 library dependencies are satisfied as a natural side effect of
4205 consecutive tests.  Linkers are sensitive to library ordering
4206 so the order in which @code{LIBS} is generated is important to reliable
4207 detection of libraries.
4209 If linking with @var{library} results in unresolved symbols that would
4210 be resolved by linking with additional libraries, give those libraries
4211 as the @var{other-libraries} argument, separated by spaces:
4212 e.g., @option{-lXt -lX11}.  Otherwise, this macro fails to detect
4213 that @var{library} is present, because linking the test program
4214 always fails with unresolved symbols.  The @var{other-libraries} argument
4215 should be limited to cases where it is desirable to test for one library
4216 in the presence of another that is not already in @code{LIBS}.
4218 @code{AC_CHECK_LIB} requires some care in usage, and should be avoided
4219 in some common cases.  Many standard functions like @code{gethostbyname}
4220 appear in the standard C library on some hosts, and in special libraries
4221 like @code{nsl} on other hosts.  On some hosts the special libraries
4222 contain variant implementations that you may not want to use.  These
4223 days it is normally better to use @code{AC_SEARCH_LIBS([gethostbyname],
4224 [nsl])} instead of @code{AC_CHECK_LIB([nsl], [gethostbyname])}.
4225 @end defmac
4227 @anchor{AC_SEARCH_LIBS}
4228 @defmac AC_SEARCH_LIBS (@var{function}, @var{search-libs}, @
4229   @ovar{action-if-found}, @ovar{action-if-not-found}, @ovar{other-libraries})
4230 @acindex{SEARCH_LIBS}
4231 Search for a library defining @var{function} if it's not already
4232 available.  This equates to calling
4233 @samp{AC_LINK_IFELSE([AC_LANG_CALL([], [@var{function}])])} first with
4234 no libraries, then for each library listed in @var{search-libs}.
4236 Add @option{-l@var{library}} to @code{LIBS} for the first library found
4237 to contain @var{function}, and run @var{action-if-found}.  If the
4238 function is not found, run @var{action-if-not-found}.
4240 If linking with @var{library} results in unresolved symbols that would
4241 be resolved by linking with additional libraries, give those libraries
4242 as the @var{other-libraries} argument, separated by spaces:
4243 e.g., @option{-lXt -lX11}.  Otherwise, this macro fails to detect
4244 that @var{function} is present, because linking the test program
4245 always fails with unresolved symbols.
4246 @end defmac
4250 @node Library Functions
4251 @section Library Functions
4253 The following macros check for particular C library functions.
4254 If there is no macro specifically defined to check for a function you need,
4255 and you don't need to check for any special properties of
4256 it, then you can use one of the general function-check macros.
4258 @menu
4259 * Function Portability::        Pitfalls with usual functions
4260 * Particular Functions::        Special handling to find certain functions
4261 * Generic Functions::           How to find other functions
4262 @end menu
4264 @node Function Portability
4265 @subsection Portability of C Functions
4266 @cindex Portability of C functions
4267 @cindex C function portability
4269 Most usual functions can either be missing, or be buggy, or be limited
4270 on some architectures.  This section tries to make an inventory of these
4271 portability issues.  By definition, this list always requires
4272 additions.  Please help us keeping it as complete as possible.
4274 @table @asis
4275 @item @code{exit}
4276 @c @fuindex exit
4277 @prindex @code{exit}
4278 On ancient hosts, @code{exit} returned @code{int}.
4279 This is because @code{exit} predates @code{void}, and there was a long
4280 tradition of it returning @code{int}.
4282 On current hosts, the problem more likely is that @code{exit} is not
4283 declared, due to C++ problems of some sort or another.  For this reason
4284 we suggest that test programs not invoke @code{exit}, but return from
4285 @code{main} instead.
4287 @item @code{free}
4288 @c @fuindex free
4289 @prindex @code{free}
4290 The C standard says a call @code{free (NULL)} does nothing, but
4291 some old systems don't support this (e.g., NextStep).
4293 @item @code{isinf}
4294 @itemx @code{isnan}
4295 @c @fuindex isinf
4296 @c @fuindex isnan
4297 @prindex @code{isinf}
4298 @prindex @code{isnan}
4299 The C99 standard says that @code{isinf} and @code{isnan} are
4300 macros.  On some systems just macros are available
4301 (e.g., @acronym{HP-UX} and Solaris 10), on
4302 some systems both macros and functions (e.g., glibc 2.3.2), and on some
4303 systems only functions (e.g., IRIX 6 and Solaris 9).  In some cases
4304 these functions are declared in nonstandard headers like
4305 @code{<sunmath.h>} and defined in non-default libraries like
4306 @option{-lm} or @option{-lsunmath}.
4308 The C99 @code{isinf} and @code{isnan} macros work correctly with
4309 @code{long double} arguments, but pre-C99 systems that use functions
4310 typically assume @code{double} arguments.  On such a system,
4311 @code{isinf} incorrectly returns true for a finite @code{long double}
4312 argument that is outside the range of @code{double}.
4314 To work around this porting mess, you can use code like the following.
4316 @smallexample
4317 #include <math.h>
4319 #ifndef isnan
4320 # define isnan(x) \
4321     (sizeof (x) == sizeof (long double) ? isnan_ld (x) \
4322      : sizeof (x) == sizeof (double) ? isnan_d (x) \
4323      : isnan_f (x))
4324 static inline int isnan_f  (float       x) @{ return x != x; @}
4325 static inline int isnan_d  (double      x) @{ return x != x; @}
4326 static inline int isnan_ld (long double x) @{ return x != x; @}
4327 #endif
4329 #ifndef isinf
4330 # define isinf(x) \
4331     (sizeof (x) == sizeof (long double) ? isinf_ld (x) \
4332      : sizeof (x) == sizeof (double) ? isinf_d (x) \
4333      : isinf_f (x))
4334 static inline int isinf_f  (float       x) @{ return isnan (x - x); @}
4335 static inline int isinf_d  (double      x) @{ return isnan (x - x); @}
4336 static inline int isinf_ld (long double x) @{ return isnan (x - x); @}
4337 #endif
4338 @end smallexample
4340 Use @code{AC_C_INLINE} (@pxref{C Compiler}) so that this code works on
4341 compilers that lack the @code{inline} keyword.  Some optimizing
4342 compilers mishandle these definitions, but systems with that bug
4343 typically have missing or broken @code{isnan} functions anyway, so it's
4344 probably not worth worrying about.
4346 @item @code{malloc}
4347 @c @fuindex malloc
4348 @prindex @code{malloc}
4349 The C standard says a call @code{malloc (0)} is implementation
4350 dependent.  It can return either @code{NULL} or a new non-null pointer.
4351 The latter is more common (e.g., the @acronym{GNU} C Library) but is by
4352 no means universal.  @code{AC_FUNC_MALLOC}
4353 can be used to insist on non-@code{NULL} (@pxref{Particular Functions}).
4355 @item @code{putenv}
4356 @c @fuindex putenv
4357 @prindex @code{putenv}
4358 Posix prefers @code{setenv} to @code{putenv}; among other things,
4359 @code{putenv} is not required of all Posix implementations, but
4360 @code{setenv} is.
4362 Posix specifies that @code{putenv} puts the given string directly in
4363 @code{environ}, but some systems make a copy of it instead (e.g.,
4364 glibc 2.0, or @acronym{BSD}).  And when a copy is made, @code{unsetenv} might
4365 not free it, causing a memory leak (e.g., Free@acronym{BSD} 4).
4367 On some systems @code{putenv ("FOO")} removes @samp{FOO} from the
4368 environment, but this is not standard usage and it dumps core
4369 on some systems (e.g., AIX).
4371 On MinGW, a call @code{putenv ("FOO=")} removes @samp{FOO} from the
4372 environment, rather than inserting it with an empty value.
4374 @item @code{realloc}
4375 @c @fuindex realloc
4376 @prindex @code{realloc}
4377 The C standard says a call @code{realloc (NULL, size)} is equivalent
4378 to @code{malloc (size)}, but some old systems don't support this (e.g.,
4379 NextStep).
4381 @item @code{signal} handler
4382 @c @fuindex signal
4383 @prindex @code{signal}
4384 @prindex @code{sigaction}
4385 Normally @code{signal} takes a handler function with a return type of
4386 @code{void}, but some old systems required @code{int} instead.  Any
4387 actual @code{int} value returned is not used; this is only a
4388 difference in the function prototype demanded.
4390 All systems we know of in current use return @code{void}.  The
4391 @code{int} was to support K&R C, where of course @code{void} is not
4392 available.  The obsolete macro @code{AC_TYPE_SIGNAL}
4393 (@pxref{AC_TYPE_SIGNAL}) can be used to establish the correct type in
4394 all cases.
4396 In most cases, it is more robust to use @code{sigaction} when it is
4397 available, rather than @code{signal}.
4399 @item @code{snprintf}
4400 @c @fuindex snprintf
4401 @prindex @code{snprintf}
4402 @c @fuindex vsnprintf
4403 @prindex @code{vsnprintf}
4404 The C99 standard says that if the output array isn't big enough
4405 and if no other errors occur, @code{snprintf} and @code{vsnprintf}
4406 truncate the output and return the number of bytes that ought to have
4407 been produced.  Some older systems return the truncated length (e.g.,
4408 @acronym{GNU} C Library 2.0.x or @sc{irix} 6.5), some a negative value
4409 (e.g., earlier @acronym{GNU} C Library versions), and some the buffer
4410 length without truncation (e.g., 32-bit Solaris 7).  Also, some buggy
4411 older systems ignore the length and overrun the buffer (e.g., 64-bit
4412 Solaris 7).
4414 @item @code{sprintf}
4415 @c @fuindex sprintf
4416 @prindex @code{sprintf}
4417 @c @fuindex vsprintf
4418 @prindex @code{vsprintf}
4419 The C standard says @code{sprintf} and @code{vsprintf} return the
4420 number of bytes written.  On some ancient systems (SunOS 4 for
4421 instance) they return the buffer pointer instead, but these no
4422 longer need to be worried about.
4424 @item @code{sscanf}
4425 @c @fuindex sscanf
4426 @prindex @code{sscanf}
4427 On various old systems, e.g., @acronym{HP-UX} 9, @code{sscanf} requires
4428 that its
4429 input string be writable (though it doesn't actually change it).  This
4430 can be a problem when using @command{gcc} since it normally puts
4431 constant strings in read-only memory (@pxref{Incompatibilities,
4432 Incompatibilities of @acronym{GCC}, , gcc, Using and
4433 Porting the @acronym{GNU} Compiler Collection}).  Apparently in some cases even
4434 having format strings read-only can be a problem.
4436 @item @code{strerror_r}
4437 @c @fuindex strerror_r
4438 @prindex @code{strerror_r}
4439 Posix specifies that @code{strerror_r} returns an @code{int}, but many
4440 systems (e.g., @acronym{GNU} C Library version 2.2.4) provide a
4441 different version returning a @code{char *}.  @code{AC_FUNC_STRERROR_R}
4442 can detect which is in use (@pxref{Particular Functions}).
4444 @item @code{strnlen}
4445 @c @fuindex strnlen
4446 @prindex @code{strnlen}
4447 @acronym{AIX} 4.3 provides a broken version which produces the
4448 following results:
4450 @example
4451 strnlen ("foobar", 0) = 0
4452 strnlen ("foobar", 1) = 3
4453 strnlen ("foobar", 2) = 2
4454 strnlen ("foobar", 3) = 1
4455 strnlen ("foobar", 4) = 0
4456 strnlen ("foobar", 5) = 6
4457 strnlen ("foobar", 6) = 6
4458 strnlen ("foobar", 7) = 6
4459 strnlen ("foobar", 8) = 6
4460 strnlen ("foobar", 9) = 6
4461 @end example
4463 @item @code{sysconf}
4464 @c @fuindex sysconf
4465 @prindex @code{sysconf}
4466 @code{_SC_PAGESIZE} is standard, but some older systems (e.g., @acronym{HP-UX}
4467 9) have @code{_SC_PAGE_SIZE} instead.  This can be tested with
4468 @code{#ifdef}.
4470 @item @code{unlink}
4471 @c @fuindex unlink
4472 @prindex @code{unlink}
4473 The Posix spec says that @code{unlink} causes the given file to be
4474 removed only after there are no more open file handles for it.  Some
4475 non-Posix hosts have trouble with this requirement, though,
4476 and some @acronym{DOS} variants even corrupt the file system.
4478 @item @code{unsetenv}
4479 @c @fuindex unsetenv
4480 @prindex @code{unsetenv}
4481 On MinGW, @code{unsetenv} is not available, but a variable @samp{FOO}
4482 can be removed with a call @code{putenv ("FOO=")}, as described under
4483 @code{putenv} above.
4485 @item @code{va_copy}
4486 @c @fuindex va_copy
4487 @prindex @code{va_copy}
4488 The C99 standard provides @code{va_copy} for copying
4489 @code{va_list} variables.  It may be available in older environments
4490 too, though possibly as @code{__va_copy} (e.g., @command{gcc} in strict
4491 pre-C99 mode).  These can be tested with @code{#ifdef}.  A fallback to
4492 @code{memcpy (&dst, &src, sizeof (va_list))} gives maximum
4493 portability.
4495 @item @code{va_list}
4496 @c @fuindex va_list
4497 @prindex @code{va_list}
4498 @code{va_list} is not necessarily just a pointer.  It can be a
4499 @code{struct} (e.g., @command{gcc} on Alpha), which means @code{NULL} is
4500 not portable.  Or it can be an array (e.g., @command{gcc} in some
4501 PowerPC configurations), which means as a function parameter it can be
4502 effectively call-by-reference and library routines might modify the
4503 value back in the caller (e.g., @code{vsnprintf} in the @acronym{GNU} C Library
4504 2.1).
4506 @item Signed @code{>>}
4507 Normally the C @code{>>} right shift of a signed type replicates the
4508 high bit, giving a so-called ``arithmetic'' shift.  But care should be
4509 taken since Standard C doesn't require that behavior.  On those
4510 few processors without a native arithmetic shift (for instance Cray
4511 vector systems) zero bits may be shifted in, the same as a shift of an
4512 unsigned type.
4514 @item Integer @code{/}
4515 C divides signed integers by truncating their quotient toward zero,
4516 yielding the same result as Fortran.  However, before C99 the standard
4517 allowed C implementations to take the floor or ceiling of the quotient
4518 in some cases.  Hardly any implementations took advantage of this
4519 freedom, though, and it's probably not worth worrying about this issue
4520 nowadays.
4521 @end table
4524 @node Particular Functions
4525 @subsection Particular Function Checks
4526 @cindex Function, checking
4528 These macros check for particular C functions---whether they exist, and
4529 in some cases how they respond when given certain arguments.
4531 @anchor{AC_FUNC_ALLOCA}
4532 @defmac AC_FUNC_ALLOCA
4533 @acindex{FUNC_ALLOCA}
4534 @cvindex C_ALLOCA
4535 @cvindex HAVE_ALLOCA_H
4536 @ovindex ALLOCA
4537 @c @fuindex alloca
4538 @prindex @code{alloca}
4539 @hdrindex{alloca.h}
4540 Check how to get @code{alloca}.  Tries to get a builtin version by
4541 checking for @file{alloca.h} or the predefined C preprocessor macros
4542 @code{__GNUC__} and @code{_AIX}.  If this macro finds @file{alloca.h},
4543 it defines @code{HAVE_ALLOCA_H}.
4545 If those attempts fail, it looks for the function in the standard C
4546 library.  If any of those methods succeed, it defines
4547 @code{HAVE_ALLOCA}.  Otherwise, it sets the output variable
4548 @code{ALLOCA} to @samp{$@{LIBOBJDIR@}alloca.o} and defines
4549 @code{C_ALLOCA} (so programs can periodically call @samp{alloca (0)} to
4550 garbage collect).  This variable is separate from @code{LIBOBJS} so
4551 multiple programs can share the value of @code{ALLOCA} without needing
4552 to create an actual library, in case only some of them use the code in
4553 @code{LIBOBJS}.  The @samp{$@{LIBOBJDIR@}} prefix serves the same
4554 purpose as in @code{LIBOBJS} (@pxref{AC_LIBOBJ vs LIBOBJS}).
4556 This macro does not try to get @code{alloca} from the System V R3
4557 @file{libPW} or the System V R4 @file{libucb} because those libraries
4558 contain some incompatible functions that cause trouble.  Some versions
4559 do not even contain @code{alloca} or contain a buggy version.  If you
4560 still want to use their @code{alloca}, use @code{ar} to extract
4561 @file{alloca.o} from them instead of compiling @file{alloca.c}.
4563 Source files that use @code{alloca} should start with a piece of code
4564 like the following, to declare it properly.
4566 @example
4567 @group
4568 #ifdef HAVE_ALLOCA_H
4569 # include <alloca.h>
4570 #elif defined __GNUC__
4571 # define alloca __builtin_alloca
4572 #elif defined _AIX
4573 # define alloca __alloca
4574 #elif defined _MSC_VER
4575 # include <malloc.h>
4576 # define alloca _alloca
4577 #else
4578 # include <stddef.h>
4579 # ifdef  __cplusplus
4580 extern "C"
4581 # endif
4582 void *alloca (size_t);
4583 #endif
4584 @end group
4585 @end example
4586 @end defmac
4588 @defmac AC_FUNC_CHOWN
4589 @acindex{FUNC_CHOWN}
4590 @cvindex HAVE_CHOWN
4591 @c @fuindex chown
4592 @prindex @code{chown}
4593 If the @code{chown} function is available and works (in particular, it
4594 should accept @option{-1} for @code{uid} and @code{gid}), define
4595 @code{HAVE_CHOWN}.
4596 @end defmac
4598 @anchor{AC_FUNC_CLOSEDIR_VOID}
4599 @defmac AC_FUNC_CLOSEDIR_VOID
4600 @acindex{FUNC_CLOSEDIR_VOID}
4601 @cvindex CLOSEDIR_VOID
4602 @c @fuindex closedir
4603 @prindex @code{closedir}
4604 If the @code{closedir} function does not return a meaningful value,
4605 define @code{CLOSEDIR_VOID}.  Otherwise, callers ought to check its
4606 return value for an error indicator.
4608 Currently this test is implemented by running a test program.  When
4609 cross compiling the pessimistic assumption that @code{closedir} does not
4610 return a meaningful value is made.
4612 This macro is obsolescent, as @code{closedir} returns a meaningful value
4613 on current systems.  New programs need not use this macro.
4614 @end defmac
4616 @defmac AC_FUNC_ERROR_AT_LINE
4617 @acindex{FUNC_ERROR_AT_LINE}
4618 @c @fuindex error_at_line
4619 @prindex @code{error_at_line}
4620 If the @code{error_at_line} function is not found, require an
4621 @code{AC_LIBOBJ} replacement of @samp{error}.
4622 @end defmac
4624 @defmac AC_FUNC_FNMATCH
4625 @acindex{FUNC_FNMATCH}
4626 @c @fuindex fnmatch
4627 @prindex @code{fnmatch}
4628 If the @code{fnmatch} function conforms to Posix, define
4629 @code{HAVE_FNMATCH}.  Detect common implementation bugs, for example,
4630 the bugs in Solaris 2.4.
4632 Unlike the other specific
4633 @code{AC_FUNC} macros, @code{AC_FUNC_FNMATCH} does not replace a
4634 broken/missing @code{fnmatch}.  This is for historical reasons.
4635 See @code{AC_REPLACE_FNMATCH} below.
4637 This macro is obsolescent.  New programs should use Gnulib's
4638 @code{fnmatch-posix} module.  @xref{Gnulib}.
4639 @end defmac
4641 @defmac AC_FUNC_FNMATCH_GNU
4642 @acindex{FUNC_FNMATCH_GNU}
4643 @c @fuindex fnmatch
4644 @prindex @code{fnmatch}
4645 Behave like @code{AC_REPLACE_FNMATCH} (@emph{replace}) but also test
4646 whether @code{fnmatch} supports @acronym{GNU} extensions.  Detect common
4647 implementation bugs, for example, the bugs in the @acronym{GNU} C
4648 Library 2.1.
4650 This macro is obsolescent.  New programs should use Gnulib's
4651 @code{fnmatch-gnu} module.  @xref{Gnulib}.
4652 @end defmac
4654 @anchor{AC_FUNC_FORK}
4655 @defmac AC_FUNC_FORK
4656 @acindex{FUNC_FORK}
4657 @cvindex HAVE_VFORK_H
4658 @cvindex HAVE_WORKING_FORK
4659 @cvindex HAVE_WORKING_VFORK
4660 @cvindex vfork
4661 @c @fuindex fork
4662 @prindex @code{fork}
4663 @c @fuindex vfork
4664 @prindex @code{vfork}
4665 @hdrindex{vfork.h}
4666 This macro checks for the @code{fork} and @code{vfork} functions.  If a
4667 working @code{fork} is found, define @code{HAVE_WORKING_FORK}.  This macro
4668 checks whether @code{fork} is just a stub by trying to run it.
4670 If @file{vfork.h} is found, define @code{HAVE_VFORK_H}.  If a working
4671 @code{vfork} is found, define @code{HAVE_WORKING_VFORK}.  Otherwise,
4672 define @code{vfork} to be @code{fork} for backward compatibility with
4673 previous versions of @command{autoconf}.  This macro checks for several known
4674 errors in implementations of @code{vfork} and considers the system to not
4675 have a working @code{vfork} if it detects any of them.  It is not considered
4676 to be an implementation error if a child's invocation of @code{signal}
4677 modifies the parent's signal handler, since child processes rarely change
4678 their signal handlers.
4680 Since this macro defines @code{vfork} only for backward compatibility with
4681 previous versions of @command{autoconf} you're encouraged to define it
4682 yourself in new code:
4683 @example
4684 @group
4685 #ifndef HAVE_WORKING_VFORK
4686 # define vfork fork
4687 #endif
4688 @end group
4689 @end example
4690 @end defmac
4692 @defmac AC_FUNC_FSEEKO
4693 @acindex{FUNC_FSEEKO}
4694 @cvindex _LARGEFILE_SOURCE
4695 @cvindex HAVE_FSEEKO
4696 @c @fuindex fseeko
4697 @prindex @code{fseeko}
4698 If the @code{fseeko} function is available, define @code{HAVE_FSEEKO}.
4699 Define @code{_LARGEFILE_SOURCE} if necessary to make the prototype
4700 visible on some systems (e.g., glibc 2.2).  Otherwise linkage problems
4701 may occur when compiling with @code{AC_SYS_LARGEFILE} on
4702 largefile-sensitive systems where @code{off_t} does not default to a
4703 64bit entity.
4704 @end defmac
4706 @defmac AC_FUNC_GETGROUPS
4707 @acindex{FUNC_GETGROUPS}
4708 @cvindex HAVE_GETGROUPS
4709 @ovindex GETGROUPS_LIBS
4710 @c @fuindex getgroups
4711 @prindex @code{getgroups}
4712 If the @code{getgroups} function is available and works (unlike on
4713 Ultrix 4.3, where @samp{getgroups (0, 0)} always fails), define
4714 @code{HAVE_GETGROUPS}.  Set @code{GETGROUPS_LIBS} to any libraries
4715 needed to get that function.  This macro runs @code{AC_TYPE_GETGROUPS}.
4716 @end defmac
4718 @anchor{AC_FUNC_GETLOADAVG}
4719 @defmac AC_FUNC_GETLOADAVG
4720 @acindex{FUNC_GETLOADAVG}
4721 @cvindex SVR4
4722 @cvindex DGUX
4723 @cvindex UMAX
4724 @cvindex UMAX4_3
4725 @cvindex HAVE_NLIST_H
4726 @cvindex NLIST_NAME_UNION
4727 @cvindex GETLOADAVG_PRIVILEGED
4728 @cvindex NEED_SETGID
4729 @cvindex C_GETLOADAVG
4730 @ovindex LIBOBJS
4731 @ovindex NEED_SETGID
4732 @ovindex KMEM_GROUP
4733 @ovindex GETLOADAVG_LIBS
4734 @c @fuindex getloadavg
4735 @prindex @code{getloadavg}
4736 Check how to get the system load averages.  To perform its tests
4737 properly, this macro needs the file @file{getloadavg.c}; therefore, be
4738 sure to set the @code{AC_LIBOBJ} replacement directory properly (see
4739 @ref{Generic Functions}, @code{AC_CONFIG_LIBOBJ_DIR}).
4741 If the system has the @code{getloadavg} function, define
4742 @code{HAVE_GETLOADAVG}, and set @code{GETLOADAVG_LIBS} to any libraries
4743 necessary to get that function.  Also add @code{GETLOADAVG_LIBS} to
4744 @code{LIBS}.  Otherwise, require an @code{AC_LIBOBJ} replacement for
4745 @samp{getloadavg} with source code in @file{@var{dir}/getloadavg.c}, and
4746 possibly define several other C preprocessor macros and output
4747 variables:
4749 @enumerate
4750 @item
4751 Define @code{C_GETLOADAVG}.
4753 @item
4754 Define @code{SVR4}, @code{DGUX}, @code{UMAX}, or @code{UMAX4_3} if on
4755 those systems.
4757 @item
4758 @hdrindex{nlist.h}
4759 If @file{nlist.h} is found, define @code{HAVE_NLIST_H}.
4761 @item
4762 If @samp{struct nlist} has an @samp{n_un.n_name} member, define
4763 @code{HAVE_STRUCT_NLIST_N_UN_N_NAME}.  The obsolete symbol
4764 @code{NLIST_NAME_UNION} is still defined, but do not depend upon it.
4766 @item
4767 Programs may need to be installed set-group-ID (or set-user-ID) for
4768 @code{getloadavg} to work.  In this case, define
4769 @code{GETLOADAVG_PRIVILEGED}, set the output variable @code{NEED_SETGID}
4770 to @samp{true} (and otherwise to @samp{false}), and set
4771 @code{KMEM_GROUP} to the name of the group that should own the installed
4772 program.
4773 @end enumerate
4775 The @code{AC_FUNC_GETLOADAVG} macro is obsolescent.  New programs should
4776 use Gnulib's @code{getloadavg} module.  @xref{Gnulib}.
4777 @end defmac
4779 @anchor{AC_FUNC_GETMNTENT}
4780 @defmac AC_FUNC_GETMNTENT
4781 @acindex{FUNC_GETMNTENT}
4782 @cvindex HAVE_GETMNTENT
4783 @c @fuindex getmntent
4784 @prindex @code{getmntent}
4785 Check for @code{getmntent} in the standard C library, and then in the
4786 @file{sun}, @file{seq}, and @file{gen} libraries, for @sc{unicos},
4787 @sc{irix} 4, @sc{ptx}, and UnixWare, respectively.  Then, if
4788 @code{getmntent} is available, define @code{HAVE_GETMNTENT}.
4789 @end defmac
4791 @defmac AC_FUNC_GETPGRP
4792 @acindex{FUNC_GETPGRP}
4793 @cvindex GETPGRP_VOID
4794 @c @fuindex getpgid
4795 @c @fuindex getpgrp
4796 @prindex @code{getpgid}
4797 @prindex @code{getpgrp}
4798 Define @code{GETPGRP_VOID} if it is an error to pass 0 to
4799 @code{getpgrp}; this is the Posix behavior.  On older @acronym{BSD}
4800 systems, you must pass 0 to @code{getpgrp}, as it takes an argument and
4801 behaves like Posix's @code{getpgid}.
4803 @example
4804 #ifdef GETPGRP_VOID
4805   pid = getpgrp ();
4806 #else
4807   pid = getpgrp (0);
4808 #endif
4809 @end example
4811 This macro does not check whether
4812 @code{getpgrp} exists at all; if you need to work in that situation,
4813 first call @code{AC_CHECK_FUNC} for @code{getpgrp}.
4815 This macro is obsolescent, as current systems have a @code{getpgrp}
4816 whose signature conforms to Posix.  New programs need not use this macro.
4817 @end defmac
4819 @defmac AC_FUNC_LSTAT_FOLLOWS_SLASHED_SYMLINK
4820 @acindex{FUNC_LSTAT_FOLLOWS_SLASHED_SYMLINK}
4821 @cvindex LSTAT_FOLLOWS_SLASHED_SYMLINK
4822 @c @fuindex lstat
4823 @prindex @code{lstat}
4824 If @file{link} is a symbolic link, then @code{lstat} should treat
4825 @file{link/} the same as @file{link/.}.  However, many older
4826 @code{lstat} implementations incorrectly ignore trailing slashes.
4828 It is safe to assume that if @code{lstat} incorrectly ignores
4829 trailing slashes, then other symbolic-link-aware functions like
4830 @code{unlink} also incorrectly ignore trailing slashes.
4832 If @code{lstat} behaves properly, define
4833 @code{LSTAT_FOLLOWS_SLASHED_SYMLINK}, otherwise require an
4834 @code{AC_LIBOBJ} replacement of @code{lstat}.
4835 @end defmac
4837 @defmac AC_FUNC_MALLOC
4838 @acindex{FUNC_MALLOC}
4839 @cvindex HAVE_MALLOC
4840 @cvindex malloc
4841 @c @fuindex malloc
4842 @prindex @code{malloc}
4843 If the @code{malloc} function is compatible with the @acronym{GNU} C
4844 library @code{malloc} (i.e., @samp{malloc (0)} returns a valid
4845 pointer), define @code{HAVE_MALLOC} to 1.  Otherwise define
4846 @code{HAVE_MALLOC} to 0, ask for an @code{AC_LIBOBJ} replacement for
4847 @samp{malloc}, and define @code{malloc} to @code{rpl_malloc} so that the
4848 native @code{malloc} is not used in the main project.
4850 Typically, the replacement file @file{malloc.c} should look like (note
4851 the @samp{#undef malloc}):
4853 @verbatim
4854 #include <config.h>
4855 #undef malloc
4857 #include <sys/types.h>
4859 void *malloc ();
4861 /* Allocate an N-byte block of memory from the heap.
4862    If N is zero, allocate a 1-byte block.  */
4864 void *
4865 rpl_malloc (size_t n)
4867   if (n == 0)
4868     n = 1;
4869   return malloc (n);
4871 @end verbatim
4872 @end defmac
4874 @defmac AC_FUNC_MEMCMP
4875 @acindex{FUNC_MEMCMP}
4876 @ovindex LIBOBJS
4877 @c @fuindex memcmp
4878 @prindex @code{memcmp}
4879 If the @code{memcmp} function is not available, or does not work on
4880 8-bit data (like the one on SunOS 4.1.3), or fails when comparing 16
4881 bytes or more and with at least one buffer not starting on a 4-byte
4882 boundary (such as the one on NeXT x86 OpenStep), require an
4883 @code{AC_LIBOBJ} replacement for @samp{memcmp}.
4885 This macro is obsolescent, as current systems have a working
4886 @code{memcmp}.  New programs need not use this macro.
4887 @end defmac
4889 @defmac AC_FUNC_MBRTOWC
4890 @acindex{FUNC_MBRTOWC}
4891 @cvindex HAVE_MBRTOWC
4892 @c @fuindex mbrtowc
4893 @prindex @code{mbrtowc}
4894 Define @code{HAVE_MBRTOWC} to 1 if the function @code{mbrtowc} and the
4895 type @code{mbstate_t} are properly declared.
4896 @end defmac
4898 @defmac AC_FUNC_MKTIME
4899 @acindex{FUNC_MKTIME}
4900 @ovindex LIBOBJS
4901 @c @fuindex mktime
4902 @prindex @code{mktime}
4903 If the @code{mktime} function is not available, or does not work
4904 correctly, require an @code{AC_LIBOBJ} replacement for @samp{mktime}.
4905 For the purposes of this test, @code{mktime} should conform to the
4906 Posix standard and should be the inverse of
4907 @code{localtime}.
4908 @end defmac
4910 @anchor{AC_FUNC_MMAP}
4911 @defmac AC_FUNC_MMAP
4912 @acindex{FUNC_MMAP}
4913 @cvindex HAVE_MMAP
4914 @c @fuindex mmap
4915 @prindex @code{mmap}
4916 If the @code{mmap} function exists and works correctly, define
4917 @code{HAVE_MMAP}.  This checks only private fixed mapping of already-mapped
4918 memory.
4919 @end defmac
4921 @defmac AC_FUNC_OBSTACK
4922 @acindex{FUNC_OBSTACK}
4923 @cvindex HAVE_OBSTACK
4924 @cindex obstack
4925 If the obstacks are found, define @code{HAVE_OBSTACK}, else require an
4926 @code{AC_LIBOBJ} replacement for @samp{obstack}.
4927 @end defmac
4929 @defmac AC_FUNC_REALLOC
4930 @acindex{FUNC_REALLOC}
4931 @cvindex HAVE_REALLOC
4932 @cvindex realloc
4933 @c @fuindex realloc
4934 @prindex @code{realloc}
4935 If the @code{realloc} function is compatible with the @acronym{GNU} C
4936 library @code{realloc} (i.e., @samp{realloc (NULL, 0)} returns a
4937 valid pointer), define @code{HAVE_REALLOC} to 1.  Otherwise define
4938 @code{HAVE_REALLOC} to 0, ask for an @code{AC_LIBOBJ} replacement for
4939 @samp{realloc}, and define @code{realloc} to @code{rpl_realloc} so that
4940 the native @code{realloc} is not used in the main project.  See
4941 @code{AC_FUNC_MALLOC} for details.
4942 @end defmac
4944 @defmac AC_FUNC_SELECT_ARGTYPES
4945 @acindex{FUNC_SELECT_ARGTYPES}
4946 @cvindex SELECT_TYPE_ARG1
4947 @cvindex SELECT_TYPE_ARG234
4948 @cvindex SELECT_TYPE_ARG5
4949 @c @fuindex select
4950 @prindex @code{select}
4951 Determines the correct type to be passed for each of the
4952 @code{select} function's arguments, and defines those types
4953 in @code{SELECT_TYPE_ARG1}, @code{SELECT_TYPE_ARG234}, and
4954 @code{SELECT_TYPE_ARG5} respectively.  @code{SELECT_TYPE_ARG1} defaults
4955 to @samp{int}, @code{SELECT_TYPE_ARG234} defaults to @samp{int *},
4956 and @code{SELECT_TYPE_ARG5} defaults to @samp{struct timeval *}.
4958 This macro is obsolescent, as current systems have a @code{select} whose
4959 signature conforms to Posix.  New programs need not use this macro.
4960 @end defmac
4962 @defmac AC_FUNC_SETPGRP
4963 @acindex{FUNC_SETPGRP}
4964 @cvindex SETPGRP_VOID
4965 @c @fuindex setpgrp
4966 @prindex @code{setpgrp}
4967 If @code{setpgrp} takes no argument (the Posix version), define
4968 @code{SETPGRP_VOID}.  Otherwise, it is the @acronym{BSD} version, which takes
4969 two process IDs as arguments.  This macro does not check whether
4970 @code{setpgrp} exists at all; if you need to work in that situation,
4971 first call @code{AC_CHECK_FUNC} for @code{setpgrp}.
4973 This macro is obsolescent, as current systems have a @code{setpgrp}
4974 whose signature conforms to Posix.  New programs need not use this macro.
4975 @end defmac
4977 @defmac AC_FUNC_STAT
4978 @defmacx AC_FUNC_LSTAT
4979 @acindex{FUNC_STAT}
4980 @acindex{FUNC_LSTAT}
4981 @cvindex HAVE_STAT_EMPTY_STRING_BUG
4982 @cvindex HAVE_LSTAT_EMPTY_STRING_BUG
4983 @c @fuindex stat
4984 @prindex @code{stat}
4985 @c @fuindex lstat
4986 @prindex @code{lstat}
4987 Determine whether @code{stat} or @code{lstat} have the bug that it
4988 succeeds when given the zero-length file name as argument.  The @code{stat}
4989 and @code{lstat} from SunOS 4.1.4 and the Hurd (as of 1998-11-01) do
4990 this.
4992 If it does, then define @code{HAVE_STAT_EMPTY_STRING_BUG} (or
4993 @code{HAVE_LSTAT_EMPTY_STRING_BUG}) and ask for an @code{AC_LIBOBJ}
4994 replacement of it.
4996 These macros are obsolescent, as no current systems have the bug.
4997 New programs need not use these macros.
4998 @end defmac
5000 @anchor{AC_FUNC_STRCOLL}
5001 @defmac AC_FUNC_STRCOLL
5002 @acindex{FUNC_STRCOLL}
5003 @cvindex HAVE_STRCOLL
5004 @c @fuindex strcoll
5005 @prindex @code{strcoll}
5006 If the @code{strcoll} function exists and works correctly, define
5007 @code{HAVE_STRCOLL}.  This does a bit more than
5008 @samp{AC_CHECK_FUNCS(strcoll)}, because some systems have incorrect
5009 definitions of @code{strcoll} that should not be used.
5010 @end defmac
5012 @defmac AC_FUNC_STRERROR_R
5013 @acindex{FUNC_STRERROR_R}
5014 @cvindex HAVE_STRERROR_R
5015 @cvindex HAVE_DECL_STRERROR_R
5016 @cvindex STRERROR_R_CHAR_P
5017 @c @fuindex strerror_r
5018 @prindex @code{strerror_r}
5019 If @code{strerror_r} is available, define @code{HAVE_STRERROR_R}, and if
5020 it is declared, define @code{HAVE_DECL_STRERROR_R}.  If it returns a
5021 @code{char *} message, define @code{STRERROR_R_CHAR_P}; otherwise it
5022 returns an @code{int} error number.  The Thread-Safe Functions option of
5023 Posix requires @code{strerror_r} to return @code{int}, but
5024 many systems (including, for example, version 2.2.4 of the @acronym{GNU} C
5025 Library) return a @code{char *} value that is not necessarily equal to
5026 the buffer argument.
5027 @end defmac
5029 @anchor{AC_FUNC_STRFTIME}
5030 @defmac AC_FUNC_STRFTIME
5031 @acindex{FUNC_STRFTIME}
5032 @cvindex HAVE_STRFTIME
5033 @c @fuindex strftime
5034 @prindex @code{strftime}
5035 Check for @code{strftime} in the @file{intl} library, for SCO Unix.
5036 Then, if @code{strftime} is available, define @code{HAVE_STRFTIME}.
5038 This macro is obsolescent, as no current systems require the @file{intl}
5039 library for @code{strftime}.  New programs need not use this macro.
5040 @end defmac
5042 @defmac AC_FUNC_STRTOD
5043 @acindex{FUNC_STRTOD}
5044 @ovindex POW_LIB
5045 @c @fuindex strtod
5046 @prindex @code{strtod}
5047 If the @code{strtod} function does not exist or doesn't work correctly,
5048 ask for an @code{AC_LIBOBJ} replacement of @samp{strtod}.  In this case,
5049 because @file{strtod.c} is likely to need @samp{pow}, set the output
5050 variable @code{POW_LIB} to the extra library needed.
5051 @end defmac
5053 @defmac AC_FUNC_STRTOLD
5054 @acindex{FUNC_STRTOLD}
5055 @cvindex HAVE_STRTOLD
5056 @prindex @code{strtold}
5057 If the @code{strtold} function exists and conforms to C99, define
5058 @code{HAVE_STRTOLD}.
5059 @end defmac
5061 @defmac AC_FUNC_STRNLEN
5062 @acindex{FUNC_STRNLEN}
5063 @cvindex HAVE_STRNLEN
5064 @c @fuindex strnlen
5065 @prindex @code{strnlen}
5066 If the @code{strnlen} function is not available, or is buggy (like the one
5067 from @acronym{AIX} 4.3), require an @code{AC_LIBOBJ} replacement for it.
5068 @end defmac
5070 @anchor{AC_FUNC_UTIME_NULL}
5071 @defmac AC_FUNC_UTIME_NULL
5072 @acindex{FUNC_UTIME_NULL}
5073 @cvindex HAVE_UTIME_NULL
5074 @c @fuindex utime
5075 @prindex @code{utime}
5076 If @samp{utime (@var{file}, NULL)} sets @var{file}'s timestamp to
5077 the present, define @code{HAVE_UTIME_NULL}.
5079 This macro is obsolescent, as all current systems have a @code{utime}
5080 that behaves this way.  New programs need not use this macro.
5081 @end defmac
5083 @anchor{AC_FUNC_VPRINTF}
5084 @defmac AC_FUNC_VPRINTF
5085 @acindex{FUNC_VPRINTF}
5086 @cvindex HAVE_VPRINTF
5087 @cvindex HAVE_DOPRNT
5088 @c @fuindex vprintf
5089 @prindex @code{vprintf}
5090 If @code{vprintf} is found, define @code{HAVE_VPRINTF}.  Otherwise, if
5091 @code{_doprnt} is found, define @code{HAVE_DOPRNT}.  (If @code{vprintf}
5092 is available, you may assume that @code{vfprintf} and @code{vsprintf}
5093 are also available.)
5095 This macro is obsolescent, as all current systems have @code{vprintf}.
5096 New programs need not use this macro.
5097 @end defmac
5099 @defmac AC_REPLACE_FNMATCH
5100 @acindex{REPLACE_FNMATCH}
5101 @c @fuindex fnmatch
5102 @prindex @code{fnmatch}
5103 @hdrindex{fnmatch.h}
5104 If the @code{fnmatch} function does not conform to Posix (see
5105 @code{AC_FUNC_FNMATCH}), ask for its @code{AC_LIBOBJ} replacement.
5107 The files @file{fnmatch.c}, @file{fnmatch_loop.c}, and @file{fnmatch_.h}
5108 in the @code{AC_LIBOBJ} replacement directory are assumed to contain a
5109 copy of the source code of @acronym{GNU} @code{fnmatch}.  If necessary,
5110 this source code is compiled as an @code{AC_LIBOBJ} replacement, and the
5111 @file{fnmatch_.h} file is linked to @file{fnmatch.h} so that it can be
5112 included in place of the system @code{<fnmatch.h>}.
5114 This macro is obsolescent, as it assumes the use of particular source
5115 files.  New programs should use Gnulib's @code{fnmatch-posix} module,
5116 which provides this macro along with the source files.  @xref{Gnulib}.
5117 @end defmac
5121 @node Generic Functions
5122 @subsection Generic Function Checks
5124 These macros are used to find functions not covered by the ``particular''
5125 test macros.  If the functions might be in libraries other than the
5126 default C library, first call @code{AC_CHECK_LIB} for those libraries.
5127 If you need to check the behavior of a function as well as find out
5128 whether it is present, you have to write your own test for
5129 it (@pxref{Writing Tests}).
5131 @anchor{AC_CHECK_FUNC}
5132 @defmac AC_CHECK_FUNC (@var{function}, @ovar{action-if-found}, @
5133   @ovar{action-if-not-found})
5134 @acindex{CHECK_FUNC}
5135 If C function @var{function} is available, run shell commands
5136 @var{action-if-found}, otherwise @var{action-if-not-found}.  If you just
5137 want to define a symbol if the function is available, consider using
5138 @code{AC_CHECK_FUNCS} instead.  This macro checks for functions with C
5139 linkage even when @code{AC_LANG(C++)} has been called, since C is more
5140 standardized than C++.  (@pxref{Language Choice}, for more information
5141 about selecting the language for checks.)
5142 @end defmac
5144 @anchor{AC_CHECK_FUNCS}
5145 @defmac AC_CHECK_FUNCS (@var{function}@dots{}, @ovar{action-if-found}, @
5146   @ovar{action-if-not-found})
5147 @acindex{CHECK_FUNCS}
5148 @cvindex HAVE_@var{function}
5149 For each @var{function} enumerated in the blank-or-newline-separated argument
5150 list, define @code{HAVE_@var{function}} (in all capitals) if it is available.
5151 If @var{action-if-found} is given, it is additional shell code to
5152 execute when one of the functions is found.  You can give it a value of
5153 @samp{break} to break out of the loop on the first match.  If
5154 @var{action-if-not-found} is given, it is executed when one of the
5155 functions is not found.
5156 @end defmac
5158 @defmac AC_CHECK_FUNCS_ONCE (@var{function}@dots{})
5159 @acindex{CHECK_FUNCS_ONCE}
5160 @cvindex HAVE_@var{function}
5161 For each @var{function} enumerated in the blank-or-newline-separated argument
5162 list, define @code{HAVE_@var{function}} (in all capitals) if it is available.
5163 This is a once-only variant of @code{AC_CHECK_FUNCS}.  It generates the
5164 checking code at most once, so that @command{configure} is smaller and
5165 faster; but the checks cannot be conditionalized and are always done once,
5166 early during the @command{configure} run.
5167 @end defmac
5169 @sp 1
5171 Autoconf follows a philosophy that was formed over the years by those
5172 who have struggled for portability: isolate the portability issues in
5173 specific files, and then program as if you were in a Posix
5174 environment.  Some functions may be missing or unfixable, and your
5175 package must be ready to replace them.
5177 Suitable replacements for many such problem functions are available from
5178 Gnulib (@pxref{Gnulib}).
5180 @defmac AC_LIBOBJ (@var{function})
5181 @acindex{LIBOBJ}
5182 @ovindex LIBOBJS
5183 Specify that @samp{@var{function}.c} must be included in the executables
5184 to replace a missing or broken implementation of @var{function}.
5186 Technically, it adds @samp{@var{function}.$ac_objext} to the output
5187 variable @code{LIBOBJS} if it is not already in, and calls
5188 @code{AC_LIBSOURCE} for @samp{@var{function}.c}.  You should not
5189 directly change @code{LIBOBJS}, since this is not traceable.
5190 @end defmac
5192 @defmac AC_LIBSOURCE (@var{file})
5193 @acindex{LIBSOURCE}
5194 Specify that @var{file} might be needed to compile the project.  If you
5195 need to know what files might be needed by a @file{configure.ac}, you
5196 should trace @code{AC_LIBSOURCE}.  @var{file} must be a literal.
5198 This macro is called automatically from @code{AC_LIBOBJ}, but you must
5199 call it explicitly if you pass a shell variable to @code{AC_LIBOBJ}.  In
5200 that case, since shell variables cannot be traced statically, you must
5201 pass to @code{AC_LIBSOURCE} any possible files that the shell variable
5202 might cause @code{AC_LIBOBJ} to need.  For example, if you want to pass
5203 a variable @code{$foo_or_bar} to @code{AC_LIBOBJ} that holds either
5204 @code{"foo"} or @code{"bar"}, you should do:
5206 @example
5207 AC_LIBSOURCE([foo.c])
5208 AC_LIBSOURCE([bar.c])
5209 AC_LIBOBJ([$foo_or_bar])
5210 @end example
5212 @noindent
5213 There is usually a way to avoid this, however, and you are encouraged to
5214 simply call @code{AC_LIBOBJ} with literal arguments.
5216 Note that this macro replaces the obsolete @code{AC_LIBOBJ_DECL}, with
5217 slightly different semantics: the old macro took the function name,
5218 e.g., @code{foo}, as its argument rather than the file name.
5219 @end defmac
5221 @defmac AC_LIBSOURCES (@var{files})
5222 @acindex{LIBSOURCES}
5223 Like @code{AC_LIBSOURCE}, but accepts one or more @var{files} in a
5224 comma-separated M4 list.  Thus, the above example might be rewritten:
5226 @example
5227 AC_LIBSOURCES([foo.c, bar.c])
5228 AC_LIBOBJ([$foo_or_bar])
5229 @end example
5230 @end defmac
5232 @defmac AC_CONFIG_LIBOBJ_DIR (@var{directory})
5233 @acindex{CONFIG_LIBOBJ_DIR}
5234 Specify that @code{AC_LIBOBJ} replacement files are to be found in
5235 @var{directory}, a name relative to the top level of the
5236 source tree.  The replacement directory defaults to @file{.}, the top
5237 level directory, and the most typical value is @file{lib}, corresponding
5238 to @samp{AC_CONFIG_LIBOBJ_DIR([lib])}.
5240 @command{configure} might need to know the replacement directory for the
5241 following reasons: (i) some checks use the replacement files, (ii) some
5242 macros bypass broken system headers by installing links to the
5243 replacement headers (iii) when used in conjunction with Automake,
5244 within each makefile, @var{directory} is used as a relative path
5245 from @code{$(top_srcdir)} to each object named in @code{LIBOBJS} and
5246 @code{LTLIBOBJS}, etc.
5247 @end defmac
5249 @sp 1
5251 It is common to merely check for the existence of a function, and ask
5252 for its @code{AC_LIBOBJ} replacement if missing.  The following macro is
5253 a convenient shorthand.
5255 @defmac AC_REPLACE_FUNCS (@var{function}@dots{})
5256 @acindex{REPLACE_FUNCS}
5257 @cvindex HAVE_@var{function}
5258 @ovindex LIBOBJS
5259 Like @code{AC_CHECK_FUNCS}, but uses @samp{AC_LIBOBJ(@var{function})} as
5260 @var{action-if-not-found}.  You can declare your replacement function by
5261 enclosing the prototype in @samp{#ifndef HAVE_@var{function}}.  If the
5262 system has the function, it probably declares it in a header file you
5263 should be including, so you shouldn't redeclare it lest your declaration
5264 conflict.
5265 @end defmac
5267 @node Header Files
5268 @section Header Files
5269 @cindex Header, checking
5271 The following macros check for the presence of certain C header files.
5272 If there is no macro specifically defined to check for a header file you need,
5273 and you don't need to check for any special properties of
5274 it, then you can use one of the general header-file check macros.
5276 @menu
5277 * Header Portability::          Collected knowledge on common headers
5278 * Particular Headers::          Special handling to find certain headers
5279 * Generic Headers::             How to find other headers
5280 @end menu
5282 @node Header Portability
5283 @subsection Portability of Headers
5284 @cindex Portability of headers
5285 @cindex Header portability
5287 This section tries to collect knowledge about common headers, and the
5288 problems they cause.  By definition, this list always requires
5289 additions.  Please help us keeping it as complete as possible.
5291 @table @asis
5293 @item @file{limits.h}
5294 C99 says that @file{limits.h} defines @code{LLONG_MIN},
5295 @code{LLONG_MAX}, and @code{ULLONG_MAX}, but many almost-C99
5296 environments (e.g., default @acronym{GCC} 4.0.2 + glibc 2.4) do not
5297 define them.
5299 @item @file{inttypes.h} vs.@: @file{stdint.h}
5300 @hdrindex{inttypes.h}
5301 @hdrindex{stdint.h}
5302 The C99 standard says that @file{inttypes.h} includes
5303 @file{stdint.h}, so there's no need to include @file{stdint.h}
5304 separately in a standard environment.  Some implementations have
5305 @file{inttypes.h} but not @file{stdint.h} (e.g., Solaris 7), but we don't
5306 know of any implementation that has @file{stdint.h} but not
5307 @file{inttypes.h}.
5309 @item @file{linux/irda.h}
5310 @hdrindex{linux/irda.h}
5311 It requires @file{linux/types.h} and @file{sys/socket.h}.
5313 @item @file{linux/random.h}
5314 @hdrindex{linux/random.h}
5315 It requires @file{linux/types.h}.
5317 @item @file{net/if.h}
5318 @hdrindex{net/if.h}
5319 On Darwin, this file requires that @file{sys/socket.h} be included
5320 beforehand.  One should run:
5322 @example
5323 AC_CHECK_HEADERS([sys/socket.h])
5324 AC_CHECK_HEADERS([net/if.h], [], [],
5325 [#include <stdio.h>
5326 #ifdef STDC_HEADERS
5327 # include <stdlib.h>
5328 # include <stddef.h>
5329 #else
5330 # ifdef HAVE_STDLIB_H
5331 #  include <stdlib.h>
5332 # endif
5333 #endif
5334 #ifdef HAVE_SYS_SOCKET_H
5335 # include <sys/socket.h>
5336 #endif
5338 @end example
5340 @item @file{netinet/if_ether.h}
5341 @hdrindex{netinet/if_ether.h}
5342 On Darwin, this file requires that @file{stdio.h} and
5343 @file{sys/socket.h} be included beforehand.  One should run:
5345 @example
5346 AC_CHECK_HEADERS([sys/socket.h])
5347 AC_CHECK_HEADERS([netinet/if_ether.h], [], [],
5348 [#include <stdio.h>
5349 #ifdef STDC_HEADERS
5350 # include <stdlib.h>
5351 # include <stddef.h>
5352 #else
5353 # ifdef HAVE_STDLIB_H
5354 #  include <stdlib.h>
5355 # endif
5356 #endif
5357 #ifdef HAVE_SYS_SOCKET_H
5358 # include <sys/socket.h>
5359 #endif
5361 @end example
5363 @item @file{stdint.h}
5364 See above, item @file{inttypes.h} vs.@: @file{stdint.h}.
5366 @item @file{stdlib.h}
5367 @hdrindex{stdlib.h}
5368 On many systems (e.g., Darwin), @file{stdio.h} is a prerequisite.
5370 @item @file{sys/mount.h}
5371 @hdrindex{sys/mount.h}
5372 On Free@acronym{BSD} 4.8 on ia32 and using gcc version 2.95.4,
5373 @file{sys/params.h} is a prerequisite.
5375 @item @file{sys/ptem.h}
5376 @hdrindex{sys/ptem.h}
5377 On Solaris 8, @file{sys/stream.h} is a prerequisite.
5379 @item @file{sys/socket.h}
5380 @hdrindex{sys/socket.h}
5381 On Darwin, @file{stdlib.h} is a prerequisite.
5383 @item @file{sys/ucred.h}
5384 @hdrindex{sys/ucred.h}
5385 On Tru64 5.1, @file{sys/types.h} is a prerequisite.
5387 @item @file{X11/extensions/scrnsaver.h}
5388 @hdrindex{X11/extensions/scrnsaver.h}
5389 Using XFree86, this header requires @file{X11/Xlib.h}, which is probably
5390 so required that you might not even consider looking for it.
5392 @example
5393 AC_CHECK_HEADERS([X11/extensions/scrnsaver.h], [], [],
5394 [[#include <X11/Xlib.h>
5396 @end example
5397 @end table
5400 @node Particular Headers
5401 @subsection Particular Header Checks
5403 These macros check for particular system header files---whether they
5404 exist, and in some cases whether they declare certain symbols.
5406 @defmac AC_HEADER_ASSERT
5407 @acindex{HEADER_ASSERT}
5408 @cvindex NDEBUG
5409 @hdrindex{assert.h}
5410 Check whether to enable assertions in the style of @file{assert.h}.
5411 Assertions are enabled by default, but the user can override this by
5412 invoking @command{configure} with the @option{--disable-assert} option.
5413 @end defmac
5415 @anchor{AC_HEADER_DIRENT}
5416 @defmac AC_HEADER_DIRENT
5417 @acindex{HEADER_DIRENT}
5418 @cvindex HAVE_DIRENT_H
5419 @cvindex HAVE_NDIR_H
5420 @cvindex HAVE_SYS_DIR_H
5421 @cvindex HAVE_SYS_NDIR_H
5422 @hdrindex{dirent.h}
5423 @hdrindex{sys/ndir.h}
5424 @hdrindex{sys/dir.h}
5425 @hdrindex{ndir.h}
5426 Check for the following header files.  For the first one that is
5427 found and defines @samp{DIR}, define the listed C preprocessor macro:
5429 @multitable {@file{sys/ndir.h}} {@code{HAVE_SYS_NDIR_H}}
5430 @item @file{dirent.h}   @tab @code{HAVE_DIRENT_H}
5431 @item @file{sys/ndir.h} @tab @code{HAVE_SYS_NDIR_H}
5432 @item @file{sys/dir.h}  @tab @code{HAVE_SYS_DIR_H}
5433 @item @file{ndir.h}     @tab @code{HAVE_NDIR_H}
5434 @end multitable
5436 The directory-library declarations in your source code should look
5437 something like the following:
5439 @example
5440 @group
5441 #include <sys/types.h>
5442 #ifdef HAVE_DIRENT_H
5443 # include <dirent.h>
5444 # define NAMLEN(dirent) strlen ((dirent)->d_name)
5445 #else
5446 # define dirent direct
5447 # define NAMLEN(dirent) ((dirent)->d_namlen)
5448 # ifdef HAVE_SYS_NDIR_H
5449 #  include <sys/ndir.h>
5450 # endif
5451 # ifdef HAVE_SYS_DIR_H
5452 #  include <sys/dir.h>
5453 # endif
5454 # ifdef HAVE_NDIR_H
5455 #  include <ndir.h>
5456 # endif
5457 #endif
5458 @end group
5459 @end example
5461 Using the above declarations, the program would declare variables to be
5462 of type @code{struct dirent}, not @code{struct direct}, and would access
5463 the length of a directory entry name by passing a pointer to a
5464 @code{struct dirent} to the @code{NAMLEN} macro.
5466 This macro also checks for the SCO Xenix @file{dir} and @file{x} libraries.
5468 This macro is obsolescent, as all current systems with directory
5469 libraries have @code{<dirent.h>}.  New programs need not use this macro.
5471 Also see @code{AC_STRUCT_DIRENT_D_INO} and
5472 @code{AC_STRUCT_DIRENT_D_TYPE} (@pxref{Particular Structures}).
5473 @end defmac
5475 @anchor{AC_HEADER_MAJOR}
5476 @defmac AC_HEADER_MAJOR
5477 @acindex{HEADER_MAJOR}
5478 @cvindex MAJOR_IN_MKDEV
5479 @cvindex MAJOR_IN_SYSMACROS
5480 @hdrindex{sys/mkdev.h}
5481 @hdrindex{sys/sysmacros.h}
5482 If @file{sys/types.h} does not define @code{major}, @code{minor}, and
5483 @code{makedev}, but @file{sys/mkdev.h} does, define
5484 @code{MAJOR_IN_MKDEV}; otherwise, if @file{sys/sysmacros.h} does, define
5485 @code{MAJOR_IN_SYSMACROS}.
5486 @end defmac
5488 @defmac AC_HEADER_RESOLV
5489 @acindex{HEADER_RESOLV}
5490 @cvindex HAVE_RESOLV_H
5491 @hdrindex{resolv.h}
5492 Checks for header @file{resolv.h}, checking for prerequisites first.
5493 To properly use @file{resolv.h}, your code should contain something like
5494 the following:
5496 @verbatim
5497 #ifdef HAVE_SYS_TYPES_H
5498 #  include <sys/types.h>
5499 #endif
5500 #ifdef HAVE_NETINET_IN_H
5501 #  include <netinet/in.h>   /* inet_ functions / structs */
5502 #endif
5503 #ifdef HAVE_ARPA_NAMESER_H
5504 #  include <arpa/nameser.h> /* DNS HEADER struct */
5505 #endif
5506 #ifdef HAVE_NETDB_H
5507 #  include <netdb.h>
5508 #endif
5509 #include <resolv.h>
5510 @end verbatim
5511 @end defmac
5513 @anchor{AC_HEADER_STAT}
5514 @defmac AC_HEADER_STAT
5515 @acindex{HEADER_STAT}
5516 @cvindex STAT_MACROS_BROKEN
5517 @hdrindex{sys/stat.h}
5518 If the macros @code{S_ISDIR}, @code{S_ISREG}, etc.@: defined in
5519 @file{sys/stat.h} do not work properly (returning false positives),
5520 define @code{STAT_MACROS_BROKEN}.  This is the case on Tektronix UTekV,
5521 Amdahl UTS and Motorola System V/88.
5523 This macro is obsolescent, as no current systems have the bug.
5524 New programs need not use this macro.
5525 @end defmac
5527 @defmac AC_HEADER_STDBOOL
5528 @acindex{HEADER_STDBOOL}
5529 @cvindex HAVE_STDBOOL_H
5530 @cvindex HAVE__BOOL
5531 @hdrindex{stdbool.h}
5532 @hdrindex{system.h}
5533 If @file{stdbool.h} exists and conforms to C99, define
5534 @code{HAVE_STDBOOL_H} to 1; if the type @code{_Bool} is defined, define
5535 @code{HAVE__BOOL} to 1.  To fulfill the C99 requirements, your
5536 @file{system.h} could contain the following code:
5538 @verbatim
5539 #ifdef HAVE_STDBOOL_H
5540 # include <stdbool.h>
5541 #else
5542 # ifndef HAVE__BOOL
5543 #  ifdef __cplusplus
5544 typedef bool _Bool;
5545 #  else
5546 #   define _Bool signed char
5547 #  endif
5548 # endif
5549 # define bool _Bool
5550 # define false 0
5551 # define true 1
5552 # define __bool_true_false_are_defined 1
5553 #endif
5554 @end verbatim
5556 Alternatively you can use the @samp{stdbool} package of Gnulib
5557 (@pxref{Gnulib}); it packages the above code into a replacement header
5558 and contains a few other bells and whistles.
5560 @end defmac
5562 @anchor{AC_HEADER_STDC}
5563 @defmac AC_HEADER_STDC
5564 @acindex{HEADER_STDC}
5565 @cvindex STDC_HEADERS
5566 @hdrindex{stdlib.h}
5567 @hdrindex{stdarg.h}
5568 @hdrindex{string.h}
5569 @hdrindex{float.h}
5570 @hdrindex{ctype.h}
5571 Define @code{STDC_HEADERS} if the system has C header files
5572 conforming to @acronym{ANSI} C89 (@acronym{ISO} C90).
5573 Specifically, this macro checks for @file{stdlib.h}, @file{stdarg.h},
5574 @file{string.h}, and @file{float.h}; if the system has those, it
5575 probably has the rest of the C89 header files.  This macro also
5576 checks whether @file{string.h} declares @code{memchr} (and thus
5577 presumably the other @code{mem} functions), whether @file{stdlib.h}
5578 declare @code{free} (and thus presumably @code{malloc} and other related
5579 functions), and whether the @file{ctype.h} macros work on characters
5580 with the high bit set, as the C standard requires.
5582 If you use this macro, your code can refer to @code{STDC_HEADERS} to
5583 determine whether the system has conforming header files (and probably C
5584 library functions).
5586 This macro is obsolescent, as current systems have conforming header
5587 files.  New programs need not use this macro.
5589 @hdrindex{string.h}
5590 @hdrindex{strings.h}
5591 Nowadays @file{string.h} is part of the C standard and declares functions like
5592 @code{strcpy}, and @file{strings.h} is standardized by Posix and declares
5593 @acronym{BSD} functions like @code{bcopy}; but
5594 historically, string functions were a major sticking point in this area.
5595 If you still want to worry about portability to ancient systems without
5596 standard headers, there is so much variation
5597 that it is probably easier to declare the functions you use than to
5598 figure out exactly what the system header files declare.  Some ancient systems
5599 contained a mix of functions from the C standard and from @acronym{BSD};
5600 some were mostly standard but lacked @samp{memmove}; some defined the
5601 @acronym{BSD} functions as macros in @file{string.h} or
5602 @file{strings.h}; some had only the @acronym{BSD} functions but
5603 @file{string.h}; some declared the memory functions in @file{memory.h},
5604 some in @file{string.h}; etc.  It is probably sufficient to check for
5605 one string function and one memory function; if the library had the
5606 standard versions of those then it probably had most of the others.
5607 If you put the following in @file{configure.ac}:
5609 @example
5610 # This example is obsolescent.
5611 # Nowadays you can omit these macro calls.
5612 AC_HEADER_STDC
5613 AC_CHECK_FUNCS([strchr memcpy])
5614 @end example
5616 @noindent
5617 then, in your code, you can use declarations like this:
5619 @example
5620 @group
5621 /* This example is obsolescent.
5622    Nowadays you can just #include <string.h>.  */
5623 #ifdef STDC_HEADERS
5624 # include <string.h>
5625 #else
5626 # ifndef HAVE_STRCHR
5627 #  define strchr index
5628 #  define strrchr rindex
5629 # endif
5630 char *strchr (), *strrchr ();
5631 # ifndef HAVE_MEMCPY
5632 #  define memcpy(d, s, n) bcopy ((s), (d), (n))
5633 #  define memmove(d, s, n) bcopy ((s), (d), (n))
5634 # endif
5635 #endif
5636 @end group
5637 @end example
5639 @noindent
5640 If you use a function like @code{memchr}, @code{memset}, @code{strtok},
5641 or @code{strspn}, which have no @acronym{BSD} equivalent, then macros don't
5642 suffice to port to ancient hosts; you must provide an implementation of
5643 each function.  An easy
5644 way to incorporate your implementations only when needed (since the ones
5645 in system C libraries may be hand optimized) is to, taking @code{memchr}
5646 for example, put it in @file{memchr.c} and use
5647 @samp{AC_REPLACE_FUNCS([memchr])}.
5648 @end defmac
5650 @defmac AC_HEADER_SYS_WAIT
5651 @acindex{HEADER_SYS_WAIT}
5652 @cvindex HAVE_SYS_WAIT_H
5653 @hdrindex{sys/wait.h}
5654 If @file{sys/wait.h} exists and is compatible with Posix, define
5655 @code{HAVE_SYS_WAIT_H}.  Incompatibility can occur if @file{sys/wait.h}
5656 does not exist, or if it uses the old @acronym{BSD} @code{union wait} instead
5657 of @code{int} to store a status value.  If @file{sys/wait.h} is not
5658 Posix compatible, then instead of including it, define the
5659 Posix macros with their usual interpretations.  Here is an
5660 example:
5662 @example
5663 @group
5664 #include <sys/types.h>
5665 #ifdef HAVE_SYS_WAIT_H
5666 # include <sys/wait.h>
5667 #endif
5668 #ifndef WEXITSTATUS
5669 # define WEXITSTATUS(stat_val) ((unsigned int) (stat_val) >> 8)
5670 #endif
5671 #ifndef WIFEXITED
5672 # define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
5673 #endif
5674 @end group
5675 @end example
5677 @noindent
5678 This macro is obsolescent, as current systems are compatible with Posix.
5679 New programs need not use this macro.
5680 @end defmac
5682 @cvindex _POSIX_VERSION
5683 @hdrindex{unistd.h}
5684 @code{_POSIX_VERSION} is defined when @file{unistd.h} is included on
5685 Posix systems.  If there is no @file{unistd.h}, it is definitely
5686 not a Posix system.  However, some non-Posix systems do
5687 have @file{unistd.h}.
5689 The way to check whether the system supports Posix is:
5691 @example
5692 @group
5693 #ifdef HAVE_UNISTD_H
5694 # include <sys/types.h>
5695 # include <unistd.h>
5696 #endif
5698 #ifdef _POSIX_VERSION
5699 /* Code for Posix systems.  */
5700 #endif
5701 @end group
5702 @end example
5704 @anchor{AC_HEADER_TIME}
5705 @defmac AC_HEADER_TIME
5706 @acindex{HEADER_TIME}
5707 @cvindex TIME_WITH_SYS_TIME
5708 @hdrindex{time.h}
5709 @hdrindex{sys/time.h}
5710 If a program may include both @file{time.h} and @file{sys/time.h},
5711 define @code{TIME_WITH_SYS_TIME}.  On some ancient systems,
5712 @file{sys/time.h} included @file{time.h}, but @file{time.h} was not
5713 protected against multiple inclusion, so programs could not explicitly
5714 include both files.  This macro is useful in programs that use, for
5715 example, @code{struct timeval} as well as
5716 @code{struct tm}.  It is best used in conjunction with
5717 @code{HAVE_SYS_TIME_H}, which can be checked for using
5718 @code{AC_CHECK_HEADERS([sys/time.h])}.
5720 @example
5721 @group
5722 #ifdef TIME_WITH_SYS_TIME
5723 # include <sys/time.h>
5724 # include <time.h>
5725 #else
5726 # ifdef HAVE_SYS_TIME_H
5727 #  include <sys/time.h>
5728 # else
5729 #  include <time.h>
5730 # endif
5731 #endif
5732 @end group
5733 @end example
5735 @noindent
5736 This macro is obsolescent, as current systems can include both files
5737 when they exist.  New programs need not use this macro.
5738 @end defmac
5741 @defmac AC_HEADER_TIOCGWINSZ
5742 @acindex{HEADER_TIOCGWINSZ}
5743 @cvindex GWINSZ_IN_SYS_IOCTL
5744 @hdrindex{sys/ioctl.h}
5745 @hdrindex{termios.h}
5746 @c FIXME: I need clarifications from Jim.
5747 If the use of @code{TIOCGWINSZ} requires @file{<sys/ioctl.h>}, then
5748 define @code{GWINSZ_IN_SYS_IOCTL}.  Otherwise @code{TIOCGWINSZ} can be
5749 found in @file{<termios.h>}.
5751 Use:
5753 @example
5754 @group
5755 #ifdef HAVE_TERMIOS_H
5756 # include <termios.h>
5757 #endif
5759 #ifdef GWINSZ_IN_SYS_IOCTL
5760 # include <sys/ioctl.h>
5761 #endif
5762 @end group
5763 @end example
5764 @end defmac
5766 @node Generic Headers
5767 @subsection Generic Header Checks
5769 These macros are used to find system header files not covered by the
5770 ``particular'' test macros.  If you need to check the contents of a header
5771 as well as find out whether it is present, you have to write your own
5772 test for it (@pxref{Writing Tests}).
5774 @anchor{AC_CHECK_HEADER}
5775 @defmac AC_CHECK_HEADER (@var{header-file}, @ovar{action-if-found}, @
5776   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
5777 @acindex{CHECK_HEADER}
5778 If the system header file @var{header-file} is compilable, execute shell
5779 commands @var{action-if-found}, otherwise execute
5780 @var{action-if-not-found}.  If you just want to define a symbol if the
5781 header file is available, consider using @code{AC_CHECK_HEADERS}
5782 instead.
5784 @var{includes} is a series of include directives, defaulting to
5785 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
5786 prior to the header under test.
5788 For compatibility issues with older versions of Autoconf, please read
5789 below.
5790 @end defmac
5792 @anchor{AC_CHECK_HEADERS}
5793 @defmac AC_CHECK_HEADERS (@var{header-file}@dots{}, @
5794   @ovar{action-if-found}, @ovar{action-if-not-found}, @
5795   @dvar{includes, AC_INCLUDES_DEFAULT})
5796 @acindex{CHECK_HEADERS}
5797 @cvindex HAVE_@var{header}
5798 For each given system header file @var{header-file} in the
5799 blank-separated argument list that exists, define
5800 @code{HAVE_@var{header-file}} (in all capitals).  If @var{action-if-found}
5801 is given, it is additional shell code to execute when one of the header
5802 files is found.  You can give it a value of @samp{break} to break out of
5803 the loop on the first match.  If @var{action-if-not-found} is given, it
5804 is executed when one of the header files is not found.
5806 @var{includes} is a series of include directives, defaulting to
5807 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
5808 prior to the headers under test.
5810 For compatibility issues with older versions of Autoconf, please read
5811 below.
5812 @end defmac
5814 Previous versions of Autoconf merely checked whether the header was
5815 accepted by the preprocessor.  This was changed because the old test was
5816 inappropriate for typical uses.  Headers are typically used to compile,
5817 not merely to preprocess, and the old behavior sometimes accepted
5818 headers that clashed at compile-time.  If you need to check whether a
5819 header is preprocessable, you can use @code{AC_PREPROC_IFELSE}
5820 (@pxref{Running the Preprocessor}).
5822 This scheme, which improves the robustness of the test, also requires
5823 that you make sure that headers that must be included before the
5824 @var{header-file} be part of the @var{includes}, (@pxref{Default
5825 Includes}).  If looking for @file{bar.h}, which requires that
5826 @file{foo.h} be included before if it exists, we suggest the following
5827 scheme:
5829 @verbatim
5830 AC_CHECK_HEADERS([foo.h])
5831 AC_CHECK_HEADERS([bar.h], [], [],
5832 [#ifdef HAVE_FOO_H
5833 # include <foo.h>
5834 # endif
5836 @end verbatim
5838 The following variant generates smaller, faster @command{configure}
5839 files if you do not need the full power of @code{AC_CHECK_HEADERS}.
5841 @defmac AC_CHECK_HEADERS_ONCE (@var{header-file}@dots{})
5842 @acindex{CHECK_HEADERS_ONCE}
5843 @cvindex HAVE_@var{header}
5844 For each given system header file @var{header-file} in the
5845 blank-separated argument list that exists, define
5846 @code{HAVE_@var{header-file}} (in all capitals).
5847 This is a once-only variant of @code{AC_CHECK_HEADERS}.  It generates the
5848 checking code at most once, so that @command{configure} is smaller and
5849 faster; but the checks cannot be conditionalized and are always done once,
5850 early during the @command{configure} run.
5851 @end defmac
5853 @node Declarations
5854 @section Declarations
5855 @cindex Declaration, checking
5857 The following macros check for the declaration of variables and
5858 functions.  If there is no macro specifically defined to check for a
5859 symbol you need, then you can use the general macros (@pxref{Generic
5860 Declarations}) or, for more complex tests, you may use
5861 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}).
5863 @menu
5864 * Particular Declarations::     Macros to check for certain declarations
5865 * Generic Declarations::        How to find other declarations
5866 @end menu
5868 @node Particular Declarations
5869 @subsection Particular Declaration Checks
5871 There are no specific macros for declarations.
5873 @node Generic Declarations
5874 @subsection Generic Declaration Checks
5876 These macros are used to find declarations not covered by the ``particular''
5877 test macros.
5879 @defmac AC_CHECK_DECL (@var{symbol}, @ovar{action-if-found}, @
5880   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
5881 @acindex{CHECK_DECL}
5882 If @var{symbol} (a function, variable, or constant) is not declared in
5883 @var{includes} and a declaration is needed, run the shell commands
5884 @var{action-if-not-found}, otherwise @var{action-if-found}.
5885 @var{includes} is a series of include directives, defaulting to
5886 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
5887 prior to the declaration under test.
5889 This macro actually tests whether @var{symbol} is defined as a macro or
5890 can be used as an r-value, not whether it is really declared, because it
5891 is much safer to avoid
5892 introducing extra declarations when they are not needed.
5893 @end defmac
5895 @anchor{AC_CHECK_DECLS}
5896 @defmac AC_CHECK_DECLS (@var{symbols}, @ovar{action-if-found}, @
5897   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
5898 @acindex{CHECK_DECLS}
5899 @cvindex HAVE_DECL_@var{symbol}
5900 For each of the @var{symbols} (@emph{comma}-separated list), define
5901 @code{HAVE_DECL_@var{symbol}} (in all capitals) to @samp{1} if
5902 @var{symbol} is declared, otherwise to @samp{0}.  If
5903 @var{action-if-not-found} is given, it is additional shell code to
5904 execute when one of the function declarations is needed, otherwise
5905 @var{action-if-found} is executed.
5907 @var{includes} is a series of include directives, defaulting to
5908 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
5909 prior to the declarations under test.
5911 This macro uses an M4 list as first argument:
5912 @example
5913 AC_CHECK_DECLS([strdup])
5914 AC_CHECK_DECLS([strlen])
5915 AC_CHECK_DECLS([malloc, realloc, calloc, free])
5916 AC_CHECK_DECLS([j0], [], [], [[#include <math.h>]])
5917 @end example
5919 Unlike the other @samp{AC_CHECK_*S} macros, when a @var{symbol} is not
5920 declared, @code{HAVE_DECL_@var{symbol}} is defined to @samp{0} instead
5921 of leaving @code{HAVE_DECL_@var{symbol}} undeclared.  When you are
5922 @emph{sure} that the check was performed, use
5923 @code{HAVE_DECL_@var{symbol}} in @code{#if}:
5925 @example
5926 #if !HAVE_DECL_SYMBOL
5927 extern char *symbol;
5928 #endif
5929 @end example
5931 @noindent
5932 If the test may have not been performed, however, because it is safer
5933 @emph{not} to declare a symbol than to use a declaration that conflicts
5934 with the system's one, you should use:
5936 @example
5937 #if defined HAVE_DECL_MALLOC && !HAVE_DECL_MALLOC
5938 void *malloc (size_t *s);
5939 #endif
5940 @end example
5942 @noindent
5943 You fall into the second category only in extreme situations: either
5944 your files may be used without being configured, or they are used during
5945 the configuration.  In most cases the traditional approach is enough.
5946 @end defmac
5948 @defmac AC_CHECK_DECLS_ONCE (@var{symbols})
5949 @acindex{CHECK_DECLS_ONCE}
5950 @cvindex HAVE_DECL_@var{symbol}
5951 For each of the @var{symbols} (@emph{comma}-separated list), define
5952 @code{HAVE_DECL_@var{symbol}} (in all capitals) to @samp{1} if
5953 @var{symbol} is declared in the default include files, otherwise to
5954 @samp{0}.  This is a once-only variant of @code{AC_CHECK_DECLS}.  It
5955 generates the checking code at most once, so that @command{configure} is
5956 smaller and faster; but the checks cannot be conditionalized and are
5957 always done once, early during the @command{configure} run.
5958 @end defmac
5961 @node Structures
5962 @section Structures
5963 @cindex Structure, checking
5965 The following macros check for the presence of certain members in C
5966 structures.  If there is no macro specifically defined to check for a
5967 member you need, then you can use the general structure-member macros
5968 (@pxref{Generic Structures}) or, for more complex tests, you may use
5969 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}).
5971 @menu
5972 * Particular Structures::       Macros to check for certain structure members
5973 * Generic Structures::          How to find other structure members
5974 @end menu
5976 @node Particular Structures
5977 @subsection Particular Structure Checks
5979 The following macros check for certain structures or structure members.
5981 @defmac AC_STRUCT_DIRENT_D_INO
5982 @acindex{STRUCT_DIRENT_D_INO}
5983 @cvindex HAVE_STRUCT_DIRENT_D_INO
5984 Perform all the actions of @code{AC_HEADER_DIRENT} (@pxref{Particular
5985 Headers}).  Then, if @code{struct dirent} contains a @code{d_ino}
5986 member, define @code{HAVE_STRUCT_DIRENT_D_INO}.
5988 @code{HAVE_STRUCT_DIRENT_D_INO} indicates only the presence of
5989 @code{d_ino}, not whether its contents are always reliable.
5990 Traditionally, a zero @code{d_ino} indicated a deleted directory entry,
5991 though current systems hide this detail from the user and never return
5992 zero @code{d_ino} values.
5993 Many current systems report an incorrect @code{d_ino} for a directory
5994 entry that is a mount point.
5995 @end defmac
5997 @defmac AC_STRUCT_DIRENT_D_TYPE
5998 @acindex{STRUCT_DIRENT_D_TYPE}
5999 @cvindex HAVE_STRUCT_DIRENT_D_TYPE
6000 Perform all the actions of @code{AC_HEADER_DIRENT} (@pxref{Particular
6001 Headers}).  Then, if @code{struct dirent} contains a @code{d_type}
6002 member, define @code{HAVE_STRUCT_DIRENT_D_TYPE}.
6003 @end defmac
6005 @anchor{AC_STRUCT_ST_BLOCKS}
6006 @defmac AC_STRUCT_ST_BLOCKS
6007 @acindex{STRUCT_ST_BLOCKS}
6008 @cvindex HAVE_STRUCT_STAT_ST_BLOCKS
6009 @cvindex HAVE_ST_BLOCKS
6010 @ovindex LIBOBJS
6011 If @code{struct stat} contains an @code{st_blocks} member, define
6012 @code{HAVE_STRUCT_STAT_ST_BLOCKS}.  Otherwise, require an
6013 @code{AC_LIBOBJ} replacement of @samp{fileblocks}.  The former name,
6014 @code{HAVE_ST_BLOCKS} is to be avoided, as its support will cease in the
6015 future.
6016 @end defmac
6018 @defmac AC_STRUCT_TM
6019 @acindex{STRUCT_TM}
6020 @cvindex TM_IN_SYS_TIME
6021 @hdrindex{time.h}
6022 @hdrindex{sys/time.h}
6023 If @file{time.h} does not define @code{struct tm}, define
6024 @code{TM_IN_SYS_TIME}, which means that including @file{sys/time.h}
6025 had better define @code{struct tm}.
6027 This macro is obsolescent, as @file{time.h} defines @code{struct tm} in
6028 current systems.  New programs need not use this macro.
6029 @end defmac
6031 @anchor{AC_STRUCT_TIMEZONE}
6032 @defmac AC_STRUCT_TIMEZONE
6033 @acindex{STRUCT_TIMEZONE}
6034 @cvindex HAVE_DECL_TZNAME
6035 @cvindex HAVE_STRUCT_TM_TM_ZONE
6036 @cvindex HAVE_TM_ZONE
6037 @cvindex HAVE_TZNAME
6038 Figure out how to get the current timezone.  If @code{struct tm} has a
6039 @code{tm_zone} member, define @code{HAVE_STRUCT_TM_TM_ZONE} (and the
6040 obsoleted @code{HAVE_TM_ZONE}).  Otherwise, if the external array
6041 @code{tzname} is found, define @code{HAVE_TZNAME}; if it is declared,
6042 define @code{HAVE_DECL_TZNAME}.
6043 @end defmac
6045 @node Generic Structures
6046 @subsection Generic Structure Checks
6048 These macros are used to find structure members not covered by the
6049 ``particular'' test macros.
6051 @defmac AC_CHECK_MEMBER (@var{aggregate}.@var{member}, @
6052   @ovar{action-if-found}, @ovar{action-if-not-found}, @
6053   @dvar{includes, AC_INCLUDES_DEFAULT})
6054 @acindex{CHECK_MEMBER}
6055 Check whether @var{member} is a member of the aggregate @var{aggregate}.
6056 If no @var{includes} are specified, the default includes are used
6057 (@pxref{Default Includes}).
6059 @example
6060 AC_CHECK_MEMBER([struct passwd.pw_gecos], [],
6061                 [AC_MSG_ERROR([We need `passwd.pw_gecos'!])],
6062                 [[#include <pwd.h>]])
6063 @end example
6065 You can use this macro for submembers:
6067 @example
6068 AC_CHECK_MEMBER(struct top.middle.bot)
6069 @end example
6070 @end defmac
6072 @anchor{AC_CHECK_MEMBERS}
6073 @defmac AC_CHECK_MEMBERS (@var{members}, @ovar{action-if-found}, @
6074   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6075 @acindex{CHECK_MEMBERS}
6076 @cvindex HAVE_@var{aggregate}_@var{member}
6077 Check for the existence of each @samp{@var{aggregate}.@var{member}} of
6078 @var{members} using the previous macro.  When @var{member} belongs to
6079 @var{aggregate}, define @code{HAVE_@var{aggregate}_@var{member}} (in all
6080 capitals, with spaces and dots replaced by underscores).  If
6081 @var{action-if-found} is given, it is executed for each of the found
6082 members.  If @var{action-if-not-found} is given, it is executed for each
6083 of the members that could not be found.
6085 @var{includes} is a series of include directives, defaulting to
6086 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
6087 prior to the members under test.
6089 This macro uses M4 lists:
6090 @example
6091 AC_CHECK_MEMBERS([struct stat.st_rdev, struct stat.st_blksize])
6092 @end example
6093 @end defmac
6096 @node Types
6097 @section Types
6098 @cindex Types
6099 @cindex C types
6101 The following macros check for C types, either builtin or typedefs.  If
6102 there is no macro specifically defined to check for a type you need, and
6103 you don't need to check for any special properties of it, then you can
6104 use a general type-check macro.
6106 @menu
6107 * Particular Types::            Special handling to find certain types
6108 * Generic Types::               How to find other types
6109 @end menu
6111 @node Particular Types
6112 @subsection Particular Type Checks
6114 @hdrindex{sys/types.h}
6115 @hdrindex{stdlib.h}
6116 @hdrindex{stdint.h}
6117 @hdrindex{inttypes.h}
6118 These macros check for particular C types in @file{sys/types.h},
6119 @file{stdlib.h}, @file{stdint.h}, @file{inttypes.h} and others, if they
6120 exist.
6122 The Gnulib @code{stdint} module is an alternate way to define many of
6123 these symbols; it is useful if you prefer your code to assume a
6124 C99-or-better environment.  @xref{Gnulib}.
6126 @anchor{AC_TYPE_GETGROUPS}
6127 @defmac AC_TYPE_GETGROUPS
6128 @acindex{TYPE_GETGROUPS}
6129 @cvindex GETGROUPS_T
6130 Define @code{GETGROUPS_T} to be whichever of @code{gid_t} or @code{int}
6131 is the base type of the array argument to @code{getgroups}.
6132 @end defmac
6134 @defmac AC_TYPE_INT8_T
6135 @acindex{TYPE_INT8_T}
6136 @cvindex HAVE_INT8_T
6137 @cvindex int8_t
6138 If @file{stdint.h} or @file{inttypes.h} does not define the type
6139 @code{int8_t}, define @code{int8_t} to a signed
6140 integer type that is exactly 8 bits wide and that uses two's complement
6141 representation, if such a type exists.
6142 If you are worried about porting to hosts that lack such a type, you can
6143 use the results of this macro in C89-or-later code as follows:
6145 @example
6146 #if HAVE_STDINT_H
6147 # include <stdint.h>
6148 #endif
6149 #if defined INT8_MAX || defined int8_t
6150  @emph{code using int8_t}
6151 #else
6152  @emph{complicated alternative using >8-bit 'signed char'}
6153 #endif
6154 @end example
6155 @end defmac
6157 @defmac AC_TYPE_INT16_T
6158 @acindex{TYPE_INT16_T}
6159 @cvindex HAVE_INT16_T
6160 @cvindex int16_t
6161 This is like @code{AC_TYPE_INT8_T}, except for 16-bit integers.
6162 @end defmac
6164 @defmac AC_TYPE_INT32_T
6165 @acindex{TYPE_INT32_T}
6166 @cvindex HAVE_INT32_T
6167 @cvindex int32_t
6168 This is like @code{AC_TYPE_INT8_T}, except for 32-bit integers.
6169 @end defmac
6171 @defmac AC_TYPE_INT64_T
6172 @acindex{TYPE_INT64_T}
6173 @cvindex HAVE_INT64_T
6174 @cvindex int64_t
6175 This is like @code{AC_TYPE_INT8_T}, except for 64-bit integers.
6176 @end defmac
6178 @defmac AC_TYPE_INTMAX_T
6179 @acindex{TYPE_INTMAX_T}
6180 @cvindex HAVE_INTMAX_T
6181 @cvindex intmax_t
6182 If @file{stdint.h} or @file{inttypes.h} defines the type @code{intmax_t},
6183 define @code{HAVE_INTMAX_T}.  Otherwise, define @code{intmax_t} to the
6184 widest signed integer type.
6185 @end defmac
6187 @defmac AC_TYPE_INTPTR_T
6188 @acindex{TYPE_INTPTR_T}
6189 @cvindex HAVE_INTPTR_T
6190 @cvindex intptr_t
6191 If @file{stdint.h} or @file{inttypes.h} defines the type @code{intptr_t},
6192 define @code{HAVE_INTPTR_T}.  Otherwise, define @code{intptr_t} to a
6193 signed integer type wide enough to hold a pointer, if such a type
6194 exists.
6195 @end defmac
6197 @defmac AC_TYPE_LONG_DOUBLE
6198 @acindex{TYPE_LONG_DOUBLE}
6199 @cvindex HAVE_LONG_DOUBLE
6200 If the C compiler supports a working @code{long double} type, define
6201 @code{HAVE_LONG_DOUBLE}.  The @code{long double} type might have the
6202 same range and precision as @code{double}.
6204 This macro is obsolescent, as current C compilers support @code{long
6205 double}.  New programs need not use this macro.
6206 @end defmac
6208 @defmac AC_TYPE_LONG_DOUBLE_WIDER
6209 @acindex{TYPE_LONG_DOUBLE_WIDER}
6210 @cvindex HAVE_LONG_DOUBLE_WIDER
6211 If the C compiler supports a working @code{long double} type with more
6212 range or precision than the @code{double} type, define
6213 @code{HAVE_LONG_DOUBLE_WIDER}.
6214 @end defmac
6216 @defmac AC_TYPE_LONG_LONG_INT
6217 @acindex{TYPE_LONG_LONG_INT}
6218 @cvindex HAVE_LONG_LONG_INT
6219 If the C compiler supports a working @code{long long int} type, define
6220 @code{HAVE_LONG_LONG_INT}.  However, this test does not test
6221 @code{long long int} values in preprocessor @code{#if} expressions,
6222 because too many compilers mishandle such expressions.
6223 @xref{Preprocessor Arithmetic}.
6224 @end defmac
6226 @defmac AC_TYPE_MBSTATE_T
6227 @acindex{TYPE_MBSTATE_T}
6228 @cvindex mbstate_t
6229 @hdrindex{wchar.h}
6230 Define @code{HAVE_MBSTATE_T} if @code{<wchar.h>} declares the
6231 @code{mbstate_t} type.  Also, define @code{mbstate_t} to be a type if
6232 @code{<wchar.h>} does not declare it.
6233 @end defmac
6235 @anchor{AC_TYPE_MODE_T}
6236 @defmac AC_TYPE_MODE_T
6237 @acindex{TYPE_MODE_T}
6238 @cvindex mode_t
6239 Define @code{mode_t} to a suitable type, if standard headers do not
6240 define it.
6241 @end defmac
6243 @anchor{AC_TYPE_OFF_T}
6244 @defmac AC_TYPE_OFF_T
6245 @acindex{TYPE_OFF_T}
6246 @cvindex off_t
6247 Define @code{off_t} to a suitable type, if standard headers do not
6248 define it.
6249 @end defmac
6251 @anchor{AC_TYPE_PID_T}
6252 @defmac AC_TYPE_PID_T
6253 @acindex{TYPE_PID_T}
6254 @cvindex pid_t
6255 Define @code{pid_t} to a suitable type, if standard headers do not
6256 define it.
6257 @end defmac
6259 @anchor{AC_TYPE_SIZE_T}
6260 @defmac AC_TYPE_SIZE_T
6261 @acindex{TYPE_SIZE_T}
6262 @cvindex size_t
6263 Define @code{size_t} to a suitable type, if standard headers do not
6264 define it.
6265 @end defmac
6267 @defmac AC_TYPE_SSIZE_T
6268 @acindex{TYPE_SSIZE_T}
6269 @cvindex ssize_t
6270 Define @code{ssize_t} to a suitable type, if standard headers do not
6271 define it.
6272 @end defmac
6274 @anchor{AC_TYPE_UID_T}
6275 @defmac AC_TYPE_UID_T
6276 @acindex{TYPE_UID_T}
6277 @cvindex uid_t
6278 @cvindex gid_t
6279 Define @code{uid_t} and @code{gid_t} to suitable types, if standard
6280 headers do not define them.
6281 @end defmac
6283 @defmac AC_TYPE_UINT8_T
6284 @acindex{TYPE_UINT8_T}
6285 @cvindex HAVE_UINT8_T
6286 @cvindex uint8_t
6287 If @file{stdint.h} or @file{inttypes.h} does not define the type
6288 @code{uint8_t}, define @code{uint8_t} to an
6289 unsigned integer type that is exactly 8 bits wide, if such a type
6290 exists.
6291 This is like @code{AC_TYPE_INT8_T}, except for unsigned integers.
6292 @end defmac
6294 @defmac AC_TYPE_UINT16_T
6295 @acindex{TYPE_UINT16_T}
6296 @cvindex HAVE_UINT16_T
6297 @cvindex uint16_t
6298 This is like @code{AC_TYPE_UINT8_T}, except for 16-bit integers.
6299 @end defmac
6301 @defmac AC_TYPE_UINT32_T
6302 @acindex{TYPE_UINT32_T}
6303 @cvindex HAVE_UINT32_T
6304 @cvindex uint32_t
6305 This is like @code{AC_TYPE_UINT8_T}, except for 32-bit integers.
6306 @end defmac
6308 @defmac AC_TYPE_UINT64_T
6309 @acindex{TYPE_UINT64_T}
6310 @cvindex HAVE_UINT64_T
6311 @cvindex uint64_t
6312 This is like @code{AC_TYPE_UINT8_T}, except for 64-bit integers.
6313 @end defmac
6315 @defmac AC_TYPE_UINTMAX_T
6316 @acindex{TYPE_UINTMAX_T}
6317 @cvindex HAVE_UINTMAX_T
6318 @cvindex uintmax_t
6319 If @file{stdint.h} or @file{inttypes.h} defines the type @code{uintmax_t},
6320 define @code{HAVE_UINTMAX_T}.  Otherwise, define @code{uintmax_t} to the
6321 widest unsigned integer type.
6322 @end defmac
6324 @defmac AC_TYPE_UINTPTR_T
6325 @acindex{TYPE_UINTPTR_T}
6326 @cvindex HAVE_UINTPTR_T
6327 @cvindex uintptr_t
6328 If @file{stdint.h} or @file{inttypes.h} defines the type @code{uintptr_t},
6329 define @code{HAVE_UINTPTR_T}.  Otherwise, define @code{uintptr_t} to an
6330 unsigned integer type wide enough to hold a pointer, if such a type
6331 exists.
6332 @end defmac
6334 @defmac AC_TYPE_UNSIGNED_LONG_LONG_INT
6335 @acindex{TYPE_UNSIGNED_LONG_LONG_INT}
6336 @cvindex HAVE_UNSIGNED_LONG_LONG_INT
6337 If the C compiler supports a working @code{unsigned long long int} type,
6338 define @code{HAVE_UNSIGNED_LONG_LONG_INT}.  However, this test does not test
6339 @code{unsigned long long int} values in preprocessor @code{#if} expressions,
6340 because too many compilers mishandle such expressions.
6341 @xref{Preprocessor Arithmetic}.
6342 @end defmac
6344 @node Generic Types
6345 @subsection Generic Type Checks
6347 These macros are used to check for types not covered by the ``particular''
6348 test macros.
6350 @defmac AC_CHECK_TYPE (@var{type}, @ovar{action-if-found}, @
6351   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6352 @acindex{CHECK_TYPE}
6353 Check whether @var{type} is defined.  It may be a compiler builtin type
6354 or defined by the @var{includes}.  @var{includes} is a series of include
6355 directives, defaulting to @code{AC_INCLUDES_DEFAULT} (@pxref{Default
6356 Includes}), which are used prior to the type under test.
6358 In C, @var{type} must be a type-name, so that the expression @samp{sizeof
6359 (@var{type})} is valid (but @samp{sizeof ((@var{type}))} is not).  The
6360 same test is applied when compiling for C++, which means that in C++
6361 @var{type} should be a type-id and should not be an anonymous
6362 @samp{struct} or @samp{union}.
6363 @end defmac
6366 @defmac AC_CHECK_TYPES (@var{types}, @ovar{action-if-found}, @
6367   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6368 @acindex{CHECK_TYPES}
6369 @cvindex HAVE_@var{type}
6370 For each @var{type} of the @var{types} that is defined, define
6371 @code{HAVE_@var{type}} (in all capitals).  Each @var{type} must follow
6372 the rules of @code{AC_CHECK_TYPE}.  If no @var{includes} are
6373 specified, the default includes are used (@pxref{Default Includes}).  If
6374 @var{action-if-found} is given, it is additional shell code to execute
6375 when one of the types is found.  If @var{action-if-not-found} is given,
6376 it is executed when one of the types is not found.
6378 This macro uses M4 lists:
6379 @example
6380 AC_CHECK_TYPES([ptrdiff_t])
6381 AC_CHECK_TYPES([unsigned long long int, uintmax_t])
6382 AC_CHECK_TYPES([float_t], [], [], [[#include <math.h>]])
6383 @end example
6385 @end defmac
6387 Autoconf, up to 2.13, used to provide to another version of
6388 @code{AC_CHECK_TYPE}, broken by design.  In order to keep backward
6389 compatibility, a simple heuristic, quite safe but not totally, is
6390 implemented.  In case of doubt, read the documentation of the former
6391 @code{AC_CHECK_TYPE}, see @ref{Obsolete Macros}.
6394 @node Compilers and Preprocessors
6395 @section Compilers and Preprocessors
6396 @cindex Compilers
6397 @cindex Preprocessors
6399 @ovindex EXEEXT
6400 All the tests for compilers (@code{AC_PROG_CC}, @code{AC_PROG_CXX},
6401 @code{AC_PROG_F77}) define the output variable @code{EXEEXT} based on
6402 the output of the compiler, typically to the empty string if
6403 Posix and @samp{.exe} if a @acronym{DOS} variant.
6405 @ovindex OBJEXT
6406 They also define the output variable @code{OBJEXT} based on the
6407 output of the compiler, after @file{.c} files have been excluded, typically
6408 to @samp{o} if Posix, @samp{obj} if a @acronym{DOS} variant.
6410 If the compiler being used does not produce executables, the tests fail.  If
6411 the executables can't be run, and cross-compilation is not enabled, they
6412 fail too.  @xref{Manual Configuration}, for more on support for cross
6413 compiling.
6415 @menu
6416 * Specific Compiler Characteristics::  Some portability issues
6417 * Generic Compiler Characteristics::  Language independent tests and features
6418 * C Compiler::                  Checking its characteristics
6419 * C++ Compiler::                Likewise
6420 * Objective C Compiler::        Likewise
6421 * Erlang Compiler and Interpreter::  Likewise
6422 * Fortran Compiler::            Likewise
6423 @end menu
6425 @node Specific Compiler Characteristics
6426 @subsection Specific Compiler Characteristics
6428 Some compilers exhibit different behaviors.
6430 @table @asis
6431 @item Static/Dynamic Expressions
6432 Autoconf relies on a trick to extract one bit of information from the C
6433 compiler: using negative array sizes.  For instance the following
6434 excerpt of a C source demonstrates how to test whether @samp{int} objects are 4
6435 bytes wide:
6437 @example
6438 static int test_array[sizeof (int) == 4 ? 1 : -1];
6439 @end example
6441 @noindent
6442 To our knowledge, there is a single compiler that does not support this
6443 trick: the @acronym{HP} C compilers (the real ones, not only the
6444 ``bundled'') on @acronym{HP-UX} 11.00.
6445 They incorrectly reject the above program with the diagnostic
6446 ``Variable-length arrays cannot have static storage.''
6447 This bug comes from @acronym{HP} compilers' mishandling of @code{sizeof (int)},
6448 not from the @code{? 1 : -1}, and
6449 Autoconf works around this problem by casting @code{sizeof (int)} to
6450 @code{long int} before comparing it.
6451 @end table
6453 @node Generic Compiler Characteristics
6454 @subsection Generic Compiler Characteristics
6456 @anchor{AC_CHECK_SIZEOF}
6457 @defmac AC_CHECK_SIZEOF (@var{type-or-expr}, @ovar{unused}, @
6458   @dvar{includes, AC_INCLUDES_DEFAULT})
6459 @acindex{CHECK_SIZEOF}
6460 @cvindex SIZEOF_@var{type-or-expr}
6461 Define @code{SIZEOF_@var{type-or-expr}} (@pxref{Standard Symbols}) to be
6462 the size in bytes of @var{type-or-expr}, which may be either a type or
6463 an expression returning a value that has a size.  If the expression
6464 @samp{sizeof (@var{type-or-expr})} is invalid, the result is 0.
6465 @var{includes} is a series of include directives, defaulting to
6466 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
6467 prior to the expression under test.
6469 This macro now works even when cross-compiling.  The @var{unused}
6470 argument was used when cross-compiling.
6472 For example, the call
6474 @example
6475 AC_CHECK_SIZEOF([int *])
6476 @end example
6478 @noindent
6479 defines @code{SIZEOF_INT_P} to be 8 on DEC Alpha AXP systems.
6480 @end defmac
6482 @defmac AC_CHECK_ALIGNOF (@var{type}, @dvar{includes, AC_INCLUDES_DEFAULT})
6483 @acindex{CHECK_ALIGNOF}
6484 @cvindex ALIGNOF_@var{type}
6485 Define @code{ALIGNOF_@var{type}} (@pxref{Standard Symbols}) to be the
6486 alignment in bytes of @var{type}.  @samp{@var{type} y;} must be valid as
6487 a structure member declaration.  If @samp{type} is unknown, the result
6488 is 0.  If no @var{includes} are specified, the default includes are used
6489 (@pxref{Default Includes}).
6490 @end defmac
6492 @defmac AC_COMPUTE_INT (@var{var}, @var{expression}, @
6493   @dvar{includes, AC_INCLUDES_DEFAULT}, @ovar{action-if-fails})
6494 @acindex{COMPUTE_INT}
6495 Store into the shell variable @var{var} the value of the integer
6496 @var{expression}.  The
6497 value should fit in an initializer in a C variable of type @code{signed
6498 long}.  To support cross compilation (in which case, the macro only works on
6499 hosts that use twos-complement arithmetic), it should be possible to evaluate
6500 the expression at compile-time.  If no @var{includes} are specified, the
6501 default includes are used (@pxref{Default Includes}).
6503 Execute @var{action-if-fails} if the value cannot be determined correctly.
6504 @end defmac
6506 @defmac AC_LANG_WERROR
6507 @acindex{LANG_WERROR}
6508 Normally Autoconf ignores warnings generated by the compiler, linker, and
6509 preprocessor.  If this macro is used, warnings count as fatal
6510 errors for the current language.  This macro is useful when the
6511 results of configuration are used where warnings are unacceptable; for
6512 instance, if parts of a program are built with the @acronym{GCC}
6513 @option{-Werror}
6514 option.  If the whole program is built using @option{-Werror} it is
6515 often simpler to put @option{-Werror} in the compiler flags (@code{CFLAGS},
6516 etc.).
6517 @end defmac
6519 @defmac AC_OPENMP
6520 @acindex{OPENMP}
6521 @cvindex _OPENMP
6522 @ovindex OPENMP_CFLAGS
6523 @ovindex OPENMP_CXXFLAGS
6524 @ovindex OPENMP_FFLAGS
6525 @ovindex OPENMP_FCFLAGS
6526 OpenMP (@url{http://www.openmp.org/}) specifies extensions of C, C++,
6527 and Fortran that simplify optimization of shared memory parallelism,
6528 which is a common problem on multicore CPUs.
6530 If the current language is C, the macro @code{AC_OPENMP} sets the
6531 variable @code{OPENMP_CFLAGS} to the C compiler flags needed for
6532 supporting OpenMP@.  @code{OPENMP_CFLAGS} is set to empty if the
6533 compiler already supports OpenMP, if it has no way to activate OpenMP
6534 support, or if the user rejects OpenMP support by invoking
6535 @samp{configure} with the @samp{--disable-openmp} option.
6537 @code{OPENMP_CFLAGS} needs to be used when compiling programs, when
6538 preprocessing program source, and when linking programs.  Therefore you
6539 need to add @code{$(OPENMP_CFLAGS)} to the @code{CFLAGS} of C programs
6540 that use OpenMP@.  If you preprocess OpenMP-specific C code, you also
6541 need to add @code{$(OPENMP_CFLAGS)} to @code{CPPFLAGS}.  The presence of
6542 OpenMP support is revealed at compile time by the preprocessor macro
6543 @code{_OPENMP}.
6545 Linking a program with @code{OPENMP_CFLAGS} typically adds one more
6546 shared library to the program's dependencies, so its use is recommended
6547 only on programs that actually require OpenMP.
6549 If the current language is C++, @code{AC_OPENMP} sets the variable
6550 @code{OPENMP_CXXFLAGS}, suitably for the C++ compiler.  The same remarks
6551 hold as for C.
6553 If the current language is Fortran 77 or Fortran, @code{AC_OPENMP} sets
6554 the variable @code{OPENMP_FFLAGS} or @code{OPENMP_FCFLAGS},
6555 respectively.  Similar remarks as for C hold, except that
6556 @code{CPPFLAGS} is not used for Fortran, and no preprocessor macro
6557 signals OpenMP support.
6558 @end defmac
6560 @node C Compiler
6561 @subsection C Compiler Characteristics
6563 The following macros provide ways to find and exercise a C Compiler.
6564 There are a few constructs that ought to be avoided, but do not deserve
6565 being checked for, since they can easily be worked around.
6567 @table @asis
6568 @item Don't use lines containing solitary backslashes
6569 They tickle a bug in the @acronym{HP-UX} C compiler (checked on
6570 @acronym{HP-UX} 10.20,
6571 11.00, and 11i).  When given the following source:
6573 @example
6574 #ifdef __STDC__
6576 * A comment with backslash-newlines in it.  %@{ %@} *\
6579 char str[] = "\\
6580 " A string with backslash-newlines in it %@{ %@} \\
6582 char apostrophe = '\\
6586 #endif
6587 @end example
6589 @noindent
6590 the compiler incorrectly fails with the diagnostics ``Non-terminating
6591 comment at end of file'' and ``Missing @samp{#endif} at end of file.''
6592 Removing the lines with solitary backslashes solves the problem.
6594 @item Don't compile several files at once if output matters to you
6595 Some compilers, such as @acronym{HP}'s, report names of files being
6596 compiled when given more than one file operand.  For instance:
6598 @example
6599 $ @kbd{cc a.c b.c}
6600 a.c:
6601 b.c:
6602 @end example
6604 @noindent
6605 This can cause problems if you observe the output of the compiler to
6606 detect failures.  Invoking @samp{cc -c a.c && cc -c b.c && cc -o c a.o
6607 b.o} solves the issue.
6609 @item Don't rely on @code{#error} failing
6610 The @sc{irix} C compiler does not fail when #error is preprocessed; it
6611 simply emits a diagnostic and continues, exiting successfully.  So,
6612 instead of an error directive like @code{#error "Unsupported word size"}
6613 it is more portable to use an invalid directive like @code{#Unsupported
6614 word size} in Autoconf tests.  In ordinary source code, @code{#error} is
6615 OK, since installers with inadequate compilers like @sc{irix} can simply
6616 examine these compilers' diagnostic output.
6618 @item Don't rely on correct @code{#line} support
6619 On Solaris, @command{c89} (at least Sun C 5.3 through 5.8)
6620 diagnoses @code{#line} directives whose line
6621 numbers are greater than 32767.  Nothing in Posix
6622 makes this invalid.  That is why Autoconf stopped issuing
6623 @code{#line} directives.
6624 @end table
6626 @defmac AC_PROG_CC (@ovar{compiler-search-list})
6627 @acindex{PROG_CC}
6628 @ovindex CC
6629 @ovindex CFLAGS
6630 Determine a C compiler to use.  If @code{CC} is not already set in the
6631 environment, check for @code{gcc} and @code{cc}, then for other C
6632 compilers.  Set output variable @code{CC} to the name of the compiler
6633 found.
6635 This macro may, however, be invoked with an optional first argument
6636 which, if specified, must be a blank-separated list of C compilers to
6637 search for.  This just gives the user an opportunity to specify an
6638 alternative search list for the C compiler.  For example, if you didn't
6639 like the default order, then you could invoke @code{AC_PROG_CC} like
6640 this:
6642 @example
6643 AC_PROG_CC([gcc cl cc])
6644 @end example
6646 If the C compiler does not handle function prototypes correctly by
6647 default, try to add an option to output variable @code{CC} to make it
6648 so.  This macro tries various options that select standard-conformance
6649 modes on various systems.
6651 After calling this macro you can check whether the C compiler has been
6652 set to accept @acronym{ANSI} C89 (@acronym{ISO} C90); if not, the shell
6653 variable
6654 @code{ac_cv_prog_cc_c89} is set to @samp{no}.  See also
6655 @code{AC_C_PROTOTYPES} below.
6657 If using the @acronym{GNU} C compiler, set shell variable @code{GCC} to
6658 @samp{yes}.  If output variable @code{CFLAGS} was not already set, set
6659 it to @option{-g -O2} for the @acronym{GNU} C compiler (@option{-O2} on systems
6660 where @acronym{GCC} does not accept @option{-g}), or @option{-g} for
6661 other compilers.
6662 @end defmac
6664 @anchor{AC_PROG_CC_C_O}
6665 @defmac AC_PROG_CC_C_O
6666 @acindex{PROG_CC_C_O}
6667 @cvindex NO_MINUS_C_MINUS_O
6668 If the C compiler does not accept the @option{-c} and @option{-o} options
6669 simultaneously, define @code{NO_MINUS_C_MINUS_O}.  This macro actually
6670 tests both the compiler found by @code{AC_PROG_CC}, and, if different,
6671 the first @code{cc} in the path.  The test fails if one fails.  This
6672 macro was created for @acronym{GNU} Make to choose the default C compilation
6673 rule.
6674 @end defmac
6677 @defmac AC_PROG_CPP
6678 @acindex{PROG_CPP}
6679 @ovindex CPP
6680 Set output variable @code{CPP} to a command that runs the
6681 C preprocessor.  If @samp{$CC -E} doesn't work, @file{/lib/cpp} is used.
6682 It is only portable to run @code{CPP} on files with a @file{.c}
6683 extension.
6685 Some preprocessors don't indicate missing include files by the error
6686 status.  For such preprocessors an internal variable is set that causes
6687 other macros to check the standard error from the preprocessor and
6688 consider the test failed if any warnings have been reported.
6689 For most preprocessors, though, warnings do not cause include-file
6690 tests to fail unless @code{AC_PROG_CPP_WERROR} is also specified.
6691 @end defmac
6693 @defmac AC_PROG_CPP_WERROR
6694 @acindex{PROG_CPP_WERROR}
6695 @ovindex CPP
6696 This acts like @code{AC_PROG_CPP}, except it treats warnings from the
6697 preprocessor as errors even if the preprocessor exit status indicates
6698 success.  This is useful for avoiding headers that generate mandatory
6699 warnings, such as deprecation notices.
6700 @end defmac
6703 The following macros check for C compiler or machine architecture
6704 features.  To check for characteristics not listed here, use
6705 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}) or
6706 @code{AC_RUN_IFELSE} (@pxref{Runtime}).
6708 @defmac AC_PROG_CC_STDC
6709 @acindex{PROG_CC_STDC}
6710 If the C compiler cannot compile @acronym{ISO} Standard C (currently
6711 C99), try to add an option to output variable @code{CC} to make it work.
6712 If the compiler does not support C99, fall back to supporting
6713 @acronym{ANSI} C89 (@acronym{ISO} C90).
6715 After calling this macro you can check whether the C compiler has been
6716 set to accept Standard C; if not, the shell variable
6717 @code{ac_cv_prog_cc_stdc} is set to @samp{no}.
6718 @end defmac
6720 @defmac AC_PROG_CC_C89
6721 @acindex{PROG_CC_C89}
6722 If the C compiler is not in @acronym{ANSI} C89 (@acronym{ISO} C90) mode by
6723 default, try to add an option to output variable @code{CC} to make it
6724 so.  This macro tries various options that select @acronym{ANSI} C89 on
6725 some system or another.  It considers the compiler to be in
6726 @acronym{ANSI} C89 mode if it handles function prototypes correctly.
6728 After calling this macro you can check whether the C compiler has been
6729 set to accept @acronym{ANSI} C89; if not, the shell variable
6730 @code{ac_cv_prog_cc_c89} is set to @samp{no}.
6732 This macro is called automatically by @code{AC_PROG_CC}.
6733 @end defmac
6735 @defmac AC_PROG_CC_C99
6736 @acindex{PROG_CC_C99}
6737 If the C compiler is not in C99 mode by default, try to add an
6738 option to output variable @code{CC} to make it so.  This macro tries
6739 various options that select C99 on some system or another.  It
6740 considers the compiler to be in C99 mode if it handles @code{_Bool},
6741 @code{//} comments, flexible array members, @code{inline}, signed and
6742 unsigned @code{long long int}, mixed code and declarations, named
6743 initialization of structs,
6744 @code{restrict}, @code{va_copy}, varargs macros, variable declarations
6745 in @code{for} loops, and variable length arrays.
6747 After calling this macro you can check whether the C compiler has been
6748 set to accept C99; if not, the shell variable
6749 @code{ac_cv_prog_cc_c99} is set to @samp{no}.
6750 @end defmac
6752 @defmac AC_C_BACKSLASH_A
6753 @acindex{C_BACKSLASH_A}
6754 @cvindex HAVE_C_BACKSLASH_A
6755 Define @samp{HAVE_C_BACKSLASH_A} to 1 if the C compiler understands
6756 @samp{\a}.
6758 This macro is obsolescent, as current C compilers understand @samp{\a}.
6759 New programs need not use this macro.
6760 @end defmac
6762 @anchor{AC_C_BIGENDIAN}
6763 @defmac AC_C_BIGENDIAN (@ovar{action-if-true}, @ovar{action-if-false}, @
6764   @ovar{action-if-unknown}, @ovar{action-if-universal})
6765 @acindex{C_BIGENDIAN}
6766 @cvindex WORDS_BIGENDIAN
6767 @cindex Endianness
6768 If words are stored with the most significant byte first (like Motorola
6769 and SPARC CPUs), execute @var{action-if-true}.  If words are stored with
6770 the least significant byte first (like Intel and VAX CPUs), execute
6771 @var{action-if-false}.
6773 This macro runs a test-case if endianness cannot be determined from the
6774 system header files.  When cross-compiling, the test-case is not run but
6775 grep'ed for some magic values.  @var{action-if-unknown} is executed if
6776 the latter case fails to determine the byte sex of the host system.
6778 In some cases a single run of a compiler can generate code for multiple
6779 architectures.  This can happen, for example, when generating Mac OS X
6780 universal binary files, which work on both PowerPC and Intel
6781 architectures.  In this case, the different variants might be for
6782 different architectures whose endiannesses differ.  If
6783 @command{configure} detects this, it executes @var{action-if-universal}
6784 instead of @var{action-if-unknown}.
6786 The default for @var{action-if-true} is to define
6787 @samp{WORDS_BIGENDIAN}.  The default for @var{action-if-false} is to do
6788 nothing.  The default for @var{action-if-unknown} is to
6789 abort configure and tell the installer how to bypass this test.
6790 And finally, the default for @var{action-if-universal} is to define
6791 @samp{WORDS_BIGENDIAN} or not, depending on the architecture that the
6792 code is being generated for.
6794 If you use this macro without specifying @var{action-if-universal}, you
6795 should also use @code{AC_CONFIG_HEADERS}; otherwise
6796 @samp{WORDS_BIGENDIAN} may be set incorrectly for Mac OS X universal
6797 binary files.
6798 @end defmac
6800 @anchor{AC_C_CONST}
6801 @defmac AC_C_CONST
6802 @acindex{C_CONST}
6803 @cvindex const
6804 If the C compiler does not fully support the @code{const} keyword,
6805 define @code{const} to be empty.  Some C compilers that do
6806 not define @code{__STDC__} do support @code{const}; some compilers that
6807 define @code{__STDC__} do not completely support @code{const}.  Programs
6808 can simply use @code{const} as if every C compiler supported it; for
6809 those that don't, the makefile or configuration header file
6810 defines it as empty.
6812 Occasionally installers use a C++ compiler to compile C code, typically
6813 because they lack a C compiler.  This causes problems with @code{const},
6814 because C and C++ treat @code{const} differently.  For example:
6816 @example
6817 const int foo;
6818 @end example
6820 @noindent
6821 is valid in C but not in C++.  These differences unfortunately cannot be
6822 papered over by defining @code{const} to be empty.
6824 If @command{autoconf} detects this situation, it leaves @code{const} alone,
6825 as this generally yields better results in practice.  However, using a
6826 C++ compiler to compile C code is not recommended or supported, and
6827 installers who run into trouble in this area should get a C compiler
6828 like @acronym{GCC} to compile their C code.
6830 This macro is obsolescent, as current C compilers support @code{const}.
6831 New programs need not use this macro.
6832 @end defmac
6834 @defmac AC_C_RESTRICT
6835 @acindex{C_RESTRICT}
6836 @cvindex restrict
6837 If the C compiler recognizes a variant spelling for the @code{restrict}
6838 keyword (@code{__restrict}, @code{__restrict__}, or @code{_Restrict}),
6839 then define @code{restrict} to that; this is more likely to do the right
6840 thing with compilers that support language variants where plain
6841 @code{restrict} is not a keyword.  Otherwise, if the C compiler
6842 recognizes the @code{restrict} keyword, don't do anything.
6843 Otherwise, define @code{restrict} to be empty.
6844 Thus, programs may simply use @code{restrict} as if every C compiler
6845 supported it; for those that do not, the makefile
6846 or configuration header defines it away.
6848 Although support in C++ for the @code{restrict} keyword is not
6849 required, several C++ compilers do accept the keyword.
6850 This macro works for them, too.
6851 @end defmac
6853 @defmac AC_C_VOLATILE
6854 @acindex{C_VOLATILE}
6855 @cvindex volatile
6856 If the C compiler does not understand the keyword @code{volatile},
6857 define @code{volatile} to be empty.  Programs can simply use
6858 @code{volatile} as if every C compiler supported it; for those that do
6859 not, the makefile or configuration header defines it as
6860 empty.
6862 If the correctness of your program depends on the semantics of
6863 @code{volatile}, simply defining it to be empty does, in a sense, break
6864 your code.  However, given that the compiler does not support
6865 @code{volatile}, you are at its mercy anyway.  At least your
6866 program compiles, when it wouldn't before.
6867 @xref{Volatile Objects}, for more about @code{volatile}.
6869 In general, the @code{volatile} keyword is a standard C feature, so
6870 you might expect that @code{volatile} is available only when
6871 @code{__STDC__} is defined.  However, Ultrix 4.3's native compiler does
6872 support volatile, but does not define @code{__STDC__}.
6874 This macro is obsolescent, as current C compilers support @code{volatile}.
6875 New programs need not use this macro.
6876 @end defmac
6878 @anchor{AC_C_INLINE}
6879 @defmac AC_C_INLINE
6880 @acindex{C_INLINE}
6881 @cvindex inline
6882 If the C compiler supports the keyword @code{inline}, do nothing.
6883 Otherwise define @code{inline} to @code{__inline__} or @code{__inline}
6884 if it accepts one of those, otherwise define @code{inline} to be empty.
6885 @end defmac
6887 @anchor{AC_C_CHAR_UNSIGNED}
6888 @defmac AC_C_CHAR_UNSIGNED
6889 @acindex{C_CHAR_UNSIGNED}
6890 @cvindex __CHAR_UNSIGNED__
6891 If the C type @code{char} is unsigned, define @code{__CHAR_UNSIGNED__},
6892 unless the C compiler predefines it.
6894 These days, using this macro is not necessary.  The same information can
6895 be determined by this portable alternative, thus avoiding the use of
6896 preprocessor macros in the namespace reserved for the implementation.
6898 @example
6899 #include <limits.h>
6900 #if CHAR_MIN == 0
6901 # define CHAR_UNSIGNED 1
6902 #endif
6903 @end example
6904 @end defmac
6906 @defmac AC_C_STRINGIZE
6907 @acindex{C_STRINGIZE}
6908 @cvindex HAVE_STRINGIZE
6909 If the C preprocessor supports the stringizing operator, define
6910 @code{HAVE_STRINGIZE}.  The stringizing operator is @samp{#} and is
6911 found in macros such as this:
6913 @example
6914 #define x(y) #y
6915 @end example
6917 This macro is obsolescent, as current C compilers support the
6918 stringizing operator.  New programs need not use this macro.
6919 @end defmac
6921 @defmac AC_C_FLEXIBLE_ARRAY_MEMBER
6922 @acindex{C_FLEXIBLE_ARRAY_MEMBER}
6923 @cvindex FLEXIBLE_ARRAY_MEMBER
6924 If the C compiler supports flexible array members, define
6925 @code{FLEXIBLE_ARRAY_MEMBER} to nothing; otherwise define it to 1.
6926 That way, a declaration like this:
6928 @example
6929 struct s
6930   @{
6931     size_t n_vals;
6932     double val[FLEXIBLE_ARRAY_MEMBER];
6933   @};
6934 @end example
6936 @noindent
6937 will let applications use the ``struct hack'' even with compilers that
6938 do not support flexible array members.  To allocate and use such an
6939 object, you can use code like this:
6941 @example
6942 size_t i;
6943 size_t n = compute_value_count ();
6944 struct s *p =
6945    malloc (offsetof (struct s, val)
6946            + n * sizeof (double));
6947 p->n_vals = n;
6948 for (i = 0; i < n; i++)
6949   p->val[i] = compute_value (i);
6950 @end example
6951 @end defmac
6953 @defmac AC_C_VARARRAYS
6954 @acindex{C_VARARRAYS}
6955 @cvindex HAVE_C_VARARRAYS
6956 If the C compiler supports variable-length arrays, define
6957 @code{HAVE_C_VARARRAYS}.  A variable-length array is an array of automatic
6958 storage duration whose length is determined at run time, when the array
6959 is declared.
6960 @end defmac
6962 @defmac AC_C_TYPEOF
6963 @acindex{C_TYPEOF}
6964 @cvindex HAVE_TYPEOF
6965 @cvindex typeof
6966 If the C compiler supports @acronym{GCC}'s @code{typeof} syntax either
6967 directly or
6968 through a different spelling of the keyword (e.g., @code{__typeof__}),
6969 define @code{HAVE_TYPEOF}.  If the support is available only through a
6970 different spelling, define @code{typeof} to that spelling.
6971 @end defmac
6973 @defmac AC_C_PROTOTYPES
6974 @acindex{C_PROTOTYPES}
6975 @cvindex PROTOTYPES
6976 @cvindex __PROTOTYPES
6977 @cvindex PARAMS
6978 If function prototypes are understood by the compiler (as determined by
6979 @code{AC_PROG_CC}), define @code{PROTOTYPES} and @code{__PROTOTYPES}.
6980 Defining @code{__PROTOTYPES} is for the benefit of
6981 header files that cannot use macros that infringe on user name space.
6983 This macro is obsolescent, as current C compilers support prototypes.
6984 New programs need not use this macro.
6985 @end defmac
6987 @anchor{AC_PROG_GCC_TRADITIONAL}
6988 @defmac AC_PROG_GCC_TRADITIONAL
6989 @acindex{PROG_GCC_TRADITIONAL}
6990 @ovindex CC
6991 Add @option{-traditional} to output variable @code{CC} if using the
6992 @acronym{GNU} C compiler and @code{ioctl} does not work properly without
6993 @option{-traditional}.  That usually happens when the fixed header files
6994 have not been installed on an old system.
6996 This macro is obsolescent, since current versions of the @acronym{GNU} C
6997 compiler fix the header files automatically when installed.
6998 @end defmac
7001 @node C++ Compiler
7002 @subsection C++ Compiler Characteristics
7005 @defmac AC_PROG_CXX (@ovar{compiler-search-list})
7006 @acindex{PROG_CXX}
7007 @ovindex CXX
7008 @ovindex CXXFLAGS
7009 Determine a C++ compiler to use.  Check whether the environment variable
7010 @code{CXX} or @code{CCC} (in that order) is set; if so, then set output
7011 variable @code{CXX} to its value.
7013 Otherwise, if the macro is invoked without an argument, then search for
7014 a C++ compiler under the likely names (first @code{g++} and @code{c++}
7015 then other names).  If none of those checks succeed, then as a last
7016 resort set @code{CXX} to @code{g++}.
7018 This macro may, however, be invoked with an optional first argument
7019 which, if specified, must be a blank-separated list of C++ compilers to
7020 search for.  This just gives the user an opportunity to specify an
7021 alternative search list for the C++ compiler.  For example, if you
7022 didn't like the default order, then you could invoke @code{AC_PROG_CXX}
7023 like this:
7025 @example
7026 AC_PROG_CXX([gcc cl KCC CC cxx cc++ xlC aCC c++ g++])
7027 @end example
7029 If using the @acronym{GNU} C++ compiler, set shell variable @code{GXX} to
7030 @samp{yes}.  If output variable @code{CXXFLAGS} was not already set, set
7031 it to @option{-g -O2} for the @acronym{GNU} C++ compiler (@option{-O2} on
7032 systems where G++ does not accept @option{-g}), or @option{-g} for other
7033 compilers.
7034 @end defmac
7036 @defmac AC_PROG_CXXCPP
7037 @acindex{PROG_CXXCPP}
7038 @ovindex CXXCPP
7039 Set output variable @code{CXXCPP} to a command that runs the C++
7040 preprocessor.  If @samp{$CXX -E} doesn't work, @file{/lib/cpp} is used.
7041 It is portable to run @code{CXXCPP} only on files with a @file{.c},
7042 @file{.C}, @file{.cc}, or @file{.cpp} extension.
7044 Some preprocessors don't indicate missing include files by the error
7045 status.  For such preprocessors an internal variable is set that causes
7046 other macros to check the standard error from the preprocessor and
7047 consider the test failed if any warnings have been reported.  However,
7048 it is not known whether such broken preprocessors exist for C++.
7049 @end defmac
7051 @defmac AC_PROG_CXX_C_O
7052 @acindex{PROG_CXX_C_O}
7053 @cvindex CXX_NO_MINUS_C_MINUS_O
7054 Test whether the C++ compiler accepts the options @option{-c} and
7055 @option{-o} simultaneously, and define @code{CXX_NO_MINUS_C_MINUS_O},
7056 if it does not.
7057 @end defmac
7060 @node Objective C Compiler
7061 @subsection Objective C Compiler Characteristics
7064 @defmac AC_PROG_OBJC (@ovar{compiler-search-list})
7065 @acindex{PROG_OBJC}
7066 @ovindex OBJC
7067 @ovindex OBJCFLAGS
7068 Determine an Objective C compiler to use.  If @code{OBJC} is not already
7069 set in the environment, check for Objective C compilers.  Set output
7070 variable @code{OBJC} to the name of the compiler found.
7072 This macro may, however, be invoked with an optional first argument
7073 which, if specified, must be a blank-separated list of Objective C compilers to
7074 search for.  This just gives the user an opportunity to specify an
7075 alternative search list for the Objective C compiler.  For example, if you
7076 didn't like the default order, then you could invoke @code{AC_PROG_OBJC}
7077 like this:
7079 @example
7080 AC_PROG_OBJC([gcc objcc objc])
7081 @end example
7083 If using the @acronym{GNU} Objective C compiler, set shell variable
7084 @code{GOBJC} to @samp{yes}.  If output variable @code{OBJCFLAGS} was not
7085 already set, set it to @option{-g -O2} for the @acronym{GNU} Objective C
7086 compiler (@option{-O2} on systems where @command{gcc} does not accept
7087 @option{-g}), or @option{-g} for other compilers.
7088 @end defmac
7090 @defmac AC_PROG_OBJCPP
7091 @acindex{PROG_OBJCPP}
7092 @ovindex OBJCPP
7093 Set output variable @code{OBJCPP} to a command that runs the Objective C
7094 preprocessor.  If @samp{$OBJC -E} doesn't work, @file{/lib/cpp} is used.
7095 @end defmac
7098 @node Erlang Compiler and Interpreter
7099 @subsection Erlang Compiler and Interpreter Characteristics
7100 @cindex Erlang
7102 Autoconf defines the following macros for determining paths to the essential
7103 Erlang/OTP programs:
7105 @defmac AC_ERLANG_PATH_ERLC (@ovar{value-if-not-found}, @dvar{path, $PATH})
7106 @acindex{ERLANG_PATH_ERLC}
7107 @ovindex ERLC
7108 @ovindex ERLCFLAGS
7109 Determine an Erlang compiler to use.  If @code{ERLC} is not already set in the
7110 environment, check for @command{erlc}.  Set output variable @code{ERLC} to the
7111 complete path of the compiler command found.  In addition, if @code{ERLCFLAGS}
7112 is not set in the environment, set it to an empty value.
7114 The two optional arguments have the same meaning as the two last arguments of
7115 macro @code{AC_PROG_PATH} for looking for the @command{erlc} program.  For
7116 example, to look for @command{erlc} only in the @file{/usr/lib/erlang/bin}
7117 directory:
7119 @example
7120 AC_ERLANG_PATH_ERLC([not found], [/usr/lib/erlang/bin])
7121 @end example
7122 @end defmac
7124 @defmac AC_ERLANG_NEED_ERLC (@dvar{path, $PATH})
7125 @acindex{ERLANG_NEED_ERLC}
7126 A simplified variant of the @code{AC_ERLANG_PATH_ERLC} macro, that prints an
7127 error message and exits the @command{configure} script if the @command{erlc}
7128 program is not found.
7129 @end defmac
7131 @defmac AC_ERLANG_PATH_ERL (@ovar{value-if-not-found}, @dvar{path, $PATH})
7132 @acindex{ERLANG_PATH_ERL}
7133 @ovindex ERL
7134 Determine an Erlang interpreter to use.  If @code{ERL} is not already
7135 set in the
7136 environment, check for @command{erl}.  Set output variable @code{ERL} to the
7137 complete path of the interpreter command found.
7139 The two optional arguments have the same meaning as the two last arguments of
7140 macro @code{AC_PROG_PATH} for looking for the @command{erl} program.  For
7141 example, to look for @command{erl} only in the @file{/usr/lib/erlang/bin}
7142 directory:
7144 @example
7145 AC_ERLANG_PATH_ERL([not found], [/usr/lib/erlang/bin])
7146 @end example
7147 @end defmac
7149 @defmac AC_ERLANG_NEED_ERL (@dvar{path, $PATH})
7150 @acindex{ERLANG_NEED_ERL}
7151 A simplified variant of the @code{AC_ERLANG_PATH_ERL} macro, that prints an
7152 error message and exits the @command{configure} script if the @command{erl}
7153 program is not found.
7154 @end defmac
7157 @node Fortran Compiler
7158 @subsection Fortran Compiler Characteristics
7159 @cindex Fortran
7160 @cindex F77
7162 The Autoconf Fortran support is divided into two categories: legacy
7163 Fortran 77 macros (@code{F77}), and modern Fortran macros (@code{FC}).
7164 The former are intended for traditional Fortran 77 code, and have output
7165 variables like @code{F77}, @code{FFLAGS}, and @code{FLIBS}.  The latter
7166 are for newer programs that can (or must) compile under the newer
7167 Fortran standards, and have output variables like @code{FC},
7168 @code{FCFLAGS}, and @code{FCLIBS}.
7170 Except for two new macros @code{AC_FC_SRCEXT} and
7171 @code{AC_FC_FREEFORM} (see below), the @code{FC} and @code{F77} macros
7172 behave almost identically, and so they are documented together in this
7173 section.
7176 @defmac AC_PROG_F77 (@ovar{compiler-search-list})
7177 @acindex{PROG_F77}
7178 @ovindex F77
7179 @ovindex FFLAGS
7180 Determine a Fortran 77 compiler to use.  If @code{F77} is not already
7181 set in the environment, then check for @code{g77} and @code{f77}, and
7182 then some other names.  Set the output variable @code{F77} to the name
7183 of the compiler found.
7185 This macro may, however, be invoked with an optional first argument
7186 which, if specified, must be a blank-separated list of Fortran 77
7187 compilers to search for.  This just gives the user an opportunity to
7188 specify an alternative search list for the Fortran 77 compiler.  For
7189 example, if you didn't like the default order, then you could invoke
7190 @code{AC_PROG_F77} like this:
7192 @example
7193 AC_PROG_F77([fl32 f77 fort77 xlf g77 f90 xlf90])
7194 @end example
7196 If using @code{g77} (the @acronym{GNU} Fortran 77 compiler), then
7197 set the shell variable @code{G77} to @samp{yes}.
7198 If the output variable @code{FFLAGS} was not already set in the
7199 environment, then set it to @option{-g -02} for @code{g77} (or @option{-O2}
7200 where @code{g77} does not accept @option{-g}).  Otherwise, set
7201 @code{FFLAGS} to @option{-g} for all other Fortran 77 compilers.
7202 @end defmac
7204 @defmac AC_PROG_FC (@ovar{compiler-search-list}, @ovar{dialect})
7205 @acindex{PROG_FC}
7206 @ovindex FC
7207 @ovindex FCFLAGS
7208 Determine a Fortran compiler to use.  If @code{FC} is not already set in
7209 the environment, then @code{dialect} is a hint to indicate what Fortran
7210 dialect to search for; the default is to search for the newest available
7211 dialect.  Set the output variable @code{FC} to the name of the compiler
7212 found.
7214 By default, newer dialects are preferred over older dialects, but if
7215 @code{dialect} is specified then older dialects are preferred starting
7216 with the specified dialect.  @code{dialect} can currently be one of
7217 Fortran 77, Fortran 90, or Fortran 95.  However, this is only a hint of
7218 which compiler @emph{name} to prefer (e.g., @code{f90} or @code{f95}),
7219 and no attempt is made to guarantee that a particular language standard
7220 is actually supported.  Thus, it is preferable that you avoid the
7221 @code{dialect} option, and use AC_PROG_FC only for code compatible with
7222 the latest Fortran standard.
7224 This macro may, alternatively, be invoked with an optional first argument
7225 which, if specified, must be a blank-separated list of Fortran
7226 compilers to search for, just as in @code{AC_PROG_F77}.
7228 If the output variable @code{FCFLAGS} was not already set in the
7229 environment, then set it to @option{-g -02} for @acronym{GNU} @code{g77} (or
7230 @option{-O2} where @code{g77} does not accept @option{-g}).  Otherwise,
7231 set @code{FCFLAGS} to @option{-g} for all other Fortran compilers.
7232 @end defmac
7234 @defmac AC_PROG_F77_C_O
7235 @defmacx AC_PROG_FC_C_O
7236 @acindex{PROG_F77_C_O}
7237 @acindex{PROG_FC_C_O}
7238 @cvindex F77_NO_MINUS_C_MINUS_O
7239 @cvindex FC_NO_MINUS_C_MINUS_O
7240 Test whether the Fortran compiler accepts the options @option{-c} and
7241 @option{-o} simultaneously, and define @code{F77_NO_MINUS_C_MINUS_O} or
7242 @code{FC_NO_MINUS_C_MINUS_O}, respectively, if it does not.
7243 @end defmac
7245 The following macros check for Fortran compiler characteristics.
7246 To check for characteristics not listed here, use
7247 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}) or
7248 @code{AC_RUN_IFELSE} (@pxref{Runtime}), making sure to first set the
7249 current language to Fortran 77 or Fortran via @code{AC_LANG([Fortran 77])}
7250 or @code{AC_LANG(Fortran)} (@pxref{Language Choice}).
7253 @defmac AC_F77_LIBRARY_LDFLAGS
7254 @defmacx AC_FC_LIBRARY_LDFLAGS
7255 @acindex{F77_LIBRARY_LDFLAGS}
7256 @ovindex FLIBS
7257 @acindex{FC_LIBRARY_LDFLAGS}
7258 @ovindex FCLIBS
7259 Determine the linker flags (e.g., @option{-L} and @option{-l}) for the
7260 @dfn{Fortran intrinsic and runtime libraries} that are required to
7261 successfully link a Fortran program or shared library.  The output
7262 variable @code{FLIBS} or @code{FCLIBS} is set to these flags (which
7263 should be included after @code{LIBS} when linking).
7265 This macro is intended to be used in those situations when it is
7266 necessary to mix, e.g., C++ and Fortran source code in a single
7267 program or shared library (@pxref{Mixing Fortran 77 With C and C++, , ,
7268 automake, @acronym{GNU} Automake}).
7270 For example, if object files from a C++ and Fortran compiler must be
7271 linked together, then the C++ compiler/linker must be used for linking
7272 (since special C++-ish things need to happen at link time like calling
7273 global constructors, instantiating templates, enabling exception
7274 support, etc.).
7276 However, the Fortran intrinsic and runtime libraries must be linked in
7277 as well, but the C++ compiler/linker doesn't know by default how to add
7278 these Fortran 77 libraries.  Hence, this macro was created to determine
7279 these Fortran libraries.
7281 The macros @code{AC_F77_DUMMY_MAIN} and @code{AC_FC_DUMMY_MAIN} or
7282 @code{AC_F77_MAIN} and @code{AC_FC_MAIN} are probably also necessary to
7283 link C/C++ with Fortran; see below.
7284 @end defmac
7286 @defmac AC_F77_DUMMY_MAIN (@ovar{action-if-found}, @ovar{action-if-not-found})
7287 @defmacx AC_FC_DUMMY_MAIN (@ovar{action-if-found}, @ovar{action-if-not-found})
7288 @acindex{F77_DUMMY_MAIN}
7289 @cvindex F77_DUMMY_MAIN
7290 With many compilers, the Fortran libraries detected by
7291 @code{AC_F77_LIBRARY_LDFLAGS} or @code{AC_FC_LIBRARY_LDFLAGS} provide
7292 their own @code{main} entry function that initializes things like
7293 Fortran I/O, and which then calls a user-provided entry function named
7294 (say) @code{MAIN__} to run the user's program.  The
7295 @code{AC_F77_DUMMY_MAIN} and @code{AC_FC_DUMMY_MAIN} or
7296 @code{AC_F77_MAIN} and @code{AC_FC_MAIN} macros figure out how to deal with
7297 this interaction.
7299 When using Fortran for purely numerical functions (no I/O, etc.)@: often
7300 one prefers to provide one's own @code{main} and skip the Fortran
7301 library initializations.  In this case, however, one may still need to
7302 provide a dummy @code{MAIN__} routine in order to prevent linking errors
7303 on some systems.  @code{AC_F77_DUMMY_MAIN} or @code{AC_FC_DUMMY_MAIN}
7304 detects whether any such routine is @emph{required} for linking, and
7305 what its name is; the shell variable @code{F77_DUMMY_MAIN} or
7306 @code{FC_DUMMY_MAIN} holds this name, @code{unknown} when no solution
7307 was found, and @code{none} when no such dummy main is needed.
7309 By default, @var{action-if-found} defines @code{F77_DUMMY_MAIN} or
7310 @code{FC_DUMMY_MAIN} to the name of this routine (e.g., @code{MAIN__})
7311 @emph{if} it is required.  @var{action-if-not-found} defaults to
7312 exiting with an error.
7314 In order to link with Fortran routines, the user's C/C++ program should
7315 then include the following code to define the dummy main if it is
7316 needed:
7318 @example
7319 #ifdef F77_DUMMY_MAIN
7320 #  ifdef __cplusplus
7321      extern "C"
7322 #  endif
7323    int F77_DUMMY_MAIN() @{ return 1; @}
7324 #endif
7325 @end example
7327 (Replace @code{F77} with @code{FC} for Fortran instead of Fortran 77.)
7329 Note that this macro is called automatically from @code{AC_F77_WRAPPERS}
7330 or @code{AC_FC_WRAPPERS}; there is generally no need to call it
7331 explicitly unless one wants to change the default actions.
7332 @end defmac
7334 @defmac AC_F77_MAIN
7335 @defmacx AC_FC_MAIN
7336 @acindex{F77_MAIN}
7337 @cvindex F77_MAIN
7338 @acindex{FC_MAIN}
7339 @cvindex FC_MAIN
7340 As discussed above, many Fortran libraries allow you to provide an entry
7341 point called (say) @code{MAIN__} instead of the usual @code{main}, which
7342 is then called by a @code{main} function in the Fortran libraries that
7343 initializes things like Fortran I/O@.  The
7344 @code{AC_F77_MAIN} and @code{AC_FC_MAIN} macros detect whether it is
7345 @emph{possible} to utilize such an alternate main function, and defines
7346 @code{F77_MAIN} and @code{FC_MAIN} to the name of the function.  (If no
7347 alternate main function name is found, @code{F77_MAIN} and @code{FC_MAIN} are
7348 simply defined to @code{main}.)
7350 Thus, when calling Fortran routines from C that perform things like I/O,
7351 one should use this macro and declare the "main" function like so:
7353 @example
7354 #ifdef __cplusplus
7355   extern "C"
7356 #endif
7357 int F77_MAIN(int argc, char *argv[]);
7358 @end example
7360 (Again, replace @code{F77} with @code{FC} for Fortran instead of Fortran 77.)
7361 @end defmac
7363 @defmac AC_F77_WRAPPERS
7364 @defmacx AC_FC_WRAPPERS
7365 @acindex{F77_WRAPPERS}
7366 @cvindex F77_FUNC
7367 @cvindex F77_FUNC_
7368 @acindex{FC_WRAPPERS}
7369 @cvindex FC_FUNC
7370 @cvindex FC_FUNC_
7371 Defines C macros @code{F77_FUNC (name, NAME)}, @code{FC_FUNC (name, NAME)},
7372 @code{F77_FUNC_(name, NAME)}, and @code{FC_FUNC_(name, NAME)} to properly
7373 mangle the names of C/C++ identifiers, and identifiers with underscores,
7374 respectively, so that they match the name-mangling scheme used by the
7375 Fortran compiler.
7377 Fortran is case-insensitive, and in order to achieve this the Fortran
7378 compiler converts all identifiers into a canonical case and format.  To
7379 call a Fortran subroutine from C or to write a C function that is
7380 callable from Fortran, the C program must explicitly use identifiers in
7381 the format expected by the Fortran compiler.  In order to do this, one
7382 simply wraps all C identifiers in one of the macros provided by
7383 @code{AC_F77_WRAPPERS} or @code{AC_FC_WRAPPERS}.  For example, suppose
7384 you have the following Fortran 77 subroutine:
7386 @example
7387       subroutine foobar (x, y)
7388       double precision x, y
7389       y = 3.14159 * x
7390       return
7391       end
7392 @end example
7394 You would then declare its prototype in C or C++ as:
7396 @example
7397 #define FOOBAR_F77 F77_FUNC (foobar, FOOBAR)
7398 #ifdef __cplusplus
7399 extern "C"  /* prevent C++ name mangling */
7400 #endif
7401 void FOOBAR_F77(double *x, double *y);
7402 @end example
7404 Note that we pass both the lowercase and uppercase versions of the
7405 function name to @code{F77_FUNC} so that it can select the right one.
7406 Note also that all parameters to Fortran 77 routines are passed as
7407 pointers (@pxref{Mixing Fortran 77 With C and C++, , , automake, @acronym{GNU}
7408 Automake}).
7410 (Replace @code{F77} with @code{FC} for Fortran instead of Fortran 77.)
7412 Although Autoconf tries to be intelligent about detecting the
7413 name-mangling scheme of the Fortran compiler, there may be Fortran
7414 compilers that it doesn't support yet.  In this case, the above code
7415 generates a compile-time error, but some other behavior
7416 (e.g., disabling Fortran-related features) can be induced by checking
7417 whether @code{F77_FUNC} or @code{FC_FUNC} is defined.
7419 Now, to call that routine from a C program, we would do something like:
7421 @example
7423     double x = 2.7183, y;
7424     FOOBAR_F77 (&x, &y);
7426 @end example
7428 If the Fortran identifier contains an underscore (e.g., @code{foo_bar}),
7429 you should use @code{F77_FUNC_} or @code{FC_FUNC_} instead of
7430 @code{F77_FUNC} or @code{FC_FUNC} (with the same arguments).  This is
7431 because some Fortran compilers mangle names differently if they contain
7432 an underscore.
7433 @end defmac
7435 @defmac AC_F77_FUNC (@var{name}, @ovar{shellvar})
7436 @defmacx AC_FC_FUNC (@var{name}, @ovar{shellvar})
7437 @acindex{F77_FUNC}
7438 @acindex{FC_FUNC}
7439 Given an identifier @var{name}, set the shell variable @var{shellvar} to
7440 hold the mangled version @var{name} according to the rules of the
7441 Fortran linker (see also @code{AC_F77_WRAPPERS} or
7442 @code{AC_FC_WRAPPERS}).  @var{shellvar} is optional; if it is not
7443 supplied, the shell variable is simply @var{name}.  The purpose of
7444 this macro is to give the caller a way to access the name-mangling
7445 information other than through the C preprocessor as above, for example,
7446 to call Fortran routines from some language other than C/C++.
7447 @end defmac
7449 @defmac AC_FC_SRCEXT (@var{ext}, @ovar{action-if-success}, @
7450   @ovar{action-if-failure})
7451 @acindex{FC_SRCEXT}
7452 By default, the @code{FC} macros perform their tests using a @file{.f}
7453 extension for source-code files.  Some compilers, however, only enable
7454 newer language features for appropriately named files, e.g., Fortran 90
7455 features only for @file{.f90} files.  On the other hand, some other
7456 compilers expect all source files to end in @file{.f} and require
7457 special flags to support other file name extensions.  The
7458 @code{AC_FC_SRCEXT} macro deals with both of these issues.
7460 The @code{AC_FC_SRCEXT} tries to get the @code{FC} compiler to accept files
7461 ending with the extension .@var{ext} (i.e., @var{ext} does @emph{not}
7462 contain the dot).  If any special compiler flags are needed for this, it
7463 stores them in the output variable @code{FCFLAGS_}@var{ext}.  This
7464 extension and these flags are then used for all subsequent @code{FC} tests
7465 (until @code{AC_FC_SRCEXT} is called again).
7467 For example, you would use @code{AC_FC_SRCEXT(f90)} to employ the
7468 @file{.f90} extension in future tests, and it would set a
7469 @code{FCFLAGS_f90} output variable with any extra flags that are needed
7470 to compile such files.
7472 The @code{FCFLAGS_}@var{ext} can @emph{not} be simply absorbed into
7473 @code{FCFLAGS}, for two reasons based on the limitations of some
7474 compilers.  First, only one @code{FCFLAGS_}@var{ext} can be used at a
7475 time, so files with different extensions must be compiled separately.
7476 Second, @code{FCFLAGS_}@var{ext} must appear @emph{immediately} before
7477 the source-code file name when compiling.  So, continuing the example
7478 above, you might compile a @file{foo.f90} file in your makefile with the
7479 command:
7481 @example
7482 foo.o: foo.f90
7483      $(FC) -c $(FCFLAGS) $(FCFLAGS_f90) '$(srcdir)/foo.f90'
7484 @end example
7486 If @code{AC_FC_SRCEXT} succeeds in compiling files with the @var{ext}
7487 extension, it calls @var{action-if-success} (defaults to nothing).  If
7488 it fails, and cannot find a way to make the @code{FC} compiler accept such
7489 files, it calls @var{action-if-failure} (defaults to exiting with an
7490 error message).
7492 @end defmac
7494 @defmac AC_FC_FREEFORM (@ovar{action-if-success}, @ovar{action-if-failure})
7495 @acindex{FC_FREEFORM}
7497 The @code{AC_FC_FREEFORM} tries to ensure that the Fortran compiler
7498 (@code{$FC}) allows free-format source code (as opposed to the older
7499 fixed-format style from Fortran 77).  If necessary, it may add some
7500 additional flags to @code{FCFLAGS}.
7502 This macro is most important if you are using the default @file{.f}
7503 extension, since many compilers interpret this extension as indicating
7504 fixed-format source unless an additional flag is supplied.  If you
7505 specify a different extension with @code{AC_FC_SRCEXT}, such as
7506 @file{.f90} or @file{.f95}, then @code{AC_FC_FREEFORM} ordinarily
7507 succeeds without modifying @code{FCFLAGS}.
7509 If @code{AC_FC_FREEFORM} succeeds in compiling free-form source, it
7510 calls @var{action-if-success} (defaults to nothing).  If it fails, it
7511 calls @var{action-if-failure} (defaults to exiting with an error
7512 message).
7513 @end defmac
7515 @node System Services
7516 @section System Services
7518 The following macros check for operating system services or capabilities.
7520 @anchor{AC_PATH_X}
7521 @defmac AC_PATH_X
7522 @acindex{PATH_X}
7523 @evindex XMKMF
7524 @cindex X Window System
7525 Try to locate the X Window System include files and libraries.  If the
7526 user gave the command line options @option{--x-includes=@var{dir}} and
7527 @option{--x-libraries=@var{dir}}, use those directories.
7529 If either or both were not given, get the missing values by running
7530 @code{xmkmf} (or an executable pointed to by the @code{XMKMF}
7531 environment variable) on a trivial @file{Imakefile} and examining the
7532 makefile that it produces.  Setting @code{XMKMF} to @samp{false}
7533 disables this method.
7535 If this method fails to find the X Window System, @command{configure}
7536 looks for the files in several directories where they often reside.
7537 If either method is successful, set the shell variables
7538 @code{x_includes} and @code{x_libraries} to their locations, unless they
7539 are in directories the compiler searches by default.
7541 If both methods fail, or the user gave the command line option
7542 @option{--without-x}, set the shell variable @code{no_x} to @samp{yes};
7543 otherwise set it to the empty string.
7544 @end defmac
7546 @anchor{AC_PATH_XTRA}
7547 @defmac AC_PATH_XTRA
7548 @acindex{PATH_XTRA}
7549 @ovindex X_CFLAGS
7550 @ovindex X_LIBS
7551 @ovindex X_EXTRA_LIBS
7552 @ovindex X_PRE_LIBS
7553 @cvindex X_DISPLAY_MISSING
7554 An enhanced version of @code{AC_PATH_X}.  It adds the C compiler flags
7555 that X needs to output variable @code{X_CFLAGS}, and the X linker flags
7556 to @code{X_LIBS}.  Define @code{X_DISPLAY_MISSING} if X is not
7557 available.
7559 This macro also checks for special libraries that some systems need in
7560 order to compile X programs.  It adds any that the system needs to
7561 output variable @code{X_EXTRA_LIBS}.  And it checks for special X11R6
7562 libraries that need to be linked with before @option{-lX11}, and adds
7563 any found to the output variable @code{X_PRE_LIBS}.
7565 @c This is an incomplete kludge.  Make a real way to do it.
7566 @c If you need to check for other X functions or libraries yourself, then
7567 @c after calling this macro, add the contents of @code{X_EXTRA_LIBS} to
7568 @c @code{LIBS} temporarily, like this: (FIXME - add example)
7569 @end defmac
7571 @anchor{AC_SYS_INTERPRETER}
7572 @defmac AC_SYS_INTERPRETER
7573 @acindex{SYS_INTERPRETER}
7574 Check whether the system supports starting scripts with a line of the
7575 form @samp{#!/bin/sh} to select the interpreter to use for the script.
7576 After running this macro, shell code in @file{configure.ac} can check
7577 the shell variable @code{interpval}; it is set to @samp{yes}
7578 if the system supports @samp{#!}, @samp{no} if not.
7579 @end defmac
7581 @defmac AC_SYS_LARGEFILE
7582 @acindex{SYS_LARGEFILE}
7583 @cvindex _FILE_OFFSET_BITS
7584 @cvindex _LARGE_FILES
7585 @ovindex CC
7586 @cindex Large file support
7587 @cindex LFS
7588 Arrange for
7589 @uref{http://www.unix-systems.org/@/version2/@/whatsnew/@/lfs20mar.html,
7590 large-file support}.  On some hosts, one must use special compiler
7591 options to build programs that can access large files.  Append any such
7592 options to the output variable @code{CC}.  Define
7593 @code{_FILE_OFFSET_BITS} and @code{_LARGE_FILES} if necessary.
7595 Large-file support can be disabled by configuring with the
7596 @option{--disable-largefile} option.
7598 If you use this macro, check that your program works even when
7599 @code{off_t} is wider than @code{long int}, since this is common when
7600 large-file support is enabled.  For example, it is not correct to print
7601 an arbitrary @code{off_t} value @code{X} with @code{printf ("%ld",
7602 (long int) X)}.
7604 The LFS introduced the @code{fseeko} and @code{ftello} functions to
7605 replace their C counterparts @code{fseek} and @code{ftell} that do not
7606 use @code{off_t}.  Take care to use @code{AC_FUNC_FSEEKO} to make their
7607 prototypes available when using them and large-file support is
7608 enabled.
7609 @end defmac
7611 @anchor{AC_SYS_LONG_FILE_NAMES}
7612 @defmac AC_SYS_LONG_FILE_NAMES
7613 @acindex{SYS_LONG_FILE_NAMES}
7614 @cvindex HAVE_LONG_FILE_NAMES
7615 If the system supports file names longer than 14 characters, define
7616 @code{HAVE_LONG_FILE_NAMES}.
7617 @end defmac
7619 @defmac AC_SYS_POSIX_TERMIOS
7620 @acindex{SYS_POSIX_TERMIOS}
7621 @cindex Posix termios headers
7622 @cindex termios Posix headers
7623 Check to see if the Posix termios headers and functions are available on the
7624 system.  If so, set the shell variable @code{ac_cv_sys_posix_termios} to
7625 @samp{yes}.  If not, set the variable to @samp{no}.
7626 @end defmac
7628 @node Posix Variants
7629 @section Posix Variants
7631 The following macro makes it possible to use features of Posix that are
7632 extensions to C, as well as platform extensions not defined by Posix.
7634 @anchor{AC_USE_SYSTEM_EXTENSIONS}
7635 @defmac AC_USE_SYSTEM_EXTENSIONS
7636 @acindex{USE_SYSTEM_EXTENSIONS}
7637 @cvindex _ALL_SOURCE
7638 @cvindex _GNU_SOURCE
7639 @cvindex _MINIX
7640 @cvindex _POSIX_1_SOURCE
7641 @cvindex _POSIX_PTHREAD_SEMANTICS
7642 @cvindex _POSIX_SOURCE
7643 @cvindex _TANDEM_SOURCE
7644 @cvindex __EXTENSIONS__
7645 This macro was introduced in Autoconf 2.60.  If possible, enable
7646 extensions to C or Posix on hosts that normally disable the extensions,
7647 typically due to standards-conformance namespace issues.  This should be
7648 called before any macros that run the C compiler.  The following
7649 preprocessor macros are defined where appropriate:
7651 @table @code
7652 @item _GNU_SOURCE
7653 Enable extensions on @acronym{GNU}/Linux.
7654 @item __EXTENSIONS__
7655 Enable general extensions on Solaris.
7656 @item _POSIX_PTHREAD_SEMANTICS
7657 Enable threading extensions on Solaris.
7658 @item _TANDEM_SOURCE
7659 Enable extensions for the @acronym{HP} NonStop platform.
7660 @item _ALL_SOURCE
7661 Enable extensions for @acronym{AIX} 3, and for Interix.
7662 @item _POSIX_SOURCE
7663 Enable Posix functions for Minix.
7664 @item _POSIX_1_SOURCE
7665 Enable additional Posix functions for Minix.
7666 @item _MINIX
7667 Identify Minix platform.  This particular preprocessor macro is
7668 obsolescent, and may be removed in a future release of Autoconf.
7669 @end table
7670 @end defmac
7673 @node Erlang Libraries
7674 @section Erlang Libraries
7675 @cindex Erlang, Library, checking
7677 The following macros check for an installation of Erlang/OTP, and for the
7678 presence of certain Erlang libraries.  All those macros require the
7679 configuration of an Erlang interpreter and an Erlang compiler
7680 (@pxref{Erlang Compiler and Interpreter}).
7682 @defmac AC_ERLANG_SUBST_ROOT_DIR
7683 @acindex{ERLANG_SUBST_ROOT_DIR}
7684 @ovindex ERLANG_ROOT_DIR
7686 Set the output variable @code{ERLANG_ROOT_DIR} to the path to the base
7687 directory in which Erlang/OTP is installed (as returned by Erlang's
7688 @code{code:root_dir/0} function).  The result of this test is cached if
7689 caching is enabled when running @command{configure}.
7690 @end defmac
7692 @defmac AC_ERLANG_SUBST_LIB_DIR
7693 @acindex{ERLANG_SUBST_LIB_DIR}
7694 @ovindex ERLANG_LIB_DIR
7696 Set the output variable @code{ERLANG_LIB_DIR} to the path of the library
7697 directory of Erlang/OTP (as returned by Erlang's
7698 @code{code:lib_dir/0} function), which subdirectories each contain an installed
7699 Erlang/OTP library.  The result of this test is cached if caching is enabled
7700 when running @command{configure}.
7701 @end defmac
7703 @defmac AC_ERLANG_CHECK_LIB (@var{library}, @ovar{action-if-found}, @
7704   @ovar{action-if-not-found})
7705 @acindex{ERLANG_CHECK_LIB}
7706 @ovindex ERLANG_LIB_DIR_@var{library}
7707 @ovindex ERLANG_LIB_VER_@var{library}
7709 Test whether the Erlang/OTP library @var{library} is installed by
7710 calling Erlang's @code{code:lib_dir/1} function.  The result of this
7711 test is cached if caching is enabled when running @command{configure}.
7712 @var{action-if-found} is a list of shell commands to run if the library
7713 is installed; @var{action-if-not-found} is a list of shell commands to
7714 run if it is not.  Additionally, if the library is installed, the output
7715 variable @samp{ERLANG_LIB_DIR_@var{library}} is set to the path to the
7716 library installation directory, and the output variable
7717 @samp{ERLANG_LIB_VER_@var{library}} is set to the version number that is
7718 part of the subdirectory name, if it is in the standard form
7719 (@code{@var{library}-@var{version}}).  If the directory name does not
7720 have a version part, @samp{ERLANG_LIB_VER_@var{library}} is set to the
7721 empty string.  If the library is not installed,
7722 @samp{ERLANG_LIB_DIR_@var{library}} and
7723 @samp{ERLANG_LIB_VER_@var{library}} are set to @code{"not found"}.  For
7724 example, to check if library @code{stdlib} is installed:
7726 @example
7727 AC_ERLANG_CHECK_LIB([stdlib],
7728   [echo "stdlib version \"$ERLANG_LIB_VER_stdlib\""
7729    echo "is installed in \"$ERLANG_LIB_DIR_stdlib\""],
7730   [AC_MSG_ERROR([stdlib was not found!])])
7731 @end example
7732 @end defmac
7734 In addition to the above macros, which test installed Erlang libraries, the
7735 following macros determine the paths to the directories into which newly built
7736 Erlang libraries are to be installed:
7738 @defmac AC_ERLANG_SUBST_INSTALL_LIB_DIR
7739 @acindex{ERLANG_SUBST_INSTALL_LIB_DIR}
7740 @ovindex ERLANG_INSTALL_LIB_DIR
7742 Set the @code{ERLANG_INSTALL_LIB_DIR} output variable to the directory into
7743 which every built Erlang library should be installed in a separate
7744 subdirectory.
7745 If this variable is not set in the environment when @command{configure} runs,
7746 its default value is @code{$ERLANG_LIB_DIR}, which value is set by the
7747 @code{AC_ERLANG_SUBST_LIB_DIR} macro.
7748 @end defmac
7750 @defmac AC_ERLANG_SUBST_INSTALL_LIB_SUBDIR (@var{library}, @var{version})
7751 @acindex{ERLANG_SUBST_INSTALL_LIB_SUBDIR}
7752 @ovindex ERLANG_INSTALL_LIB_DIR_@var{library}
7754 Set the @samp{ERLANG_INSTALL_LIB_DIR_@var{library}} output variable to the
7755 directory into which the built Erlang library @var{library} version
7756 @var{version} should be installed.  If this variable is not set in the
7757 environment when @command{configure} runs, its default value is
7758 @samp{$ERLANG_INSTALL_LIB_DIR/@var{library}-@var{version}}, the value of the
7759 @code{ERLANG_INSTALL_LIB_DIR} variable being set by the
7760 @code{AC_ERLANG_SUBST_INSTALL_LIB_DIR} macro.
7761 @end defmac
7767 @c ========================================================= Writing Tests
7769 @node Writing Tests
7770 @chapter Writing Tests
7772 If the existing feature tests don't do something you need, you have to
7773 write new ones.  These macros are the building blocks.  They provide
7774 ways for other macros to check whether various kinds of features are
7775 available and report the results.
7777 This chapter contains some suggestions and some of the reasons why the
7778 existing tests are written the way they are.  You can also learn a lot
7779 about how to write Autoconf tests by looking at the existing ones.  If
7780 something goes wrong in one or more of the Autoconf tests, this
7781 information can help you understand the assumptions behind them, which
7782 might help you figure out how to best solve the problem.
7784 These macros check the output of the compiler system of the current
7785 language (@pxref{Language Choice}).  They do not cache the results of
7786 their tests for future use (@pxref{Caching Results}), because they don't
7787 know enough about the information they are checking for to generate a
7788 cache variable name.  They also do not print any messages, for the same
7789 reason.  The checks for particular kinds of features call these macros
7790 and do cache their results and print messages about what they're
7791 checking for.
7793 When you write a feature test that could be applicable to more than one
7794 software package, the best thing to do is encapsulate it in a new macro.
7795 @xref{Writing Autoconf Macros}, for how to do that.
7797 @menu
7798 * Language Choice::             Selecting which language to use for testing
7799 * Writing Test Programs::       Forging source files for compilers
7800 * Running the Preprocessor::    Detecting preprocessor symbols
7801 * Running the Compiler::        Detecting language or header features
7802 * Running the Linker::          Detecting library features
7803 * Runtime::                     Testing for runtime features
7804 * Systemology::                 A zoology of operating systems
7805 * Multiple Cases::              Tests for several possible values
7806 @end menu
7808 @node Language Choice
7809 @section Language Choice
7810 @cindex Language
7812 Autoconf-generated @command{configure} scripts check for the C compiler and
7813 its features by default.  Packages that use other programming languages
7814 (maybe more than one, e.g., C and C++) need to test features of the
7815 compilers for the respective languages.  The following macros determine
7816 which programming language is used in the subsequent tests in
7817 @file{configure.ac}.
7819 @anchor{AC_LANG}
7820 @defmac AC_LANG (@var{language})
7821 Do compilation tests using the compiler, preprocessor, and file
7822 extensions for the specified @var{language}.
7824 Supported languages are:
7826 @table @samp
7827 @item C
7828 Do compilation tests using @code{CC} and @code{CPP} and use extension
7829 @file{.c} for test programs.  Use compilation flags: @code{CPPFLAGS} with
7830 @code{CPP}, and both @code{CPPFLAGS} and @code{CFLAGS} with @code{CC}.
7832 @item C++
7833 Do compilation tests using @code{CXX} and @code{CXXCPP} and use
7834 extension @file{.C} for test programs.  Use compilation flags:
7835 @code{CPPFLAGS} with @code{CXXCPP}, and both @code{CPPFLAGS} and
7836 @code{CXXFLAGS} with @code{CXX}.
7838 @item Fortran 77
7839 Do compilation tests using @code{F77} and use extension @file{.f} for
7840 test programs.  Use compilation flags: @code{FFLAGS}.
7842 @item Fortran
7843 Do compilation tests using @code{FC} and use extension @file{.f} (or
7844 whatever has been set by @code{AC_FC_SRCEXT}) for test programs.  Use
7845 compilation flags: @code{FCFLAGS}.
7847 @item Erlang
7848 @ovindex ERLC
7849 @ovindex ERL
7850 @ovindex ERLCFLAGS
7851 Compile and execute tests using @code{ERLC} and @code{ERL} and use extension
7852 @file{.erl} for test Erlang modules.  Use compilation flags: @code{ERLCFLAGS}.
7854 @item Objective C
7855 Do compilation tests using @code{OBJC} and @code{OBJCPP} and use
7856 extension @file{.m} for test programs.  Use compilation flags:
7857 @code{CPPFLAGS} with @code{OBJCPP}, and both @code{CPPFLAGS} and
7858 @code{OBJCFLAGS} with @code{OBJC}.
7859 @end table
7860 @end defmac
7862 @anchor{AC_LANG_PUSH}
7863 @defmac AC_LANG_PUSH (@var{language})
7864 @acindex{LANG_PUSH}
7865 Remember the current language (as set by @code{AC_LANG}) on a stack, and
7866 then select the @var{language}.  Use this macro and @code{AC_LANG_POP}
7867 in macros that need to temporarily switch to a particular language.
7868 @end defmac
7870 @defmac AC_LANG_POP (@ovar{language})
7871 @acindex{LANG_POP}
7872 Select the language that is saved on the top of the stack, as set by
7873 @code{AC_LANG_PUSH}, and remove it from the stack.
7875 If given, @var{language} specifies the language we just @emph{quit}.  It
7876 is a good idea to specify it when it's known (which should be the
7877 case@dots{}), since Autoconf detects inconsistencies.
7879 @example
7880 AC_LANG_PUSH([Fortran 77])
7881 # Perform some tests on Fortran 77.
7882 # @dots{}
7883 AC_LANG_POP([Fortran 77])
7884 @end example
7885 @end defmac
7887 @defmac AC_LANG_ASSERT (@var{language})
7888 @acindex{LANG_ASSERT} Check statically that the current language is
7889 @var{language}.  You should use this in your language specific macros
7890 to avoid that they be called with an inappropriate language.
7892 This macro runs only at @command{autoconf} time, and incurs no cost at
7893 @command{configure} time.  Sadly enough and because Autoconf is a two
7894 layer language @footnote{Because M4 is not aware of Sh code,
7895 especially conditionals, some optimizations that look nice statically
7896 may produce incorrect results at runtime.}, the macros
7897 @code{AC_LANG_PUSH} and @code{AC_LANG_POP} cannot be ``optimizing'',
7898 therefore as much as possible you ought to avoid using them to wrap
7899 your code, rather, require from the user to run the macro with a
7900 correct current language, and check it with @code{AC_LANG_ASSERT}.
7901 And anyway, that may help the user understand she is running a Fortran
7902 macro while expecting a result about her Fortran 77 compiler@dots{}
7903 @end defmac
7906 @defmac AC_REQUIRE_CPP
7907 @acindex{REQUIRE_CPP}
7908 Ensure that whichever preprocessor would currently be used for tests has
7909 been found.  Calls @code{AC_REQUIRE} (@pxref{Prerequisite Macros}) with an
7910 argument of either @code{AC_PROG_CPP} or @code{AC_PROG_CXXCPP},
7911 depending on which language is current.
7912 @end defmac
7915 @node Writing Test Programs
7916 @section Writing Test Programs
7918 Autoconf tests follow a common scheme: feed some program with some
7919 input, and most of the time, feed a compiler with some source file.
7920 This section is dedicated to these source samples.
7922 @menu
7923 * Guidelines::                  General rules for writing test programs
7924 * Test Functions::              Avoiding pitfalls in test programs
7925 * Generating Sources::          Source program boilerplate
7926 @end menu
7928 @node Guidelines
7929 @subsection Guidelines for Test Programs
7931 The most important rule to follow when writing testing samples is:
7933 @center @emph{Look for realism.}
7935 This motto means that testing samples must be written with the same
7936 strictness as real programs are written.  In particular, you should
7937 avoid ``shortcuts'' and simplifications.
7939 Don't just play with the preprocessor if you want to prepare a
7940 compilation.  For instance, using @command{cpp} to check whether a header is
7941 functional might let your @command{configure} accept a header which
7942 causes some @emph{compiler} error.  Do not hesitate to check a header with
7943 other headers included before, especially required headers.
7945 Make sure the symbols you use are properly defined, i.e., refrain for
7946 simply declaring a function yourself instead of including the proper
7947 header.
7949 Test programs should not write to standard output.  They
7950 should exit with status 0 if the test succeeds, and with status 1
7951 otherwise, so that success
7952 can be distinguished easily from a core dump or other failure;
7953 segmentation violations and other failures produce a nonzero exit
7954 status.  Unless you arrange for @code{exit} to be declared, test
7955 programs should @code{return}, not @code{exit}, from @code{main},
7956 because on many systems @code{exit} is not declared by default.
7958 Test programs can use @code{#if} or @code{#ifdef} to check the values of
7959 preprocessor macros defined by tests that have already run.  For
7960 example, if you call @code{AC_HEADER_STDBOOL}, then later on in
7961 @file{configure.ac} you can have a test program that includes
7962 @file{stdbool.h} conditionally:
7964 @example
7965 @group
7966 #ifdef HAVE_STDBOOL_H
7967 # include <stdbool.h>
7968 #endif
7969 @end group
7970 @end example
7972 Both @code{#if HAVE_STDBOOL_H} and @code{#ifdef HAVE_STDBOOL_H} will
7973 work with any standard C compiler.  Some developers prefer @code{#if}
7974 because it is easier to read, while others prefer @code{#ifdef} because
7975 it avoids diagnostics with picky compilers like @acronym{GCC} with the
7976 @option{-Wundef} option.
7978 If a test program needs to use or create a data file, give it a name
7979 that starts with @file{conftest}, such as @file{conftest.data}.  The
7980 @command{configure} script cleans up by running @samp{rm -f -r conftest*}
7981 after running test programs and if the script is interrupted.
7983 @node Test Functions
7984 @subsection Test Functions
7986 These days it's safe to assume support for function prototypes
7987 (introduced in C89).
7989 Functions that test programs declare should also be conditionalized for
7990 C++, which requires @samp{extern "C"} prototypes.  Make sure to not
7991 include any header files containing clashing prototypes.
7993 @example
7994 #ifdef __cplusplus
7995 extern "C"
7996 #endif
7997 void *valloc (size_t);
7998 @end example
8000 If a test program calls a function with invalid parameters (just to see
8001 whether it exists), organize the program to ensure that it never invokes
8002 that function.  You can do this by calling it in another function that is
8003 never invoked.  You can't do it by putting it after a call to
8004 @code{exit}, because @acronym{GCC} version 2 knows that @code{exit}
8005 never returns
8006 and optimizes out any code that follows it in the same block.
8008 If you include any header files, be sure to call the functions
8009 relevant to them with the correct number of arguments, even if they are
8010 just 0, to avoid compilation errors due to prototypes.  @acronym{GCC}
8011 version 2
8012 has internal prototypes for several functions that it automatically
8013 inlines; for example, @code{memcpy}.  To avoid errors when checking for
8014 them, either pass them the correct number of arguments or redeclare them
8015 with a different return type (such as @code{char}).
8018 @node Generating Sources
8019 @subsection Generating Sources
8021 Autoconf provides a set of macros that can be used to generate test
8022 source files.  They are written to be language generic, i.e., they
8023 actually depend on the current language (@pxref{Language Choice}) to
8024 ``format'' the output properly.
8027 @defmac AC_LANG_CONFTEST (@var{source})
8028 @acindex{LANG_CONFTEST}
8029 Save the @var{source} text in the current test source file:
8030 @file{conftest.@var{extension}} where the @var{extension} depends on the
8031 current language.
8033 Note that the @var{source} is evaluated exactly once, like regular
8034 Autoconf macro arguments, and therefore (i) you may pass a macro
8035 invocation, (ii) if not, be sure to double quote if needed.
8036 @end defmac
8038 @defmac AC_LANG_SOURCE (@var{source})
8039 @acindex{LANG_SOURCE}
8040 Expands into the @var{source}, with the definition of
8041 all the @code{AC_DEFINE} performed so far.
8042 @end defmac
8044 For instance executing (observe the double quotation!):
8046 @example
8047 AC_INIT([Hello], [1.0], [bug-hello@@example.org])
8048 AC_DEFINE([HELLO_WORLD], ["Hello, World\n"],
8049   [Greetings string.])
8050 AC_LANG(C)
8051 AC_LANG_CONFTEST(
8052    [AC_LANG_SOURCE([[const char hw[] = "Hello, World\n";]])])
8053 gcc -E -dD -o - conftest.c
8054 @end example
8056 @noindent
8057 results in:
8059 @example
8060 @dots{}
8061 # 1 "conftest.c"
8063 #define PACKAGE_NAME "Hello"
8064 #define PACKAGE_TARNAME "hello"
8065 #define PACKAGE_VERSION "1.0"
8066 #define PACKAGE_STRING "Hello 1.0"
8067 #define PACKAGE_BUGREPORT "bug-hello@@example.org"
8068 #define HELLO_WORLD "Hello, World\n"
8070 const char hw[] = "Hello, World\n";
8071 @end example
8073 When the test language is Fortran or Erlang, the @code{AC_DEFINE} definitions
8074 are not automatically translated into constants in the source code by this
8075 macro.
8077 @defmac AC_LANG_PROGRAM (@var{prologue}, @var{body})
8078 @acindex{LANG_PROGRAM}
8079 Expands into a source file which consists of the @var{prologue}, and
8080 then @var{body} as body of the main function (e.g., @code{main} in
8081 C).  Since it uses @code{AC_LANG_SOURCE}, the features of the latter are
8082 available.
8083 @end defmac
8085 For instance:
8087 @example
8088 AC_INIT([Hello], [1.0], [bug-hello@@example.org])
8089 AC_DEFINE([HELLO_WORLD], ["Hello, World\n"],
8090   [Greetings string.])
8091 AC_LANG_CONFTEST(
8092 [AC_LANG_PROGRAM([[const char hw[] = "Hello, World\n";]],
8093                  [[fputs (hw, stdout);]])])
8094 gcc -E -dD -o - conftest.c
8095 @end example
8097 @noindent
8098 results in:
8100 @example
8101 @dots{}
8102 # 1 "conftest.c"
8104 #define PACKAGE_NAME "Hello"
8105 #define PACKAGE_TARNAME "hello"
8106 #define PACKAGE_VERSION "1.0"
8107 #define PACKAGE_STRING "Hello 1.0"
8108 #define PACKAGE_BUGREPORT "bug-hello@@example.org"
8109 #define HELLO_WORLD "Hello, World\n"
8111 const char hw[] = "Hello, World\n";
8113 main ()
8115 fputs (hw, stdout);
8116   ;
8117   return 0;
8119 @end example
8121 In Erlang tests, the created source file is that of an Erlang module called
8122 @code{conftest} (@file{conftest.erl}).  This module defines and exports
8123 at least
8124 one @code{start/0} function, which is called to perform the test.  The
8125 @var{prologue} is optional code that is inserted between the module header and
8126 the @code{start/0} function definition.  @var{body} is the body of the
8127 @code{start/0} function without the final period (@pxref{Runtime}, about
8128 constraints on this function's behavior).
8130 For instance:
8132 @example
8133 AC_INIT([Hello], [1.0], [bug-hello@@example.org])
8134 AC_LANG(Erlang)
8135 AC_LANG_CONFTEST(
8136 [AC_LANG_PROGRAM([[-define(HELLO_WORLD, "Hello, world!").]],
8137                  [[io:format("~s~n", [?HELLO_WORLD])]])])
8138 cat conftest.erl
8139 @end example
8141 @noindent
8142 results in:
8144 @example
8145 -module(conftest).
8146 -export([start/0]).
8147 -define(HELLO_WORLD, "Hello, world!").
8148 start() ->
8149 io:format("~s~n", [?HELLO_WORLD])
8151 @end example
8153 @defmac AC_LANG_CALL (@var{prologue}, @var{function})
8154 @acindex{LANG_CALL}
8155 Expands into a source file which consists of the @var{prologue}, and
8156 then a call to the @var{function} as body of the main function (e.g.,
8157 @code{main} in C).  Since it uses @code{AC_LANG_PROGRAM}, the feature
8158 of the latter are available.
8160 This function will probably be replaced in the future by a version
8161 which would enable specifying the arguments.  The use of this macro is
8162 not encouraged, as it violates strongly the typing system.
8164 This macro cannot be used for Erlang tests.
8165 @end defmac
8167 @defmac AC_LANG_FUNC_LINK_TRY (@var{function})
8168 @acindex{LANG_FUNC_LINK_TRY}
8169 Expands into a source file which uses the @var{function} in the body of
8170 the main function (e.g., @code{main} in C).  Since it uses
8171 @code{AC_LANG_PROGRAM}, the features of the latter are available.
8173 As @code{AC_LANG_CALL}, this macro is documented only for completeness.
8174 It is considered to be severely broken, and in the future will be
8175 removed in favor of actual function calls (with properly typed
8176 arguments).
8178 This macro cannot be used for Erlang tests.
8179 @end defmac
8181 @node Running the Preprocessor
8182 @section Running the Preprocessor
8184 Sometimes one might need to run the preprocessor on some source file.
8185 @emph{Usually it is a bad idea}, as you typically need to @emph{compile}
8186 your project, not merely run the preprocessor on it; therefore you
8187 certainly want to run the compiler, not the preprocessor.  Resist the
8188 temptation of following the easiest path.
8190 Nevertheless, if you need to run the preprocessor, then use
8191 @code{AC_PREPROC_IFELSE}.
8193 The macros described in this section cannot be used for tests in Erlang or
8194 Fortran, since those languages require no preprocessor.
8196 @anchor{AC_PREPROC_IFELSE}
8197 @defmac AC_PREPROC_IFELSE (@var{input}, @ovar{action-if-true}, @
8198   @ovar{action-if-false})
8199 @acindex{PREPROC_IFELSE}
8200 Run the preprocessor of the current language (@pxref{Language Choice})
8201 on the @var{input}, run the shell commands @var{action-if-true} on
8202 success, @var{action-if-false} otherwise.  The @var{input} can be made
8203 by @code{AC_LANG_PROGRAM} and friends.
8205 This macro uses @code{CPPFLAGS}, but not @code{CFLAGS}, because
8206 @option{-g}, @option{-O}, etc.@: are not valid options to many C
8207 preprocessors.
8209 It is customary to report unexpected failures with
8210 @code{AC_MSG_FAILURE}.
8211 @end defmac
8213 For instance:
8215 @example
8216 AC_INIT([Hello], [1.0], [bug-hello@@example.org])
8217 AC_DEFINE([HELLO_WORLD], ["Hello, World\n"],
8218   [Greetings string.])
8219 AC_PREPROC_IFELSE(
8220    [AC_LANG_PROGRAM([[const char hw[] = "Hello, World\n";]],
8221                     [[fputs (hw, stdout);]])],
8222    [AC_MSG_RESULT([OK])],
8223    [AC_MSG_FAILURE([unexpected preprocessor failure])])
8224 @end example
8226 @noindent
8227 results in:
8229 @example
8230 checking for gcc... gcc
8231 checking for C compiler default output file name... a.out
8232 checking whether the C compiler works... yes
8233 checking whether we are cross compiling... no
8234 checking for suffix of executables...
8235 checking for suffix of object files... o
8236 checking whether we are using the GNU C compiler... yes
8237 checking whether gcc accepts -g... yes
8238 checking for gcc option to accept ISO C89... none needed
8239 checking how to run the C preprocessor... gcc -E
8241 @end example
8243 @sp 1
8245 The macro @code{AC_TRY_CPP} (@pxref{Obsolete Macros}) used to play the
8246 role of @code{AC_PREPROC_IFELSE}, but double quotes its argument, making
8247 it impossible to use it to elaborate sources.  You are encouraged to
8248 get rid of your old use of the macro @code{AC_TRY_CPP} in favor of
8249 @code{AC_PREPROC_IFELSE}, but, in the first place, are you sure you need
8250 to run the @emph{preprocessor} and not the compiler?
8252 @anchor{AC_EGREP_HEADER}
8253 @defmac AC_EGREP_HEADER (@var{pattern}, @var{header-file}, @
8254   @var{action-if-found}, @ovar{action-if-not-found})
8255 @acindex{EGREP_HEADER}
8256 If the output of running the preprocessor on the system header file
8257 @var{header-file} matches the extended regular expression
8258 @var{pattern}, execute shell commands @var{action-if-found}, otherwise
8259 execute @var{action-if-not-found}.
8260 @end defmac
8262 @anchor{AC_EGREP_CPP}
8263 @defmac AC_EGREP_CPP (@var{pattern}, @var{program}, @
8264   @ovar{action-if-found}, @ovar{action-if-not-found})
8265 @acindex{EGREP_CPP}
8266 @var{program} is the text of a C or C++ program, on which shell
8267 variable, back quote, and backslash substitutions are performed.  If the
8268 output of running the preprocessor on @var{program} matches the
8269 extended regular expression @var{pattern}, execute shell commands
8270 @var{action-if-found}, otherwise execute @var{action-if-not-found}.
8271 @end defmac
8275 @node Running the Compiler
8276 @section Running the Compiler
8278 To check for a syntax feature of the current language's (@pxref{Language
8279 Choice}) compiler, such as whether it recognizes a certain keyword, or
8280 simply to try some library feature, use @code{AC_COMPILE_IFELSE} to try
8281 to compile a small program that uses that feature.
8283 @defmac AC_COMPILE_IFELSE (@var{input}, @ovar{action-if-true}, @
8284   @ovar{action-if-false})
8285 @acindex{COMPILE_IFELSE}
8286 Run the compiler and compilation flags of the current language
8287 (@pxref{Language Choice}) on the @var{input}, run the shell commands
8288 @var{action-if-true} on success, @var{action-if-false} otherwise.  The
8289 @var{input} can be made by @code{AC_LANG_PROGRAM} and friends.
8291 It is customary to report unexpected failures with
8292 @code{AC_MSG_FAILURE}.  This macro does not try to link; use
8293 @code{AC_LINK_IFELSE} if you need to do that (@pxref{Running the
8294 Linker}).
8295 @end defmac
8297 @ovindex ERL
8298 For tests in Erlang, the @var{input} must be the source code of a module named
8299 @code{conftest}.  @code{AC_COMPILE_IFELSE} generates a @file{conftest.beam}
8300 file that can be interpreted by the Erlang virtual machine (@code{ERL}).  It is
8301 recommended to use @code{AC_LANG_PROGRAM} to specify the test program,
8302 to ensure that the Erlang module has the right name.
8304 @node Running the Linker
8305 @section Running the Linker
8307 To check for a library, a function, or a global variable, Autoconf
8308 @command{configure} scripts try to compile and link a small program that
8309 uses it.  This is unlike Metaconfig, which by default uses @code{nm} or
8310 @code{ar} on the C library to try to figure out which functions are
8311 available.  Trying to link with the function is usually a more reliable
8312 approach because it avoids dealing with the variations in the options
8313 and output formats of @code{nm} and @code{ar} and in the location of the
8314 standard libraries.  It also allows configuring for cross-compilation or
8315 checking a function's runtime behavior if needed.  On the other hand,
8316 it can be slower than scanning the libraries once, but accuracy is more
8317 important than speed.
8319 @code{AC_LINK_IFELSE} is used to compile test programs to test for
8320 functions and global variables.  It is also used by @code{AC_CHECK_LIB}
8321 to check for libraries (@pxref{Libraries}), by adding the library being
8322 checked for to @code{LIBS} temporarily and trying to link a small
8323 program.
8325 @anchor{AC_LINK_IFELSE}
8326 @defmac AC_LINK_IFELSE (@var{input}, @ovar{action-if-true}, @
8327   @ovar{action-if-false})
8328 @acindex{LINK_IFELSE}
8329 Run the compiler (and compilation flags) and the linker of the current
8330 language (@pxref{Language Choice}) on the @var{input}, run the shell
8331 commands @var{action-if-true} on success, @var{action-if-false}
8332 otherwise.  The @var{input} can be made by @code{AC_LANG_PROGRAM} and
8333 friends.
8335 @code{LDFLAGS} and @code{LIBS} are used for linking, in addition to the
8336 current compilation flags.
8338 It is customary to report unexpected failures with
8339 @code{AC_MSG_FAILURE}.  This macro does not try to execute the program;
8340 use @code{AC_RUN_IFELSE} if you need to do that (@pxref{Runtime}).
8341 @end defmac
8343 The @code{AC_LINK_IFELSE} macro cannot be used for Erlang tests, since Erlang
8344 programs are interpreted and do not require linking.
8348 @node Runtime
8349 @section Checking Runtime Behavior
8351 Sometimes you need to find out how a system performs at runtime, such
8352 as whether a given function has a certain capability or bug.  If you
8353 can, make such checks when your program runs instead of when it is
8354 configured.  You can check for things like the machine's endianness when
8355 your program initializes itself.
8357 If you really need to test for a runtime behavior while configuring,
8358 you can write a test program to determine the result, and compile and
8359 run it using @code{AC_RUN_IFELSE}.  Avoid running test programs if
8360 possible, because this prevents people from configuring your package for
8361 cross-compiling.
8363 @anchor{AC_RUN_IFELSE}
8364 @defmac AC_RUN_IFELSE (@var{input}, @ovar{action-if-true}, @
8365   @ovar{action-if-false}, @ovar{action-if-cross-compiling})
8366 @acindex{RUN_IFELSE}
8367 If @var{program} compiles and links successfully and returns an exit
8368 status of 0 when executed, run shell commands @var{action-if-true}.
8369 Otherwise, run shell commands @var{action-if-false}.
8371 The @var{input} can be made by @code{AC_LANG_PROGRAM} and friends.
8372 @code{LDFLAGS} and @code{LIBS} are used for linking, in addition to the
8373 compilation flags of the current language (@pxref{Language Choice}).
8375 If the compiler being used does not produce executables that run on the
8376 system where @command{configure} is being run, then the test program is
8377 not run.  If the optional shell commands @var{action-if-cross-compiling}
8378 are given, they are run instead.  Otherwise, @command{configure} prints
8379 an error message and exits.
8381 In the @var{action-if-false} section, the failing exit status is
8382 available in the shell variable @samp{$?}.  This exit status might be
8383 that of a failed compilation, or it might be that of a failed program
8384 execution.
8386 It is customary to report unexpected failures with
8387 @code{AC_MSG_FAILURE}.
8388 @end defmac
8390 Try to provide a pessimistic default value to use when cross-compiling
8391 makes runtime tests impossible.  You do this by passing the optional
8392 last argument to @code{AC_RUN_IFELSE}.  @command{autoconf} prints a
8393 warning message when creating @command{configure} each time it
8394 encounters a call to @code{AC_RUN_IFELSE} with no
8395 @var{action-if-cross-compiling} argument given.  You may ignore the
8396 warning, though users cannot configure your package for
8397 cross-compiling.  A few of the macros distributed with Autoconf produce
8398 this warning message.
8400 To configure for cross-compiling you can also choose a value for those
8401 parameters based on the canonical system name (@pxref{Manual
8402 Configuration}).  Alternatively, set up a test results cache file with
8403 the correct values for the host system (@pxref{Caching Results}).
8405 @ovindex cross_compiling
8406 To provide a default for calls of @code{AC_RUN_IFELSE} that are embedded
8407 in other macros, including a few of the ones that come with Autoconf,
8408 you can test whether the shell variable @code{cross_compiling} is set to
8409 @samp{yes}, and then use an alternate method to get the results instead
8410 of calling the macros.
8412 It is also permissible to temporarily assign to @code{cross_compiling}
8413 in order to force tests to behave as though they are in a
8414 cross-compilation environment, particularly since this provides a way to
8415 test your @var{action-if-cross-compiling} even when you are not using a
8416 cross-compiler.
8418 @example
8419 # We temporarily set cross-compile mode to force AC_COMPUTE_INT
8420 # to use the slow link-only method
8421 save_cross_compiling=$cross_compiling
8422 cross_compiling=yes
8423 AC_COMPUTE_INT([@dots{}])
8424 cross_compiling=$save_cross_compiling
8425 @end example
8427 A C or C++ runtime test should be portable.
8428 @xref{Portable C and C++}.
8430 Erlang tests must exit themselves the Erlang VM by calling the @code{halt/1}
8431 function: the given status code is used to determine the success of the test
8432 (status is @code{0}) or its failure (status is different than @code{0}), as
8433 explained above.  It must be noted that data output through the standard output
8434 (e.g., using @code{io:format/2}) may be truncated when halting the VM.
8435 Therefore, if a test must output configuration information, it is recommended
8436 to create and to output data into the temporary file named @file{conftest.out},
8437 using the functions of module @code{file}.  The @code{conftest.out} file is
8438 automatically deleted by the @code{AC_RUN_IFELSE} macro.  For instance, a
8439 simplified implementation of Autoconf's @code{AC_ERLANG_SUBST_LIB_DIR}
8440 macro is:
8442 @example
8443 AC_INIT([LibdirTest], [1.0], [bug-libdirtest@@example.org])
8444 AC_ERLANG_NEED_ERL
8445 AC_LANG(Erlang)
8446 AC_RUN_IFELSE(
8447   [AC_LANG_PROGRAM([], [dnl
8448     file:write_file("conftest.out", code:lib_dir()),
8449     halt(0)])],
8450   [echo "code:lib_dir() returned: `cat conftest.out`"],
8451   [AC_MSG_FAILURE([test Erlang program execution failed])])
8452 @end example
8455 @node Systemology
8456 @section Systemology
8457 @cindex Systemology
8459 This section aims at presenting some systems and pointers to
8460 documentation.  It may help you addressing particular problems reported
8461 by users.
8463 @uref{http://www.opengroup.org/susv3, Posix-conforming systems} are
8464 derived from the @uref{http://www.bell-labs.com/history/unix/, Unix
8465 operating system}.
8467 The @uref{http://bhami.com/rosetta.html, Rosetta Stone for Unix}
8468 contains a table correlating the features of various Posix-conforming
8469 systems.  @uref{http://www.levenez.com/unix/, Unix History} is a
8470 simplified diagram of how many Unix systems were derived from each
8471 other.
8473 @uref{http://heirloom.sourceforge.net/, The Heirloom Project}
8474 provides some variants of traditional implementations of Unix utilities.
8476 @table @asis
8477 @item Darwin
8478 @cindex Darwin
8479 Darwin is also known as Mac OS X@.  Beware that the file system @emph{can} be
8480 case-preserving, but case insensitive.  This can cause nasty problems,
8481 since for instance the installation attempt for a package having an
8482 @file{INSTALL} file can result in @samp{make install} report that
8483 nothing was to be done!
8485 That's all dependent on whether the file system is a UFS (case
8486 sensitive) or HFS+ (case preserving).  By default Apple wants you to
8487 install the OS on HFS+.  Unfortunately, there are some pieces of
8488 software which really need to be built on UFS@.  We may want to rebuild
8489 Darwin to have both UFS and HFS+ available (and put the /local/build
8490 tree on the UFS).
8492 @item @acronym{QNX} 4.25
8493 @cindex @acronym{QNX} 4.25
8494 @c FIXME: Please, if you feel like writing something more precise,
8495 @c it'd be great.  In particular, I can't understand the difference with
8496 @c QNX Neutrino.
8497 @acronym{QNX} is a realtime operating system running on Intel architecture
8498 meant to be scalable from the small embedded systems to the hundred
8499 processor super-computer.  It claims to be Posix certified.  More
8500 information is available on the
8501 @uref{http://www.qnx.com/, @acronym{QNX} home page}.
8503 @item Tru64
8504 @cindex Tru64
8505 @uref{http://h30097.www3.hp.com/@/docs/,
8506 Documentation of several versions of Tru64} is available in different
8507 formats.
8509 @item Unix version 7
8510 @cindex Unix version 7
8511 @cindex V7
8512 Officially this was called the ``Seventh Edition'' of ``the @sc{unix}
8513 time-sharing system'' but we use the more-common name ``Unix version 7''.
8514 Documentation is available in the
8515 @uref{http://plan9.bell-labs.com/@/7thEdMan/, Unix Seventh Edition Manual}.
8516 Previous versions of Unix are called ``Unix version 6'', etc., but
8517 they were not as widely used.
8518 @end table
8521 @node Multiple Cases
8522 @section Multiple Cases
8524 Some operations are accomplished in several possible ways, depending on
8525 the OS variant.  Checking for them essentially requires a ``case
8526 statement''.  Autoconf does not directly provide one; however, it is
8527 easy to simulate by using a shell variable to keep track of whether a
8528 way to perform the operation has been found yet.
8530 Here is an example that uses the shell variable @code{fstype} to keep
8531 track of whether the remaining cases need to be checked.
8533 @example
8534 @group
8535 AC_MSG_CHECKING([how to get file system type])
8536 fstype=no
8537 # The order of these tests is important.
8538 AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <sys/statvfs.h>
8539 #include <sys/fstyp.h>]])],
8540                   [AC_DEFINE([FSTYPE_STATVFS], [1],
8541                      [Define if statvfs exists.])
8542                    fstype=SVR4])
8543 if test $fstype = no; then
8544   AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <sys/statfs.h>
8545 #include <sys/fstyp.h>]])],
8546                   [AC_DEFINE([FSTYPE_USG_STATFS], [1],
8547                      [Define if USG statfs.])
8548                    fstype=SVR3])
8550 if test $fstype = no; then
8551   AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <sys/statfs.h>
8552 #include <sys/vmount.h>]])]),
8553                   [AC_DEFINE([FSTYPE_AIX_STATFS], [1],
8554                      [Define if AIX statfs.])
8555                    fstype=AIX])
8557 # (more cases omitted here)
8558 AC_MSG_RESULT([$fstype])
8559 @end group
8560 @end example
8562 @c ====================================================== Results of Tests.
8564 @node Results
8565 @chapter Results of Tests
8567 Once @command{configure} has determined whether a feature exists, what can
8568 it do to record that information?  There are four sorts of things it can
8569 do: define a C preprocessor symbol, set a variable in the output files,
8570 save the result in a cache file for future @command{configure} runs, and
8571 print a message letting the user know the result of the test.
8573 @menu
8574 * Defining Symbols::            Defining C preprocessor symbols
8575 * Setting Output Variables::    Replacing variables in output files
8576 * Special Chars in Variables::  Characters to beware of in variables
8577 * Caching Results::             Speeding up subsequent @command{configure} runs
8578 * Printing Messages::           Notifying @command{configure} users
8579 @end menu
8581 @node Defining Symbols
8582 @section Defining C Preprocessor Symbols
8584 A common action to take in response to a feature test is to define a C
8585 preprocessor symbol indicating the results of the test.  That is done by
8586 calling @code{AC_DEFINE} or @code{AC_DEFINE_UNQUOTED}.
8588 By default, @code{AC_OUTPUT} places the symbols defined by these macros
8589 into the output variable @code{DEFS}, which contains an option
8590 @option{-D@var{symbol}=@var{value}} for each symbol defined.  Unlike in
8591 Autoconf version 1, there is no variable @code{DEFS} defined while
8592 @command{configure} is running.  To check whether Autoconf macros have
8593 already defined a certain C preprocessor symbol, test the value of the
8594 appropriate cache variable, as in this example:
8596 @example
8597 AC_CHECK_FUNC([vprintf], [AC_DEFINE([HAVE_VPRINTF], [1],
8598                           [Define if vprintf exists.])])
8599 if test "$ac_cv_func_vprintf" != yes; then
8600   AC_CHECK_FUNC([_doprnt], [AC_DEFINE([HAVE_DOPRNT], [1],
8601                             [Define if _doprnt exists.])])
8603 @end example
8605 If @code{AC_CONFIG_HEADERS} has been called, then instead of creating
8606 @code{DEFS}, @code{AC_OUTPUT} creates a header file by substituting the
8607 correct values into @code{#define} statements in a template file.
8608 @xref{Configuration Headers}, for more information about this kind of
8609 output.
8611 @defmac AC_DEFINE (@var{variable}, @var{value}, @ovar{description})
8612 @defmacx AC_DEFINE (@var{variable})
8613 @cvindex @var{variable}
8614 @acindex{DEFINE}
8615 Define @var{variable} to @var{value} (verbatim), by defining a C
8616 preprocessor macro for @var{variable}.  @var{variable} should be a C
8617 identifier, optionally suffixed by a parenthesized argument list to
8618 define a C preprocessor macro with arguments.  The macro argument list,
8619 if present, should be a comma-separated list of C identifiers, possibly
8620 terminated by an ellipsis @samp{...} if C99 syntax is employed.
8621 @var{variable} should not contain comments, white space, trigraphs,
8622 backslash-newlines, universal character names, or non-@acronym{ASCII}
8623 characters.
8625 @var{value} may contain backslash-escaped newlines, which will be
8626 preserved if you use @code{AC_CONFIG_HEADERS} but flattened if passed
8627 via @code{@@DEFS@@} (with no effect on the compilation, since the
8628 preprocessor sees only one line in the first place).  @var{value} should
8629 not contain raw newlines.  If you are not using
8630 @code{AC_CONFIG_HEADERS}, @var{value} should not contain any @samp{#}
8631 characters, as @command{make} tends to eat them.  To use a shell
8632 variable, use @code{AC_DEFINE_UNQUOTED} instead.
8634 @var{description} is only useful if you are using
8635 @code{AC_CONFIG_HEADERS}.  In this case, @var{description} is put into
8636 the generated @file{config.h.in} as the comment before the macro define.
8637 The following example defines the C preprocessor variable
8638 @code{EQUATION} to be the string constant @samp{"$a > $b"}:
8640 @example
8641 AC_DEFINE([EQUATION], ["$a > $b"],
8642   [Equation string.])
8643 @end example
8645 If neither @var{value} nor @var{description} are given, then
8646 @var{value} defaults to 1 instead of to the empty string.  This is for
8647 backwards compatibility with older versions of Autoconf, but this usage
8648 is obsolescent and may be withdrawn in future versions of Autoconf.
8650 If the @var{variable} is a literal string, it is passed to
8651 @code{m4_pattern_allow} (@pxref{Forbidden Patterns}).
8653 If multiple @code{AC_DEFINE} statements are executed for the same
8654 @var{variable} name (not counting any parenthesized argument list),
8655 the last one wins.
8656 @end defmac
8658 @defmac AC_DEFINE_UNQUOTED (@var{variable}, @var{value}, @ovar{description})
8659 @defmacx AC_DEFINE_UNQUOTED (@var{variable})
8660 @acindex{DEFINE_UNQUOTED}
8661 @cvindex @var{variable}
8662 Like @code{AC_DEFINE}, but three shell expansions are
8663 performed---once---on @var{variable} and @var{value}: variable expansion
8664 (@samp{$}), command substitution (@samp{`}), and backslash escaping
8665 (@samp{\}).  Single and double quote characters in the value have no
8666 special meaning.  Use this macro instead of @code{AC_DEFINE} when
8667 @var{variable} or @var{value} is a shell variable.  Examples:
8669 @example
8670 AC_DEFINE_UNQUOTED([config_machfile], ["$machfile"],
8671   [Configuration machine file.])
8672 AC_DEFINE_UNQUOTED([GETGROUPS_T], [$ac_cv_type_getgroups],
8673   [getgroups return type.])
8674 AC_DEFINE_UNQUOTED([$ac_tr_hdr], [1],
8675   [Translated header name.])
8676 @end example
8677 @end defmac
8679 Due to a syntactical bizarreness of the Bourne shell, do not use
8680 semicolons to separate @code{AC_DEFINE} or @code{AC_DEFINE_UNQUOTED}
8681 calls from other macro calls or shell code; that can cause syntax errors
8682 in the resulting @command{configure} script.  Use either blanks or
8683 newlines.  That is, do this:
8685 @example
8686 AC_CHECK_HEADER([elf.h],
8687   [AC_DEFINE([SVR4], [1], [System V Release 4]) LIBS="-lelf $LIBS"])
8688 @end example
8690 @noindent
8691 or this:
8693 @example
8694 AC_CHECK_HEADER([elf.h],
8695   [AC_DEFINE([SVR4], [1], [System V Release 4])
8696    LIBS="-lelf $LIBS"])
8697 @end example
8699 @noindent
8700 instead of this:
8702 @example
8703 AC_CHECK_HEADER([elf.h],
8704   [AC_DEFINE([SVR4], [1], [System V Release 4]); LIBS="-lelf $LIBS"])
8705 @end example
8707 @node Setting Output Variables
8708 @section Setting Output Variables
8709 @cindex Output variables
8711 Another way to record the results of tests is to set @dfn{output
8712 variables}, which are shell variables whose values are substituted into
8713 files that @command{configure} outputs.  The two macros below create new
8714 output variables.  @xref{Preset Output Variables}, for a list of output
8715 variables that are always available.
8717 @defmac AC_SUBST (@var{variable}, @ovar{value})
8718 @acindex{SUBST}
8719 Create an output variable from a shell variable.  Make @code{AC_OUTPUT}
8720 substitute the variable @var{variable} into output files (typically one
8721 or more makefiles).  This means that @code{AC_OUTPUT}
8722 replaces instances of @samp{@@@var{variable}@@} in input files with the
8723 value that the shell variable @var{variable} has when @code{AC_OUTPUT}
8724 is called.  The value can contain any non-@code{NUL} character, including
8725 newline.
8726 Variable occurrences should not overlap: e.g., an input file should
8727 not contain @samp{@@@var{var1}@@@var{var2}@@} if @var{var1} and @var{var2}
8728 are variable names.
8729 The substituted value is not rescanned for more output variables;
8730 occurrences of @samp{@@@var{variable}@@} in the value are inserted
8731 literally into the output file.  (The algorithm uses the special marker
8732 @code{|#_!!_#|} internally, so neither the substituted value nor the
8733 output file may contain @code{|#_!!_#|}.)
8735 If @var{value} is given, in addition assign it to @var{variable}.
8737 The string @var{variable} is passed to @code{m4_pattern_allow}
8738 (@pxref{Forbidden Patterns}).
8739 @end defmac
8741 @defmac AC_SUBST_FILE (@var{variable})
8742 @acindex{SUBST_FILE}
8743 Another way to create an output variable from a shell variable.  Make
8744 @code{AC_OUTPUT} insert (without substitutions) the contents of the file
8745 named by shell variable @var{variable} into output files.  This means
8746 that @code{AC_OUTPUT} replaces instances of
8747 @samp{@@@var{variable}@@} in output files (such as @file{Makefile.in})
8748 with the contents of the file that the shell variable @var{variable}
8749 names when @code{AC_OUTPUT} is called.  Set the variable to
8750 @file{/dev/null} for cases that do not have a file to insert.
8751 This substitution occurs only when the @samp{@@@var{variable}@@} is on a
8752 line by itself, optionally surrounded by spaces and tabs.  The
8753 substitution replaces the whole line, including the spaces, tabs, and
8754 the terminating newline.
8756 This macro is useful for inserting makefile fragments containing
8757 special dependencies or other @command{make} directives for particular host
8758 or target types into makefiles.  For example, @file{configure.ac}
8759 could contain:
8761 @example
8762 AC_SUBST_FILE([host_frag])
8763 host_frag=$srcdir/conf/sun4.mh
8764 @end example
8766 @noindent
8767 and then a @file{Makefile.in} could contain:
8769 @example
8770 @@host_frag@@
8771 @end example
8773 The string @var{variable} is passed to @code{m4_pattern_allow}
8774 (@pxref{Forbidden Patterns}).
8775 @end defmac
8777 @cindex Precious Variable
8778 @cindex Variable, Precious
8779 Running @command{configure} in varying environments can be extremely
8780 dangerous.  If for instance the user runs @samp{CC=bizarre-cc
8781 ./configure}, then the cache, @file{config.h}, and many other output
8782 files depend upon @command{bizarre-cc} being the C compiler.  If
8783 for some reason the user runs @command{./configure} again, or if it is
8784 run via @samp{./config.status --recheck}, (@xref{Automatic Remaking},
8785 and @pxref{config.status Invocation}), then the configuration can be
8786 inconsistent, composed of results depending upon two different
8787 compilers.
8789 Environment variables that affect this situation, such as @samp{CC}
8790 above, are called @dfn{precious variables}, and can be declared as such
8791 by @code{AC_ARG_VAR}.
8793 @defmac AC_ARG_VAR (@var{variable}, @var{description})
8794 @acindex{ARG_VAR}
8795 Declare @var{variable} is a precious variable, and include its
8796 @var{description} in the variable section of @samp{./configure --help}.
8798 Being precious means that
8799 @itemize @minus
8800 @item
8801 @var{variable} is substituted via @code{AC_SUBST}.
8803 @item
8804 The value of @var{variable} when @command{configure} was launched is
8805 saved in the cache, including if it was not specified on the command
8806 line but via the environment.  Indeed, while @command{configure} can
8807 notice the definition of @code{CC} in @samp{./configure CC=bizarre-cc},
8808 it is impossible to notice it in @samp{CC=bizarre-cc ./configure},
8809 which, unfortunately, is what most users do.
8811 We emphasize that it is the @emph{initial} value of @var{variable} which
8812 is saved, not that found during the execution of @command{configure}.
8813 Indeed, specifying @samp{./configure FOO=foo} and letting
8814 @samp{./configure} guess that @code{FOO} is @code{foo} can be two
8815 different things.
8817 @item
8818 @var{variable} is checked for consistency between two
8819 @command{configure} runs.  For instance:
8821 @example
8822 $ @kbd{./configure --silent --config-cache}
8823 $ @kbd{CC=cc ./configure --silent --config-cache}
8824 configure: error: `CC' was not set in the previous run
8825 configure: error: changes in the environment can compromise \
8826 the build
8827 configure: error: run `make distclean' and/or \
8828 `rm config.cache' and start over
8829 @end example
8831 @noindent
8832 and similarly if the variable is unset, or if its content is changed.
8833 If the content has white space changes only, then the error is degraded
8834 to a warning only, but the old value is reused.
8836 @item
8837 @var{variable} is kept during automatic reconfiguration
8838 (@pxref{config.status Invocation}) as if it had been passed as a command
8839 line argument, including when no cache is used:
8841 @example
8842 $ @kbd{CC=/usr/bin/cc ./configure var=raboof --silent}
8843 $ @kbd{./config.status --recheck}
8844 running CONFIG_SHELL=/bin/sh /bin/sh ./configure var=raboof \
8845   CC=/usr/bin/cc  --no-create --no-recursion
8846 @end example
8847 @end itemize
8848 @end defmac
8850 @node Special Chars in Variables
8851 @section Special Characters in Output Variables
8852 @cindex Output variables, special characters in
8854 Many output variables are intended to be evaluated both by
8855 @command{make} and by the shell.  Some characters are expanded
8856 differently in these two contexts, so to avoid confusion these
8857 variables' values should not contain any of the following characters:
8859 @example
8860 " # $ & ' ( ) * ; < > ? [ \ ^ ` |
8861 @end example
8863 Also, these variables' values should neither contain newlines, nor start
8864 with @samp{~}, nor contain white space or @samp{:} immediately followed
8865 by @samp{~}.  The values can contain nonempty sequences of white space
8866 characters like tabs and spaces, but each such sequence might
8867 arbitrarily be replaced by a single space during substitution.
8869 These restrictions apply both to the values that @command{configure}
8870 computes, and to the values set directly by the user.  For example, the
8871 following invocations of @command{configure} are problematic, since they
8872 attempt to use special characters within @code{CPPFLAGS} and white space
8873 within @code{$(srcdir)}:
8875 @example
8876 CPPFLAGS='-DOUCH="&\"#$*?"' '../My Source/ouch-1.0/configure'
8878 '../My Source/ouch-1.0/configure' CPPFLAGS='-DOUCH="&\"#$*?"'
8879 @end example
8881 @node Caching Results
8882 @section Caching Results
8883 @cindex Cache
8885 To avoid checking for the same features repeatedly in various
8886 @command{configure} scripts (or in repeated runs of one script),
8887 @command{configure} can optionally save the results of many checks in a
8888 @dfn{cache file} (@pxref{Cache Files}).  If a @command{configure} script
8889 runs with caching enabled and finds a cache file, it reads the results
8890 of previous runs from the cache and avoids rerunning those checks.  As a
8891 result, @command{configure} can then run much faster than if it had to
8892 perform all of the checks every time.
8894 @defmac AC_CACHE_VAL (@var{cache-id}, @var{commands-to-set-it})
8895 @acindex{CACHE_VAL}
8896 Ensure that the results of the check identified by @var{cache-id} are
8897 available.  If the results of the check were in the cache file that was
8898 read, and @command{configure} was not given the @option{--quiet} or
8899 @option{--silent} option, print a message saying that the result was
8900 cached; otherwise, run the shell commands @var{commands-to-set-it}.  If
8901 the shell commands are run to determine the value, the value is
8902 saved in the cache file just before @command{configure} creates its output
8903 files.  @xref{Cache Variable Names}, for how to choose the name of the
8904 @var{cache-id} variable.
8906 The @var{commands-to-set-it} @emph{must have no side effects} except for
8907 setting the variable @var{cache-id}, see below.
8908 @end defmac
8910 @defmac AC_CACHE_CHECK (@var{message}, @var{cache-id}, @
8911   @var{commands-to-set-it})
8912 @acindex{CACHE_CHECK}
8913 A wrapper for @code{AC_CACHE_VAL} that takes care of printing the
8914 messages.  This macro provides a convenient shorthand for the most
8915 common way to use these macros.  It calls @code{AC_MSG_CHECKING} for
8916 @var{message}, then @code{AC_CACHE_VAL} with the @var{cache-id} and
8917 @var{commands} arguments, and @code{AC_MSG_RESULT} with @var{cache-id}.
8919 The @var{commands-to-set-it} @emph{must have no side effects} except for
8920 setting the variable @var{cache-id}, see below.
8921 @end defmac
8923 It is common to find buggy macros using @code{AC_CACHE_VAL} or
8924 @code{AC_CACHE_CHECK}, because people are tempted to call
8925 @code{AC_DEFINE} in the @var{commands-to-set-it}.  Instead, the code that
8926 @emph{follows} the call to @code{AC_CACHE_VAL} should call
8927 @code{AC_DEFINE}, by examining the value of the cache variable.  For
8928 instance, the following macro is broken:
8930 @example
8931 @group
8932 AC_DEFUN([AC_SHELL_TRUE],
8933 [AC_CACHE_CHECK([whether true(1) works], [my_cv_shell_true_works],
8934                 [my_cv_shell_true_works=no
8935                  (true) 2>/dev/null && my_cv_shell_true_works=yes
8936                  if test "$my_cv_shell_true_works" = yes; then
8937                    AC_DEFINE([TRUE_WORKS], [1],
8938                              [Define if `true(1)' works properly.])
8939                  fi])
8941 @end group
8942 @end example
8944 @noindent
8945 This fails if the cache is enabled: the second time this macro is run,
8946 @code{TRUE_WORKS} @emph{will not be defined}.  The proper implementation
8949 @example
8950 @group
8951 AC_DEFUN([AC_SHELL_TRUE],
8952 [AC_CACHE_CHECK([whether true(1) works], [my_cv_shell_true_works],
8953                 [my_cv_shell_true_works=no
8954                  (true) 2>/dev/null && my_cv_shell_true_works=yes])
8955  if test "$my_cv_shell_true_works" = yes; then
8956    AC_DEFINE([TRUE_WORKS], [1],
8957              [Define if `true(1)' works properly.])
8958  fi
8960 @end group
8961 @end example
8963 Also, @var{commands-to-set-it} should not print any messages, for
8964 example with @code{AC_MSG_CHECKING}; do that before calling
8965 @code{AC_CACHE_VAL}, so the messages are printed regardless of whether
8966 the results of the check are retrieved from the cache or determined by
8967 running the shell commands.
8969 @menu
8970 * Cache Variable Names::        Shell variables used in caches
8971 * Cache Files::                 Files @command{configure} uses for caching
8972 * Cache Checkpointing::         Loading and saving the cache file
8973 @end menu
8975 @node Cache Variable Names
8976 @subsection Cache Variable Names
8977 @cindex Cache variable
8979 The names of cache variables should have the following format:
8981 @example
8982 @var{package-prefix}_cv_@var{value-type}_@var{specific-value}_@ovar{additional-options}
8983 @end example
8985 @noindent
8986 for example, @samp{ac_cv_header_stat_broken} or
8987 @samp{ac_cv_prog_gcc_traditional}.  The parts of the variable name are:
8989 @table @asis
8990 @item @var{package-prefix}
8991 An abbreviation for your package or organization; the same prefix you
8992 begin local Autoconf macros with, except lowercase by convention.
8993 For cache values used by the distributed Autoconf macros, this value is
8994 @samp{ac}.
8996 @item @code{_cv_}
8997 Indicates that this shell variable is a cache value.  This string
8998 @emph{must} be present in the variable name, including the leading
8999 underscore.
9001 @item @var{value-type}
9002 A convention for classifying cache values, to produce a rational naming
9003 system.  The values used in Autoconf are listed in @ref{Macro Names}.
9005 @item @var{specific-value}
9006 Which member of the class of cache values this test applies to.
9007 For example, which function (@samp{alloca}), program (@samp{gcc}), or
9008 output variable (@samp{INSTALL}).
9010 @item @var{additional-options}
9011 Any particular behavior of the specific member that this test applies to.
9012 For example, @samp{broken} or @samp{set}.  This part of the name may
9013 be omitted if it does not apply.
9014 @end table
9016 The values assigned to cache variables may not contain newlines.
9017 Usually, their values are Boolean (@samp{yes} or @samp{no}) or the
9018 names of files or functions; so this is not an important restriction.
9020 @node Cache Files
9021 @subsection Cache Files
9023 A cache file is a shell script that caches the results of configure
9024 tests run on one system so they can be shared between configure scripts
9025 and configure runs.  It is not useful on other systems.  If its contents
9026 are invalid for some reason, the user may delete or edit it.
9028 By default, @command{configure} uses no cache file,
9029 to avoid problems caused by accidental
9030 use of stale cache files.
9032 To enable caching, @command{configure} accepts @option{--config-cache} (or
9033 @option{-C}) to cache results in the file @file{config.cache}.
9034 Alternatively, @option{--cache-file=@var{file}} specifies that
9035 @var{file} be the cache file.  The cache file is created if it does not
9036 exist already.  When @command{configure} calls @command{configure} scripts in
9037 subdirectories, it uses the @option{--cache-file} argument so that they
9038 share the same cache.  @xref{Subdirectories}, for information on
9039 configuring subdirectories with the @code{AC_CONFIG_SUBDIRS} macro.
9041 @file{config.status} only pays attention to the cache file if it is
9042 given the @option{--recheck} option, which makes it rerun
9043 @command{configure}.
9045 It is wrong to try to distribute cache files for particular system types.
9046 There is too much room for error in doing that, and too much
9047 administrative overhead in maintaining them.  For any features that
9048 can't be guessed automatically, use the standard method of the canonical
9049 system type and linking files (@pxref{Manual Configuration}).
9051 The site initialization script can specify a site-wide cache file to
9052 use, instead of the usual per-program cache.  In this case, the cache
9053 file gradually accumulates information whenever someone runs a new
9054 @command{configure} script.  (Running @command{configure} merges the new cache
9055 results with the existing cache file.)  This may cause problems,
9056 however, if the system configuration (e.g., the installed libraries or
9057 compilers) changes and the stale cache file is not deleted.
9059 @node Cache Checkpointing
9060 @subsection Cache Checkpointing
9062 If your configure script, or a macro called from @file{configure.ac}, happens
9063 to abort the configure process, it may be useful to checkpoint the cache
9064 a few times at key points using @code{AC_CACHE_SAVE}.  Doing so
9065 reduces the amount of time it takes to rerun the configure script with
9066 (hopefully) the error that caused the previous abort corrected.
9068 @c FIXME: Do we really want to document this guy?
9069 @defmac AC_CACHE_LOAD
9070 @acindex{CACHE_LOAD}
9071 Loads values from existing cache file, or creates a new cache file if a
9072 cache file is not found.  Called automatically from @code{AC_INIT}.
9073 @end defmac
9075 @defmac AC_CACHE_SAVE
9076 @acindex{CACHE_SAVE}
9077 Flushes all cached values to the cache file.  Called automatically from
9078 @code{AC_OUTPUT}, but it can be quite useful to call
9079 @code{AC_CACHE_SAVE} at key points in @file{configure.ac}.
9080 @end defmac
9082 For instance:
9084 @example
9085 @r{ @dots{} AC_INIT, etc. @dots{}}
9086 @group
9087 # Checks for programs.
9088 AC_PROG_CC
9089 AC_PROG_AWK
9090 @r{ @dots{} more program checks @dots{}}
9091 AC_CACHE_SAVE
9092 @end group
9094 @group
9095 # Checks for libraries.
9096 AC_CHECK_LIB([nsl], [gethostbyname])
9097 AC_CHECK_LIB([socket], [connect])
9098 @r{ @dots{} more lib checks @dots{}}
9099 AC_CACHE_SAVE
9100 @end group
9102 @group
9103 # Might abort@dots{}
9104 AM_PATH_GTK([1.0.2], [], [AC_MSG_ERROR([GTK not in path])])
9105 AM_PATH_GTKMM([0.9.5], [], [AC_MSG_ERROR([GTK not in path])])
9106 @end group
9107 @r{ @dots{} AC_OUTPUT, etc. @dots{}}
9108 @end example
9110 @node Printing Messages
9111 @section Printing Messages
9112 @cindex Messages, from @command{configure}
9114 @command{configure} scripts need to give users running them several kinds
9115 of information.  The following macros print messages in ways appropriate
9116 for each kind.  The arguments to all of them get enclosed in shell
9117 double quotes, so the shell performs variable and back-quote
9118 substitution on them.
9120 These macros are all wrappers around the @command{echo} shell command.
9121 They direct output to the appropriate file descriptor (@pxref{File
9122 Descriptor Macros}).
9123 @command{configure} scripts should rarely need to run @command{echo} directly
9124 to print messages for the user.  Using these macros makes it easy to
9125 change how and when each kind of message is printed; such changes need
9126 only be made to the macro definitions and all the callers change
9127 automatically.
9129 To diagnose static issues, i.e., when @command{autoconf} is run, see
9130 @ref{Diagnostic Macros}.
9132 @defmac AC_MSG_CHECKING (@var{feature-description})
9133 @acindex{MSG_CHECKING}
9134 Notify the user that @command{configure} is checking for a particular
9135 feature.  This macro prints a message that starts with @samp{checking }
9136 and ends with @samp{...} and no newline.  It must be followed by a call
9137 to @code{AC_MSG_RESULT} to print the result of the check and the
9138 newline.  The @var{feature-description} should be something like
9139 @samp{whether the Fortran compiler accepts C++ comments} or @samp{for
9140 c89}.
9142 This macro prints nothing if @command{configure} is run with the
9143 @option{--quiet} or @option{--silent} option.
9144 @end defmac
9146 @anchor{AC_MSG_RESULT}
9147 @defmac AC_MSG_RESULT (@var{result-description})
9148 @acindex{MSG_RESULT}
9149 Notify the user of the results of a check.  @var{result-description} is
9150 almost always the value of the cache variable for the check, typically
9151 @samp{yes}, @samp{no}, or a file name.  This macro should follow a call
9152 to @code{AC_MSG_CHECKING}, and the @var{result-description} should be
9153 the completion of the message printed by the call to
9154 @code{AC_MSG_CHECKING}.
9156 This macro prints nothing if @command{configure} is run with the
9157 @option{--quiet} or @option{--silent} option.
9158 @end defmac
9160 @anchor{AC_MSG_NOTICE}
9161 @defmac AC_MSG_NOTICE (@var{message})
9162 @acindex{MSG_NOTICE}
9163 Deliver the @var{message} to the user.  It is useful mainly to print a
9164 general description of the overall purpose of a group of feature checks,
9165 e.g.,
9167 @example
9168 AC_MSG_NOTICE([checking if stack overflow is detectable])
9169 @end example
9171 This macro prints nothing if @command{configure} is run with the
9172 @option{--quiet} or @option{--silent} option.
9173 @end defmac
9175 @anchor{AC_MSG_ERROR}
9176 @defmac AC_MSG_ERROR (@var{error-description}, @ovar{exit-status})
9177 @acindex{MSG_ERROR}
9178 Notify the user of an error that prevents @command{configure} from
9179 completing.  This macro prints an error message to the standard error
9180 output and exits @command{configure} with @var{exit-status} (1 by default).
9181 @var{error-description} should be something like @samp{invalid value
9182 $HOME for \$HOME}.
9184 The @var{error-description} should start with a lower-case letter, and
9185 ``cannot'' is preferred to ``can't''.
9186 @end defmac
9188 @defmac AC_MSG_FAILURE (@var{error-description}, @ovar{exit-status})
9189 @acindex{MSG_FAILURE}
9190 This @code{AC_MSG_ERROR} wrapper notifies the user of an error that
9191 prevents @command{configure} from completing @emph{and} that additional
9192 details are provided in @file{config.log}.  This is typically used when
9193 abnormal results are found during a compilation.
9194 @end defmac
9196 @anchor{AC_MSG_WARN}
9197 @defmac AC_MSG_WARN (@var{problem-description})
9198 @acindex{MSG_WARN}
9199 Notify the @command{configure} user of a possible problem.  This macro
9200 prints the message to the standard error output; @command{configure}
9201 continues running afterward, so macros that call @code{AC_MSG_WARN} should
9202 provide a default (back-up) behavior for the situations they warn about.
9203 @var{problem-description} should be something like @samp{ln -s seems to
9204 make hard links}.
9205 @end defmac
9209 @c ====================================================== Programming in M4.
9211 @node Programming in M4
9212 @chapter Programming in M4
9213 @cindex M4
9215 Autoconf is written on top of two layers: @dfn{M4sugar}, which provides
9216 convenient macros for pure M4 programming, and @dfn{M4sh}, which
9217 provides macros dedicated to shell script generation.
9219 As of this version of Autoconf, these two layers still contain
9220 experimental macros, whose interface might change in the future.  As a
9221 matter of fact, @emph{anything that is not documented must not be used}.
9223 @menu
9224 * M4 Quotation::                Protecting macros from unwanted expansion
9225 * Using autom4te::              The Autoconf executables backbone
9226 * Programming in M4sugar::      Convenient pure M4 macros
9227 * Programming in M4sh::         Common shell Constructs
9228 * File Descriptor Macros::      File descriptor macros for input and output
9229 @end menu
9231 @node M4 Quotation
9232 @section M4 Quotation
9233 @cindex M4 quotation
9234 @cindex quotation
9236 The most common problem with existing macros is an improper quotation.
9237 This section, which users of Autoconf can skip, but which macro writers
9238 @emph{must} read, first justifies the quotation scheme that was chosen
9239 for Autoconf and then ends with a rule of thumb.  Understanding the
9240 former helps one to follow the latter.
9242 @menu
9243 * Active Characters::           Characters that change the behavior of M4
9244 * One Macro Call::              Quotation and one macro call
9245 * Quoting and Parameters::      M4 vs. shell parameters
9246 * Quotation and Nested Macros::  Macros calling macros
9247 * Changequote is Evil::         Worse than INTERCAL: M4 + changequote
9248 * Quadrigraphs::                Another way to escape special characters
9249 * Quotation Rule Of Thumb::     One parenthesis, one quote
9250 @end menu
9252 @node Active Characters
9253 @subsection Active Characters
9255 To fully understand where proper quotation is important, you first need
9256 to know what the special characters are in Autoconf: @samp{#} introduces
9257 a comment inside which no macro expansion is performed, @samp{,}
9258 separates arguments, @samp{[} and @samp{]} are the quotes themselves,
9259 @samp{(} and @samp{)} (which M4 tries to match by pairs), and finally
9260 @samp{$} inside a macro definition.
9262 In order to understand the delicate case of macro calls, we first have
9263 to present some obvious failures.  Below they are ``obvious-ified'',
9264 but when you find them in real life, they are usually in disguise.
9266 Comments, introduced by a hash and running up to the newline, are opaque
9267 tokens to the top level: active characters are turned off, and there is
9268 no macro expansion:
9270 @example
9271 # define([def], ine)
9272 @result{}# define([def], ine)
9273 @end example
9275 Each time there can be a macro expansion, there is a quotation
9276 expansion, i.e., one level of quotes is stripped:
9278 @example
9279 int tab[10];
9280 @result{}int tab10;
9281 [int tab[10];]
9282 @result{}int tab[10];
9283 @end example
9285 Without this in mind, the reader might try hopelessly to use her macro
9286 @code{array}:
9288 @example
9289 define([array], [int tab[10];])
9290 array
9291 @result{}int tab10;
9292 [array]
9293 @result{}array
9294 @end example
9296 @noindent
9297 How can you correctly output the intended results@footnote{Using
9298 @code{defn}.}?
9301 @node One Macro Call
9302 @subsection One Macro Call
9304 Let's proceed on the interaction between active characters and macros
9305 with this small macro, which just returns its first argument:
9307 @example
9308 define([car], [$1])
9309 @end example
9311 @noindent
9312 The two pairs of quotes above are not part of the arguments of
9313 @code{define}; rather, they are understood by the top level when it
9314 tries to find the arguments of @code{define}.  Therefore, assuming
9315 @code{car} is not already defined, it is equivalent to write:
9317 @example
9318 define(car, $1)
9319 @end example
9321 @noindent
9322 But, while it is acceptable for a @file{configure.ac} to avoid unnecessary
9323 quotes, it is bad practice for Autoconf macros which must both be more
9324 robust and also advocate perfect style.
9326 At the top level, there are only two possibilities: either you
9327 quote or you don't:
9329 @example
9330 car(foo, bar, baz)
9331 @result{}foo
9332 [car(foo, bar, baz)]
9333 @result{}car(foo, bar, baz)
9334 @end example
9336 Let's pay attention to the special characters:
9338 @example
9339 car(#)
9340 @error{}EOF in argument list
9341 @end example
9343 The closing parenthesis is hidden in the comment; with a hypothetical
9344 quoting, the top level understood it this way:
9346 @example
9347 car([#)]
9348 @end example
9350 @noindent
9351 Proper quotation, of course, fixes the problem:
9353 @example
9354 car([#])
9355 @result{}#
9356 @end example
9358 Here are more examples:
9360 @example
9361 car(foo, bar)
9362 @result{}foo
9363 car([foo, bar])
9364 @result{}foo, bar
9365 car((foo, bar))
9366 @result{}(foo, bar)
9367 car([(foo], [bar)])
9368 @result{}(foo
9369 define([a], [b])
9370 @result{}
9371 car(a)
9372 @result{}b
9373 car([a])
9374 @result{}b
9375 car([[a]])
9376 @result{}a
9377 car([[[a]]])
9378 @result{}[a]
9379 @end example
9381 @node Quoting and Parameters
9382 @subsection Quoting and Parameters
9384 When M4 encounters @samp{$} within a macro definition, followed
9385 immediately by a character it recognizes (@samp{0}@dots{}@samp{9},
9386 @samp{#}, @samp{@@}, or @samp{*}), it will perform M4 parameter
9387 expansion.  This happens regardless of how many layers of quotes the
9388 parameter expansion is nested within, or even if it occurs in text that
9389 will be rescanned as a comment.
9391 @example
9392 define([none], [$1])
9393 @result{}
9394 define([one], [[$1]])
9395 @result{}
9396 define([two], [[[$1]]])
9397 @result{}
9398 define([comment], [# $1])
9399 @result{}
9400 define([active], [ACTIVE])
9401 @result{}
9402 none([active])
9403 @result{}ACTIVE
9404 one([active])
9405 @result{}active
9406 two([active])
9407 @result{}[active]
9408 comment([active])
9409 @result{}# active
9410 @end example
9412 On the other hand, since autoconf generates shell code, you often want
9413 to output shell variable expansion, rather than performing M4 parameter
9414 expansion.  To do this, you must use M4 quoting to separate the @samp{$}
9415 from the next character in the definition of your macro.  If the macro
9416 definition occurs in single-quoted text, then insert another level of
9417 quoting; if the usage is already inside a double-quoted string, then
9418 split it into concatenated strings.
9420 @example
9421 define([single], [a single-quoted $[]1 definition])
9422 @result{}
9423 define([double], [[a double-quoted $][1 definition]])
9424 @result{}
9425 single
9426 @result{}a single-quoted $1 definition
9427 double
9428 @result{}a double-quoted $1 definition
9429 @end example
9431 Posix states that M4 implementations are free to provide implementation
9432 extensions when @samp{$@{} is encountered in a macro definition.
9433 Autoconf reserves the longer sequence @samp{$@{@{} for use with planned
9434 extensions that will be available in the future @acronym{GNU} M4 2.0,
9435 but guarantees that all other instances of @samp{$@{} will be output
9436 literally.  Therefore, this idiom can also be used to output shell code
9437 parameter references:
9439 @example
9440 define([first], [$@{1@}])first
9441 @result{}$@{1@}
9442 @end example
9444 Posix also states that @samp{$11} should expand to the first parameter
9445 concatenated with a literal @samp{1}, although some versions of
9446 @acronym{GNU} M4 expand the eleventh parameter instead.  For
9447 portability, you should only use single-digit M4 parameter expansion.
9449 With this in mind, we can explore the cases where macros invoke
9450 macros@enddots{}
9452 @node Quotation and Nested Macros
9453 @subsection Quotation and Nested Macros
9455 The examples below use the following macros:
9457 @example
9458 define([car], [$1])
9459 define([active], [ACT, IVE])
9460 define([array], [int tab[10]])
9461 @end example
9463 Each additional embedded macro call introduces other possible
9464 interesting quotations:
9466 @example
9467 car(active)
9468 @result{}ACT
9469 car([active])
9470 @result{}ACT, IVE
9471 car([[active]])
9472 @result{}active
9473 @end example
9475 In the first case, the top level looks for the arguments of @code{car},
9476 and finds @samp{active}.  Because M4 evaluates its arguments
9477 before applying the macro, @samp{active} is expanded, which results in:
9479 @example
9480 car(ACT, IVE)
9481 @result{}ACT
9482 @end example
9484 @noindent
9485 In the second case, the top level gives @samp{active} as first and only
9486 argument of @code{car}, which results in:
9488 @example
9489 active
9490 @result{}ACT, IVE
9491 @end example
9493 @noindent
9494 i.e., the argument is evaluated @emph{after} the macro that invokes it.
9495 In the third case, @code{car} receives @samp{[active]}, which results in:
9497 @example
9498 [active]
9499 @result{}active
9500 @end example
9502 @noindent
9503 exactly as we already saw above.
9505 The example above, applied to a more realistic example, gives:
9507 @example
9508 car(int tab[10];)
9509 @result{}int tab10;
9510 car([int tab[10];])
9511 @result{}int tab10;
9512 car([[int tab[10];]])
9513 @result{}int tab[10];
9514 @end example
9516 @noindent
9517 Huh?  The first case is easily understood, but why is the second wrong,
9518 and the third right?  To understand that, you must know that after
9519 M4 expands a macro, the resulting text is immediately subjected
9520 to macro expansion and quote removal.  This means that the quote removal
9521 occurs twice---first before the argument is passed to the @code{car}
9522 macro, and second after the @code{car} macro expands to the first
9523 argument.
9525 As the author of the Autoconf macro @code{car}, you then consider it to
9526 be incorrect that your users have to double-quote the arguments of
9527 @code{car}, so you ``fix'' your macro.  Let's call it @code{qar} for
9528 quoted car:
9530 @example
9531 define([qar], [[$1]])
9532 @end example
9534 @noindent
9535 and check that @code{qar} is properly fixed:
9537 @example
9538 qar([int tab[10];])
9539 @result{}int tab[10];
9540 @end example
9542 @noindent
9543 Ahhh!  That's much better.
9545 But note what you've done: now that the result of @code{qar} is always
9546 a literal string, the only time a user can use nested macros is if she
9547 relies on an @emph{unquoted} macro call:
9549 @example
9550 qar(active)
9551 @result{}ACT
9552 qar([active])
9553 @result{}active
9554 @end example
9556 @noindent
9557 leaving no way for her to reproduce what she used to do with @code{car}:
9559 @example
9560 car([active])
9561 @result{}ACT, IVE
9562 @end example
9564 @noindent
9565 Worse yet: she wants to use a macro that produces a set of @code{cpp}
9566 macros:
9568 @example
9569 define([my_includes], [#include <stdio.h>])
9570 car([my_includes])
9571 @result{}#include <stdio.h>
9572 qar(my_includes)
9573 @error{}EOF in argument list
9574 @end example
9576 This macro, @code{qar}, because it double quotes its arguments, forces
9577 its users to leave their macro calls unquoted, which is dangerous.
9578 Commas and other active symbols are interpreted by M4 before
9579 they are given to the macro, often not in the way the users expect.
9580 Also, because @code{qar} behaves differently from the other macros,
9581 it's an exception that should be avoided in Autoconf.
9583 @node Changequote is Evil
9584 @subsection @code{changequote} is Evil
9585 @cindex @code{changequote}
9587 The temptation is often high to bypass proper quotation, in particular
9588 when it's late at night.  Then, many experienced Autoconf hackers
9589 finally surrender to the dark side of the force and use the ultimate
9590 weapon: @code{changequote}.
9592 The M4 builtin @code{changequote} belongs to a set of primitives that
9593 allow one to adjust the syntax of the language to adjust it to one's
9594 needs.  For instance, by default M4 uses @samp{`} and @samp{'} as
9595 quotes, but in the context of shell programming (and actually of most
9596 programming languages), that's about the worst choice one can make:
9597 because of strings and back-quoted expressions in shell code (such as
9598 @samp{'this'} and @samp{`that`}), and because of literal characters in usual
9599 programming languages (as in @samp{'0'}), there are many unbalanced
9600 @samp{`} and @samp{'}.  Proper M4 quotation then becomes a nightmare, if
9601 not impossible.  In order to make M4 useful in such a context, its
9602 designers have equipped it with @code{changequote}, which makes it
9603 possible to choose another pair of quotes.  M4sugar, M4sh, Autoconf, and
9604 Autotest all have chosen to use @samp{[} and @samp{]}.  Not especially
9605 because they are unlikely characters, but @emph{because they are
9606 characters unlikely to be unbalanced}.
9608 There are other magic primitives, such as @code{changecom} to specify
9609 what syntactic forms are comments (it is common to see
9610 @samp{changecom(<!--, -->)} when M4 is used to produce HTML pages),
9611 @code{changeword} and @code{changesyntax} to change other syntactic
9612 details (such as the character to denote the @var{n}th argument, @samp{$} by
9613 default, the parentheses around arguments, etc.).
9615 These primitives are really meant to make M4 more useful for specific
9616 domains: they should be considered like command line options:
9617 @option{--quotes}, @option{--comments}, @option{--words}, and
9618 @option{--syntax}.  Nevertheless, they are implemented as M4 builtins, as
9619 it makes M4 libraries self contained (no need for additional options).
9621 There lies the problem@enddots{}
9623 @sp 1
9625 The problem is that it is then tempting to use them in the middle of an
9626 M4 script, as opposed to its initialization.  This, if not carefully
9627 thought out, can lead to disastrous effects: @emph{you are changing the
9628 language in the middle of the execution}.  Changing and restoring the
9629 syntax is often not enough: if you happened to invoke macros in between,
9630 these macros are lost, as the current syntax is probably not
9631 the one they were implemented with.
9633 @c FIXME: I've been looking for a short, real case example, but I
9634 @c lost them all :(
9637 @node Quadrigraphs
9638 @subsection Quadrigraphs
9639 @cindex quadrigraphs
9640 @cindex @samp{@@S|@@}
9641 @cindex @samp{@@&t@@}
9642 @c Info cannot handle `:' in index entries.
9643 @c @cindex @samp{@@<:@@}
9644 @c @cindex @samp{@@:>@@}
9645 @c @cindex @samp{@@%:@@}
9646 @c @cindex @samp{@@@{:@@}
9647 @c @cindex @samp{@@:@}@@}
9649 When writing an Autoconf macro you may occasionally need to generate
9650 special characters that are difficult to express with the standard
9651 Autoconf quoting rules.  For example, you may need to output the regular
9652 expression @samp{[^[]}, which matches any character other than @samp{[}.
9653 This expression contains unbalanced brackets so it cannot be put easily
9654 into an M4 macro.
9656 Additionally, there are a few m4sugar macros (such as @code{m4_split}
9657 and @code{m4_expand}) which internally use special markers in addition
9658 to the regular quoting characters.  If the arguments to these macros
9659 contain the literal strings @samp{-=<@{(} or @samp{)@}>=-}, the macros
9660 might behave incorrectly.
9662 You can work around these problems by using one of the following
9663 @dfn{quadrigraphs}:
9665 @table @samp
9666 @item @@<:@@
9667 @samp{[}
9668 @item @@:>@@
9669 @samp{]}
9670 @item @@S|@@
9671 @samp{$}
9672 @item @@%:@@
9673 @samp{#}
9674 @item @@@{:@@
9675 @samp{(}
9676 @item @@:@}@@
9677 @samp{)}
9678 @item @@&t@@
9679 Expands to nothing.
9680 @end table
9682 Quadrigraphs are replaced at a late stage of the translation process,
9683 after @command{m4} is run, so they do not get in the way of M4 quoting.
9684 For example, the string @samp{^@@<:@@}, independently of its quotation,
9685 appears as @samp{^[} in the output.
9687 The empty quadrigraph can be used:
9689 @itemize @minus
9690 @item to mark trailing spaces explicitly
9692 Trailing spaces are smashed by @command{autom4te}.  This is a feature.
9694 @item to produce quadrigraphs and other strings reserved by m4sugar
9696 For instance @samp{@@<@@&t@@:@@} produces @samp{@@<:@@}.  For a more
9697 contrived example:
9699 @example
9700 m4_define([a], [A])m4_define([b], [B])m4_define([c], [C])dnl
9701 m4_split([a )@}>=- b -=<@{( c])
9702 @result{}[a], [], [B], [], [c]
9703 m4_split([a )@}@@&t@@>=- b -=<@@&t@@@{( c])
9704 @result{}[a], [)@}>=-], [b], [-=<@{(], [c]
9705 @end example
9707 @item to escape @emph{occurrences} of forbidden patterns
9709 For instance you might want to mention @code{AC_FOO} in a comment, while
9710 still being sure that @command{autom4te} still catches unexpanded
9711 @samp{AC_*}.  Then write @samp{AC@@&t@@_FOO}.
9712 @end itemize
9714 The name @samp{@@&t@@} was suggested by Paul Eggert:
9716 @quotation
9717 I should give some credit to the @samp{@@&t@@} pun.  The @samp{&} is my
9718 own invention, but the @samp{t} came from the source code of the
9719 @sc{algol68c} compiler, written by Steve Bourne (of Bourne shell fame),
9720 and which used @samp{mt} to denote the empty string.  In C, it would
9721 have looked like something like:
9723 @example
9724 char const mt[] = "";
9725 @end example
9727 @noindent
9728 but of course the source code was written in Algol 68.
9730 I don't know where he got @samp{mt} from: it could have been his own
9731 invention, and I suppose it could have been a common pun around the
9732 Cambridge University computer lab at the time.
9733 @end quotation
9735 @node Quotation Rule Of Thumb
9736 @subsection Quotation Rule Of Thumb
9738 To conclude, the quotation rule of thumb is:
9740 @center @emph{One pair of quotes per pair of parentheses.}
9742 Never over-quote, never under-quote, in particular in the definition of
9743 macros.  In the few places where the macros need to use brackets
9744 (usually in C program text or regular expressions), properly quote
9745 @emph{the arguments}!
9747 It is common to read Autoconf programs with snippets like:
9749 @example
9750 AC_TRY_LINK(
9751 changequote(<<, >>)dnl
9752 <<#include <time.h>
9753 #ifndef tzname /* For SGI.  */
9754 extern char *tzname[]; /* RS6000 and others reject char **tzname.  */
9755 #endif>>,
9756 changequote([, ])dnl
9757 [atoi (*tzname);], ac_cv_var_tzname=yes, ac_cv_var_tzname=no)
9758 @end example
9760 @noindent
9761 which is incredibly useless since @code{AC_TRY_LINK} is @emph{already}
9762 double quoting, so you just need:
9764 @example
9765 AC_TRY_LINK(
9766 [#include <time.h>
9767 #ifndef tzname /* For SGI.  */
9768 extern char *tzname[]; /* RS6000 and others reject char **tzname.  */
9769 #endif],
9770             [atoi (*tzname);],
9771             [ac_cv_var_tzname=yes],
9772             [ac_cv_var_tzname=no])
9773 @end example
9775 @noindent
9776 The M4-fluent reader might note that these two examples are rigorously
9777 equivalent, since M4 swallows both the @samp{changequote(<<, >>)}
9778 and @samp{<<} @samp{>>} when it @dfn{collects} the arguments: these
9779 quotes are not part of the arguments!
9781 Simplified, the example above is just doing this:
9783 @example
9784 changequote(<<, >>)dnl
9785 <<[]>>
9786 changequote([, ])dnl
9787 @end example
9789 @noindent
9790 instead of simply:
9792 @example
9793 [[]]
9794 @end example
9796 With macros that do not double quote their arguments (which is the
9797 rule), double-quote the (risky) literals:
9799 @example
9800 AC_LINK_IFELSE([AC_LANG_PROGRAM(
9801 [[#include <time.h>
9802 #ifndef tzname /* For SGI.  */
9803 extern char *tzname[]; /* RS6000 and others reject char **tzname.  */
9804 #endif]],
9805                                 [atoi (*tzname);])],
9806                [ac_cv_var_tzname=yes],
9807                [ac_cv_var_tzname=no])
9808 @end example
9810 Please note that the macro @code{AC_TRY_LINK} is obsolete, so you really
9811 should be using @code{AC_LINK_IFELSE} instead.
9813 @xref{Quadrigraphs}, for what to do if you run into a hopeless case
9814 where quoting does not suffice.
9816 When you create a @command{configure} script using newly written macros,
9817 examine it carefully to check whether you need to add more quotes in
9818 your macros.  If one or more words have disappeared in the M4
9819 output, you need more quotes.  When in doubt, quote.
9821 However, it's also possible to put on too many layers of quotes.  If
9822 this happens, the resulting @command{configure} script may contain
9823 unexpanded macros.  The @command{autoconf} program checks for this problem
9824 by looking for the string @samp{AC_} in @file{configure}.  However, this
9825 heuristic does not work in general: for example, it does not catch
9826 overquoting in @code{AC_DEFINE} descriptions.
9829 @c ---------------------------------------- Using autom4te
9831 @node Using autom4te
9832 @section Using @command{autom4te}
9834 The Autoconf suite, including M4sugar, M4sh, and Autotest, in addition
9835 to Autoconf per se, heavily rely on M4.  All these different uses
9836 revealed common needs factored into a layer over M4:
9837 @command{autom4te}@footnote{
9839 Yet another great name from Lars J. Aas.
9843 @command{autom4te} is a preprocessor that is like @command{m4}.
9844 It supports M4 extensions designed for use in tools like Autoconf.
9846 @menu
9847 * autom4te Invocation::         A @acronym{GNU} M4 wrapper
9848 * Customizing autom4te::        Customizing the Autoconf package
9849 @end menu
9851 @node autom4te Invocation
9852 @subsection Invoking @command{autom4te}
9854 The command line arguments are modeled after M4's:
9856 @example
9857 autom4te @var{options} @var{files}
9858 @end example
9860 @noindent
9861 @evindex M4
9862 where the @var{files} are directly passed to @command{m4}.  By default,
9863 @acronym{GNU} M4 is found during configuration, but the environment
9864 variable
9865 @env{M4} can be set to tell @command{autom4te} where to look.  In addition
9866 to the regular expansion, it handles the replacement of the quadrigraphs
9867 (@pxref{Quadrigraphs}), and of @samp{__oline__}, the current line in the
9868 output.  It supports an extended syntax for the @var{files}:
9870 @table @file
9871 @item @var{file}.m4f
9872 This file is an M4 frozen file.  Note that @emph{all the previous files
9873 are ignored}.  See the option @option{--melt} for the rationale.
9875 @item @var{file}?
9876 If found in the library path, the @var{file} is included for expansion,
9877 otherwise it is ignored instead of triggering a failure.
9878 @end table
9880 @sp 1
9882 Of course, it supports the Autoconf common subset of options:
9884 @table @option
9885 @item --help
9886 @itemx -h
9887 Print a summary of the command line options and exit.
9889 @item --version
9890 @itemx -V
9891 Print the version number of Autoconf and exit.
9893 @item --verbose
9894 @itemx -v
9895 Report processing steps.
9897 @item --debug
9898 @itemx -d
9899 Don't remove the temporary files and be even more verbose.
9901 @item --include=@var{dir}
9902 @itemx -I @var{dir}
9903 Also look for input files in @var{dir}.  Multiple invocations
9904 accumulate.
9906 @item --output=@var{file}
9907 @itemx -o @var{file}
9908 Save output (script or trace) to @var{file}.  The file @option{-} stands
9909 for the standard output.
9910 @end table
9912 @sp 1
9914 As an extension of @command{m4}, it includes the following options:
9916 @table @option
9917 @item --warnings=@var{category}
9918 @itemx -W @var{category}
9919 @evindex WARNINGS
9920 @c FIXME: Point to the M4sugar macros, not Autoconf's.
9921 Report the warnings related to @var{category} (which can actually be a
9922 comma separated list).  @xref{Reporting Messages}, macro
9923 @code{AC_DIAGNOSE}, for a comprehensive list of categories.  Special
9924 values include:
9926 @table @samp
9927 @item all
9928 report all the warnings
9930 @item none
9931 report none
9933 @item error
9934 treats warnings as errors
9936 @item no-@var{category}
9937 disable warnings falling into @var{category}
9938 @end table
9940 Warnings about @samp{syntax} are enabled by default, and the environment
9941 variable @env{WARNINGS}, a comma separated list of categories, is
9942 honored.  @samp{autom4te -W @var{category}} actually
9943 behaves as if you had run:
9945 @example
9946 autom4te --warnings=syntax,$WARNINGS,@var{category}
9947 @end example
9949 @noindent
9950 For example, if you want to disable defaults and @env{WARNINGS}
9951 of @command{autom4te}, but enable the warnings about obsolete
9952 constructs, you would use @option{-W none,obsolete}.
9954 @cindex Back trace
9955 @cindex Macro invocation stack
9956 @command{autom4te} displays a back trace for errors, but not for
9957 warnings; if you want them, just pass @option{-W error}.
9959 @item --melt
9960 @itemx -M
9961 Do not use frozen files.  Any argument @code{@var{file}.m4f} is
9962 replaced by @code{@var{file}.m4}.  This helps tracing the macros which
9963 are executed only when the files are frozen, typically
9964 @code{m4_define}.  For instance, running:
9966 @example
9967 autom4te --melt 1.m4 2.m4f 3.m4 4.m4f input.m4
9968 @end example
9970 @noindent
9971 is roughly equivalent to running:
9973 @example
9974 m4 1.m4 2.m4 3.m4 4.m4 input.m4
9975 @end example
9977 @noindent
9978 while
9980 @example
9981 autom4te 1.m4 2.m4f 3.m4 4.m4f input.m4
9982 @end example
9984 @noindent
9985 is equivalent to:
9987 @example
9988 m4 --reload-state=4.m4f input.m4
9989 @end example
9991 @item --freeze
9992 @itemx -F
9993 Produce a frozen state file.  @command{autom4te} freezing is stricter
9994 than M4's: it must produce no warnings, and no output other than empty
9995 lines (a line with white space is @emph{not} empty) and comments
9996 (starting with @samp{#}).  Unlike @command{m4}'s similarly-named option,
9997 this option takes no argument:
9999 @example
10000 autom4te 1.m4 2.m4 3.m4 --freeze --output=3.m4f
10001 @end example
10003 @noindent
10004 corresponds to
10006 @example
10007 m4 1.m4 2.m4 3.m4 --freeze-state=3.m4f
10008 @end example
10010 @item --mode=@var{octal-mode}
10011 @itemx -m @var{octal-mode}
10012 Set the mode of the non-traces output to @var{octal-mode}; by default
10013 @samp{0666}.
10014 @end table
10016 @sp 1
10018 @cindex @file{autom4te.cache}
10019 As another additional feature over @command{m4}, @command{autom4te}
10020 caches its results.  @acronym{GNU} M4 is able to produce a regular
10021 output and traces at the same time.  Traces are heavily used in the
10022 @acronym{GNU} Build System: @command{autoheader} uses them to build
10023 @file{config.h.in}, @command{autoreconf} to determine what
10024 @acronym{GNU} Build System components are used, @command{automake} to
10025 ``parse'' @file{configure.ac} etc.  To avoid recomputation,
10026 traces are cached while performing regular expansion,
10027 and conversely.  This cache is (actually, the caches are) stored in
10028 the directory @file{autom4te.cache}.  @emph{It can safely be removed}
10029 at any moment (especially if for some reason @command{autom4te}
10030 considers it trashed).
10032 @table @option
10033 @item --cache=@var{directory}
10034 @itemx -C @var{directory}
10035 Specify the name of the directory where the result should be cached.
10036 Passing an empty value disables caching.  Be sure to pass a relative
10037 file name, as for the time being, global caches are not supported.
10039 @item --no-cache
10040 Don't cache the results.
10042 @item --force
10043 @itemx -f
10044 If a cache is used, consider it obsolete (but update it anyway).
10045 @end table
10047 @sp 1
10049 Because traces are so important to the @acronym{GNU} Build System,
10050 @command{autom4te} provides high level tracing features as compared to
10051 M4, and helps exploiting the cache:
10053 @table @option
10054 @item --trace=@var{macro}[:@var{format}]
10055 @itemx -t @var{macro}[:@var{format}]
10056 Trace the invocations of @var{macro} according to the @var{format}.
10057 Multiple @option{--trace} arguments can be used to list several macros.
10058 Multiple @option{--trace} arguments for a single macro are not
10059 cumulative; instead, you should just make @var{format} as long as
10060 needed.
10062 The @var{format} is a regular string, with newlines if desired, and
10063 several special escape codes.  It defaults to @samp{$f:$l:$n:$%}.  It can
10064 use the following special escapes:
10066 @table @samp
10067 @item $$
10068 The character @samp{$}.
10070 @item $f
10071 The file name from which @var{macro} is called.
10073 @item $l
10074 The line number from which @var{macro} is called.
10076 @item $d
10077 The depth of the @var{macro} call.  This is an M4 technical detail that
10078 you probably don't want to know about.
10080 @item $n
10081 The name of the @var{macro}.
10083 @item $@var{num}
10084 The @var{num}th argument of the call to @var{macro}.
10086 @item $@@
10087 @itemx $@var{sep}@@
10088 @itemx $@{@var{separator}@}@@
10089 All the arguments passed to @var{macro}, separated by the character
10090 @var{sep} or the string @var{separator} (@samp{,} by default).  Each
10091 argument is quoted, i.e., enclosed in a pair of square brackets.
10093 @item $*
10094 @itemx $@var{sep}*
10095 @itemx $@{@var{separator}@}*
10096 As above, but the arguments are not quoted.
10098 @item $%
10099 @itemx $@var{sep}%
10100 @itemx $@{@var{separator}@}%
10101 As above, but the arguments are not quoted, all new line characters in
10102 the arguments are smashed, and the default separator is @samp{:}.
10104 The escape @samp{$%} produces single-line trace outputs (unless you put
10105 newlines in the @samp{separator}), while @samp{$@@} and @samp{$*} do
10106 not.
10107 @end table
10109 @xref{autoconf Invocation}, for examples of trace uses.
10111 @item --preselect=@var{macro}
10112 @itemx -p @var{macro}
10113 Cache the traces of @var{macro}, but do not enable traces.  This is
10114 especially important to save CPU cycles in the future.  For instance,
10115 when invoked, @command{autoconf} preselects all the macros that
10116 @command{autoheader}, @command{automake}, @command{autoreconf}, etc.,
10117 trace, so that running @command{m4} is not needed to trace them: the
10118 cache suffices.  This results in a huge speed-up.
10119 @end table
10121 @sp 1
10123 @cindex Autom4te Library
10124 Finally, @command{autom4te} introduces the concept of @dfn{Autom4te
10125 libraries}.  They consists in a powerful yet extremely simple feature:
10126 sets of combined command line arguments:
10128 @table @option
10129 @item --language=@var{language}
10130 @itemx -l @var{language}
10131 Use the @var{language} Autom4te library.  Current languages include:
10133 @table @code
10134 @item M4sugar
10135 create M4sugar output.
10137 @item M4sh
10138 create M4sh executable shell scripts.
10140 @item Autotest
10141 create Autotest executable test suites.
10143 @item Autoconf-without-aclocal-m4
10144 create Autoconf executable configure scripts without
10145 reading @file{aclocal.m4}.
10147 @item Autoconf
10148 create Autoconf executable configure scripts.  This language inherits
10149 all the characteristics of @code{Autoconf-without-aclocal-m4} and
10150 additionally reads @file{aclocal.m4}.
10151 @end table
10153 @item --prepend-include=@var{dir}
10154 @itemx -B @var{dir}
10155 Prepend directory @var{dir} to the search path.  This is used to include
10156 the language-specific files before any third-party macros.
10158 @end table
10160 @cindex @file{autom4te.cfg}
10161 As an example, if Autoconf is installed in its default location,
10162 @file{/usr/local}, the command @samp{autom4te -l m4sugar foo.m4} is
10163 strictly equivalent to the command:
10165 @example
10166 autom4te --prepend-include /usr/local/share/autoconf \
10167   m4sugar/m4sugar.m4f --warnings syntax foo.m4
10168 @end example
10170 @noindent
10171 Recursive expansion applies here: the command @samp{autom4te -l m4sh foo.m4}
10172 is the same as @samp{autom4te --language M4sugar m4sugar/m4sh.m4f
10173 foo.m4}, i.e.:
10175 @example
10176 autom4te --prepend-include /usr/local/share/autoconf \
10177   m4sugar/m4sugar.m4f m4sugar/m4sh.m4f --mode 777 foo.m4
10178 @end example
10180 @noindent
10181 The definition of the languages is stored in @file{autom4te.cfg}.
10183 @node Customizing autom4te
10184 @subsection Customizing @command{autom4te}
10186 One can customize @command{autom4te} via @file{~/.autom4te.cfg} (i.e.,
10187 as found in the user home directory), and @file{./.autom4te.cfg} (i.e.,
10188 as found in the directory from which @command{autom4te} is run).  The
10189 order is first reading @file{autom4te.cfg}, then @file{~/.autom4te.cfg},
10190 then @file{./.autom4te.cfg}, and finally the command line arguments.
10192 In these text files, comments are introduced with @code{#}, and empty
10193 lines are ignored.  Customization is performed on a per-language basis,
10194 wrapped in between a @samp{begin-language: "@var{language}"},
10195 @samp{end-language: "@var{language}"} pair.
10197 Customizing a language stands for appending options (@pxref{autom4te
10198 Invocation}) to the current definition of the language.  Options, and
10199 more generally arguments, are introduced by @samp{args:
10200 @var{arguments}}.  You may use the traditional shell syntax to quote the
10201 @var{arguments}.
10203 As an example, to disable Autoconf caches (@file{autom4te.cache})
10204 globally, include the following lines in @file{~/.autom4te.cfg}:
10206 @verbatim
10207 ## ------------------ ##
10208 ## User Preferences.  ##
10209 ## ------------------ ##
10211 begin-language: "Autoconf-without-aclocal-m4"
10212 args: --no-cache
10213 end-language: "Autoconf-without-aclocal-m4"
10214 @end verbatim
10217 @node Programming in M4sugar
10218 @section Programming in M4sugar
10220 @cindex M4sugar
10221 M4 by itself provides only a small, but sufficient, set of all-purpose
10222 macros.  M4sugar introduces additional generic macros.  Its name was
10223 coined by Lars J. Aas: ``Readability And Greater Understanding Stands 4
10224 M4sugar''.
10226 M4sugar reserves the macro namespace @samp{^_m4_} for internal use, and
10227 the macro namespace @samp{^m4_} for M4sugar macros.  You should not
10228 define your own macros into these namespaces.
10230 @menu
10231 * Redefined M4 Macros::         M4 builtins changed in M4sugar
10232 * Diagnostic Macros::           Diagnostic messages from M4sugar
10233 * Diversion support::           Diversions in M4sugar
10234 * Conditional constructs::      Conditions in M4
10235 * Looping constructs::          Iteration in M4
10236 * Evaluation Macros::           More quotation and evaluation control
10237 * Text processing Macros::      String manipulation in M4
10238 * Number processing Macros::    Arithmetic computation in M4
10239 * Set manipulation Macros::     Set manipulation in M4
10240 * Forbidden Patterns::          Catching unexpanded macros
10241 @end menu
10243 @node Redefined M4 Macros
10244 @subsection Redefined M4 Macros
10246 @msindex{builtin}
10247 @msindex{changecom}
10248 @msindex{changequote}
10249 @msindex{debugfile}
10250 @msindex{debugmode}
10251 @msindex{decr}
10252 @msindex{define}
10253 @msindex{divnum}
10254 @msindex{dumpdef}
10255 @msindex{errprint}
10256 @msindex{esyscmd}
10257 @msindex{eval}
10258 @msindex{format}
10259 @msindex{ifdef}
10260 @msindex{incr}
10261 @msindex{index}
10262 @msindex{indir}
10263 @msindex{len}
10264 @msindex{pushdef}
10265 @msindex{shift}
10266 @msindex{substr}
10267 @msindex{syscmd}
10268 @msindex{sysval}
10269 @msindex{traceoff}
10270 @msindex{traceon}
10271 @msindex{translit}
10272 With a few exceptions, all the M4 native macros are moved in the
10273 @samp{m4_} pseudo-namespace, e.g., M4sugar renames @code{define} as
10274 @code{m4_define} etc.
10276 The list of macros unchanged from M4, except for their name, is:
10277 @itemize @minus
10278 @item m4_builtin
10279 @item m4_changecom
10280 @item m4_changequote
10281 @item m4_debugfile
10282 @item m4_debugmode
10283 @item m4_decr
10284 @item m4_define
10285 @item m4_divnum
10286 @item m4_dumpdef
10287 @item m4_errprint
10288 @item m4_esyscmd
10289 @item m4_eval
10290 @item m4_format
10291 @item m4_ifdef
10292 @item m4_incr
10293 @item m4_index
10294 @item m4_indir
10295 @item m4_len
10296 @item m4_pushdef
10297 @item m4_shift
10298 @item m4_substr
10299 @item m4_syscmd
10300 @item m4_sysval
10301 @item m4_traceoff
10302 @item m4_traceon
10303 @item m4_translit
10304 @end itemize
10306 Some M4 macros are redefined, and are slightly incompatible with their
10307 native equivalent.
10309 @defmac __file__
10310 @defmacx __line__
10311 @MSindex __file__
10312 @MSindex __line__
10313 All M4 macros starting with @samp{__} retain their original name: for
10314 example, no @code{m4__file__} is defined.
10315 @end defmac
10317 @defmac __oline__
10318 @MSindex __oline__
10319 This is not technically a macro, but a feature of Autom4te.  The
10320 sequence @code{__oline__} can be used similarly to the other m4sugar
10321 location macros, but rather than expanding to the location of the input
10322 file, it is translated to the line number where it appears in the output
10323 file after all other M4 expansions.
10324 @end defmac
10326 @defmac dnl
10327 @MSindex dnl
10328 This macro kept its original name: no @code{m4_dnl} is defined.
10329 @end defmac
10331 @defmac m4_bpatsubst (@var{string}, @var{regexp}, @ovar{replacement})
10332 @msindex{bpatsubst}
10333 This macro corresponds to @code{patsubst}.  The name @code{m4_patsubst}
10334 is kept for future versions of M4sugar, once @acronym{GNU} M4 2.0 is
10335 released and supports extended regular expression syntax.
10336 @end defmac
10338 @defmac m4_bregexp (@var{string}, @var{regexp}, @ovar{replacement})
10339 @msindex{bregexp}
10340 This macro corresponds to @code{regexp}.  The name @code{m4_regexp}
10341 is kept for future versions of M4sugar, once @acronym{GNU} M4 2.0 is
10342 released and supports extended regular expression syntax.
10343 @end defmac
10345 @defmac m4_defn (@var{macro}@dots{})
10346 @msindex{defn}
10347 This macro fails if @var{macro} is not defined, even when using older
10348 versions of M4 that did not warn.  See @code{m4_undefine}.
10349 Unfortunately, in order to support these older versions of M4, there are
10350 some situations involving unbalanced quotes where concatenating multiple
10351 macros together will work in newer M4 but not in m4sugar; use
10352 quadrigraphs to work around this.
10353 @end defmac
10355 @defmac m4_divert (@var{diversion})
10356 @msindex{divert}
10357 M4sugar relies heavily on diversions, so rather than behaving as a
10358 primitive, @code{m4_divert} behaves like:
10359 @example
10360 m4_divert_pop()m4_divert_push([@var{diversion}])
10361 @end example
10362 @noindent
10363 @xref{Diversion support}, for more details about the use of the
10364 diversion stack.
10365 @end defmac
10367 @defmac m4_exit (@var{exit-status})
10368 @msindex{exit}
10369 This macro corresponds to @code{m4exit}.
10370 @end defmac
10372 @defmac m4_if (@var{comment})
10373 @defmacx m4_if (@var{string-1}, @var{string-2}, @var{equal}, @ovar{not-equal})
10374 @defmacx m4_if (@var{string-1}, @var{string-2}, @var{equal}, @dots{})
10375 @msindex{if}
10376 This macro corresponds to @code{ifelse}.  @var{string-1} and
10377 @var{string-2} are compared literally, so usually one of the two
10378 arguments is passed unquoted.  @xref{Conditional constructs}, for more
10379 conditional idioms.
10380 @end defmac
10382 @defmac m4_include (@var{file})
10383 @defmacx m4_sinclude (@var{file})
10384 @msindex{include}
10385 @msindex{sinclude}
10386 Like the M4 builtins, but warn against multiple inclusions of @var{file}.
10387 @end defmac
10389 @defmac m4_mkstemp (@var{template})
10390 @defmacx m4_maketemp (@var{template})
10391 @msindex{maketemp}
10392 @msindex{mkstemp}
10393 Posix requires @code{maketemp} to replace the trailing @samp{X}
10394 characters in @var{template} with the process id, without regards to the
10395 existence of a file by that name, but this a security hole.  When this
10396 was pointed out to the Posix folks, they agreed to invent a new macro
10397 @code{mkstemp} that always creates a uniquely named file, but not all
10398 versions of @acronym{GNU} M4 support the new macro.  In M4sugar,
10399 @code{m4_maketemp} and @code{m4_mkstemp} are synonyms for each other,
10400 and both have the secure semantics regardless of which macro the
10401 underlying M4 provides.
10402 @end defmac
10404 @defmac m4_popdef (@var{macro}@dots{})
10405 @msindex{popdef}
10406 This macro fails if @var{macro} is not defined, even when using older
10407 versions of M4 that did not warn.  See @code{m4_undefine}.
10408 @end defmac
10410 @defmac m4_undefine (@var{macro}@dots{})
10411 @msindex{undefine}
10412 This macro fails if @var{macro} is not defined, even when using older
10413 versions of M4 that did not warn.  Use
10415 @example
10416 m4_ifdef([@var{macro}], [m4_undefine([@var{macro}])])
10417 @end example
10419 @noindent
10420 if you are not sure whether @var{macro} is defined.
10421 @end defmac
10423 @defmac m4_undivert (@var{diversion})
10424 @msindex{undivert}
10425 Unlike the M4 builtin, only one diversion can be undiverted per
10426 invocation.  Also, since the M4sugar diversion stack prefers named
10427 diversions, the use of @code{m4_undivert} to include files is risky.
10428 @xref{Diversion support}, for more details about the use of the
10429 diversion stack.
10430 @end defmac
10432 @defmac m4_wrap (@var{text})
10433 @defmacx m4_wrap_lifo (@var{text})
10434 @msindex{wrap}
10435 @msindex{wrap_lifo}
10436 These macros correspond to @code{m4wrap}.  Posix requires arguments of
10437 multiple wrap calls to be reprocessed at @acronym{EOF} in the same order
10438 as the original calls (first-in, first-out).  @acronym{GNU} M4 versions
10439 through 1.4.10, however, reprocess them in reverse order (last-in,
10440 first-out).  Both orders are useful, therefore, you can rely on
10441 @code{m4_wrap} to provide FIFO semantics and @code{m4_wrap_lifo} for
10442 LIFO semantics, regardless of the underlying @acronym{GNU} M4 version.
10444 Unlike the @acronym{GNU} M4 builtin, these macros only recognize one
10445 argument, and avoid token pasting between consecutive invocations.  On
10446 the other hand, nested calls to @code{m4_wrap} from within wrapped text
10447 work just as in the builtin.
10448 @end defmac
10451 @node Diagnostic Macros
10452 @subsection Diagnostic messages from M4sugar
10453 @cindex Messages, from @command{M4sugar}
10455 When macros statically diagnose abnormal situations, benign or fatal,
10456 they should report them using these macros.  For issuing dynamic issues,
10457 i.e., when @command{configure} is run, see @ref{Printing Messages}.
10459 @defmac m4_assert (@var{expression}, @dvar{exit-status, 1})
10460 @msindex{assert}
10461 Assert that the arithmetic @var{expression} evaluates to non-zero.
10462 Otherwise, issue a fatal error, and exit @command{autom4te} with
10463 @var{exit-status}.
10464 @end defmac
10466 @defmac m4_errprintn (@var{message})
10467 @msindex{errprintn}
10468 Similar to the builtin @code{m4_errprint}, except that a newline is
10469 guaranteed after @var{message}.
10470 @end defmac
10472 @anchor{m4_fatal}
10473 @defmac m4_fatal (@var{message})
10474 @msindex{fatal}
10475 Report a severe error @var{message} prefixed with the current location,
10476 and have @command{autom4te} die.
10477 @end defmac
10479 @defmac m4_location
10480 @msindex{location}
10481 Useful as a prefix in a message line.  Short for:
10482 @example
10483 __file__:__line__
10484 @end example
10485 @end defmac
10487 @anchor{m4_warn}
10488 @defmac m4_warn (@var{category}, @var{message})
10489 @msindex{warn}
10490 Report @var{message} as a warning (or as an error if requested by the
10491 user) if warnings of the @var{category} are turned on.  If the message
10492 is emitted, it is prefixed with the current location, and followed by a
10493 call trace of all macros defined via @code{AC_DEFUN} used to get to the
10494 current expansion.  You are encouraged to use standard categories, which
10495 currently include:
10497 @table @samp
10498 @item all
10499 messages that don't fall into one of the following categories.  Use of an
10500 empty @var{category} is equivalent.
10502 @item cross
10503 related to cross compilation issues.
10505 @item obsolete
10506 use of an obsolete construct.
10508 @item syntax
10509 dubious syntactic constructs, incorrectly ordered macro calls.
10510 @end table
10511 @end defmac
10514 @node Diversion support
10515 @subsection Diversion support
10517 M4sugar makes heavy use of diversions, because it is often the case that
10518 text that must appear early in the output is not discovered until late
10519 in the input.  Additionally, some of the topological sorting algorithms
10520 used in resolving macro dependencies use diversions.  Therefore, most
10521 macros should not need to change diversions directly, but rather rely on
10522 higher-level M4sugar macros to manage diversions transparently.
10524 To make diversion management easier, M4sugar uses the concept of named
10525 diversions.  Rather than using diversion numbers directly, it is nicer
10526 to associate a name with each diversion; the diversion number associated
10527 with a particular diversion name is an implementation detail, so you
10528 should only use diversion names.  In general, you should not output text
10529 to a named diversion until after calling the appropriate initialization
10530 routine for your language (@code{m4_init}, @code{AS_INIT},
10531 @code{AT_INIT}, @dots{}), although there are some exceptions documented
10532 below.
10534 M4sugar defines two named diversions.
10535 @table @code
10536 @item KILL
10537 Text written to this diversion is discarded.  This is the default
10538 diversion once M4sugar is initialized.
10539 @item GROW
10540 This diversion is used behind the scenes by topological sorting macros,
10541 such as @code{AC_REQUIRE}.
10542 @end table
10544 M4sh adds several more named diversions.
10545 @table @code
10546 @item BINSH
10547 This diversion is reserved for the @samp{#!} interpreter line.
10548 @item HEADER-REVISION
10549 This diversion holds text from @code{AC_REVISION}.
10550 @item HEADER-COMMENT
10551 This diversion holds comments about the purpose of a file.
10552 @item HEADER-COPYRIGHT
10553 This diversion is managed by @code{AC_COPYRIGHT}.
10554 @item M4SH-SANITIZE
10555 This diversion contains M4sh sanitization code, used to ensure M4sh is
10556 executing in a reasonable shell environment.
10557 @item M4SH-INIT
10558 This diversion contains M4sh initialization code, initializing variables
10559 that are required by other M4sh macros.
10560 @item BODY
10561 This diversion contains the body of the shell code, and is the default
10562 diversion once M4sh is initialized.
10563 @end table
10565 Autotest inherits diversions from M4sh, and changes the default
10566 diversion from @code{BODY} back to @code{KILL}.  It also adds several
10567 more named diversions, with the following subset designed for developer
10568 use.
10569 @table @code
10570 @item PREPARE_TESTS
10571 This diversion contains initialization sequences which are executed
10572 after @file{atconfig} and @file{atlocal}, and after all command line
10573 arguments have been parsed, but prior to running any tests.  It can be
10574 used to set up state that is required across all tests.  This diversion
10575 will work even before @code{AT_INIT}.
10576 @end table
10578 For now, the named diversions of Autoconf and Autoheader, and the
10579 remaining diversions of Autotest, are not documented.  In other words,
10580 intentionally outputting text into an undocumented diversion is subject
10581 to breakage in a future release of Autoconf.
10583 @defmac m4_divert_once (@var{diversion}, @ovar{content})
10584 @msindex{divert_once}
10585 Similar to @code{m4_divert_text}, except that @var{content} is only
10586 output to @var{diversion} if this is the first time that
10587 @code{m4_divert_once} has been called with its particular arguments.
10588 @end defmac
10590 @defmac m4_divert_pop (@ovar{diversion})
10591 @msindex{divert_pop}
10592 If provided, check that the current diversion is indeed @var{diversion}.
10593 Then change to the diversion located earlier on the stack, giving an
10594 error if an attempt is made to pop beyond the initial m4sugar diversion
10595 of @code{KILL}.
10596 @end defmac
10598 @defmac m4_divert_push (@var{diversion})
10599 @msindex{divert_push}
10600 Remember the former diversion on the diversion stack, and output
10601 subsequent text into @var{diversion}.  M4sugar maintains a diversion
10602 stack, and issues an error if there is not a matching pop for every
10603 push.
10604 @end defmac
10606 @defmac m4_divert_text (@var{diversion}, @ovar{content})
10607 @msindex{divert_text}
10608 Output @var{content} and a newline into @var{diversion}, without
10609 affecting the current diversion.  Shorthand for:
10610 @example
10611 m4_divert_push([@var{diversion}])@var{content}
10612 m4_divert_pop([@var{diversion}])dnl
10613 @end example
10614 @end defmac
10616 @defmac m4_init
10617 @msindex{init}
10618 Initialize the M4sugar environment, setting up the default named
10619 diversion to be @code{KILL}.
10620 @end defmac
10622 @node Conditional constructs
10623 @subsection Conditional constructs
10625 The following macros provide additional conditional contructs, as
10626 convenience wrappers around @code{m4_if}.
10628 @defmac m4_bmatch (@var{string}, @var{regex-1}, @var{value-1}, @
10629   @ovar{regex-2}, @ovar{value-2}, @dots{}, @ovar{default})
10630 @msindex{bmatch}
10631 The string @var{string} is repeatedly compared against a series of
10632 @var{regex} arguments; if a match is found, the expansion is the
10633 corresponding @var{value}, otherwise, the macro moves on to the next
10634 @var{regex}.  If no @var{regex} match, then the result is the optional
10635 @var{default}, or nothing.
10636 @end defmac
10638 @defmac m4_bpatsubsts (@var{string}, @var{regex-1}, @var{subst-1}, @
10639   @ovar{regex-2}, @ovar{subst-2}, @dots{})
10640 @msindex{bpatsubsts}
10641 The string @var{string} is altered by @var{regex-1} and @var{subst-1},
10642 as if by:
10643 @example
10644 m4_bpatsubst([[@var{string}]], [@var{regex}], [@var{subst}])
10645 @end example
10647 @noindent
10648 The result of the substitution is then passed through the next set of
10649 @var{regex} and @var{subst}, and so forth.  An empty @var{subst} implies
10650 deletion of any matched portions in the current string.  Note that this
10651 macro over-quotes @var{string}; this behavior is intentional, so that
10652 the result of each step of the recursion remains as a quoted string.
10653 However, it means that anchors (@samp{^} and @samp{$} in the @var{regex}
10654 will line up with the extra quotations, and not the characters of the
10655 original string.  The overquoting is removed after the final
10656 substitution.
10657 @end defmac
10659 @defmac m4_case (@var{string}, @var{value-1}, @var{if-value-1}, @
10660   @ovar{value-2}, @ovar{if-value-2}, @dots{}, @ovar{default})
10661 @msindex{case}
10662 Test @var{string} against multiple @var{value} possibilities, resulting
10663 in the first @var{if-value} for a match, or in the optional
10664 @var{default}.  This is shorthand for:
10665 @example
10666 m4_if([@var{string}], [@var{value-1}], [@var{if-value-1}],
10667       [@var{string}], [@var{value-2}], [@var{if-value-2}], @dots{},
10668       [@var{default}])
10669 @end example
10670 @end defmac
10672 @defmac m4_cond (@var{test-1}, @var{value-1}, @var{if-value-1}, @
10673   @ovar{test-2}, @ovar{value-2}, @ovar{if-value-2}, @dots{}, @ovar{default})
10674 @msindex{cond}
10675 This macro was introduced in Autoconf 2.62.  Similar to @code{m4_if},
10676 except that each @var{test} is expanded only when it is encountered.
10677 This is useful for short-circuiting expensive tests; while @code{m4_if}
10678 requires all its strings to be expanded up front before doing
10679 comparisons, @code{m4_cond} only expands a @var{test} when all earlier
10680 tests have failed.
10682 For an example, these two sequences give the same result, but in the
10683 case where @samp{$1} does not contain a backslash, the @code{m4_cond}
10684 version only expands @code{m4_index} once, instead of five times, for
10685 faster computation if this is a common case for @samp{$1}.  Notice that
10686 every third argument is unquoted for @code{m4_if}, and quoted for
10687 @code{m4_cond}:
10689 @example
10690 m4_if(m4_index([$1], [\]), [-1], [$2],
10691       m4_eval(m4_index([$1], [\\]) >= 0), [1], [$2],
10692       m4_eval(m4_index([$1], [\$]) >= 0), [1], [$2],
10693       m4_eval(m4_index([$1], [\`]) >= 0), [1], [$3],
10694       m4_eval(m4_index([$1], [\"]) >= 0), [1], [$3],
10695       [$2])
10696 m4_cond([m4_index([$1], [\])], [-1], [$2],
10697         [m4_eval(m4_index([$1], [\\]) >= 0)], [1], [$2],
10698         [m4_eval(m4_index([$1], [\$]) >= 0)], [1], [$2],
10699         [m4_eval(m4_index([$1], [\`]) >= 0)], [1], [$3],
10700         [m4_eval(m4_index([$1], [\"]) >= 0)], [1], [$3],
10701         [$2])
10702 @end example
10703 @end defmac
10705 @defmac m4_default (@var{expr-1}, @var{expr-2})
10706 @msindex{default}
10707 If @var{expr-1} is not empty, use it.  Otherwise, expand to
10708 @var{expr-2}.  Useful for providing a fixed default if the expression
10709 that results in @var{expr-1} would otherwise be empty.
10710 @end defmac
10712 @defmac m4_ifndef (@var{macro}, @var{if-not-defined}, @ovar{if-defined})
10713 @msindex{ifndef}
10714 This is shorthand for:
10715 @example
10716 m4_ifdef([@var{macro}], [@var{if-defined}], [@var{if-not-defined}])
10717 @end example
10718 @end defmac
10720 @defmac m4_ifset (@var{macro}, @ovar{if-true}, @ovar{if-false})
10721 @msindex{ifset}
10722 If @var{macro} is undefined, or is defined as the empty string, expand
10723 to @var{if-false}.  Otherwise, expands to @var{if-true}.  Similar to:
10724 @example
10725 m4_ifval(m4_defn([@var{macro}]), [@var{if-true}], [@var{if-false}])
10726 @end example
10727 @noindent
10728 except that it is not an error if @var{macro} is undefined.
10729 @end defmac
10731 @defmac m4_ifval (@var{cond}, @ovar{if-true}, @ovar{if-false})
10732 @msindex{ifval}
10733 Expands to @var{if-true} if @var{cond} is not empty, otherwise to
10734 @var{if-false}.  This is shorthand for:
10735 @example
10736 m4_if([@var{cond}], [], [@var{if-true}], [@var{if-false}])
10737 @end example
10738 @end defmac
10740 @defmac m4_ifvaln (@var{cond}, @ovar{if-true}, @ovar{if-false})
10741 @msindex{ifvaln}
10742 Similar to @code{m4_ifval}, except guarantee that a newline is present
10743 after any non-empty expansion.
10744 @end defmac
10746 @defmac m4_n (@var{text})
10747 @msindex{n}
10748 Expand to @var{text}, and add a newline if @var{text} is not empty.
10749 @end defmac
10752 @node Looping constructs
10753 @subsection Looping constructs
10755 The following macros are useful in implementing recursive algorithms in
10756 M4, including loop operations.  An M4 list is formed by quoting a list
10757 of quoted elements; generally the lists are comma-separated, although
10758 @code{m4_foreach_w} is whitespace-separated.  For example, the list
10759 @samp{[[a], [b,c]]} contains two elements: @samp{[a]} and @samp{[b,c]}.
10760 It is common to see lists with unquoted elements when those elements are
10761 not likely to be macro names, as in @samp{[fputc_unlocked,
10762 fgetc_unlocked]}.
10764 Although not generally recommended, it is possible for quoted lists to
10765 have side effects; all side effects are expanded only once, and prior to
10766 visiting any list element.  On the other hand, the fact that unquoted
10767 macros are expanded exactly once means that macros without side effects
10768 can be used to generate lists.  For example,
10770 @example
10771 m4_foreach([i], [[1], [2], [3]m4_errprintn([hi])], [i])
10772 @error{}hi
10773 @result{}123
10774 m4_define([list], [[1], [2], [3]])
10775 @result{}
10776 m4_foreach([i], [list], [i])
10777 @result{}123
10778 @end example
10780 @defmac m4_car (@var{list})
10781 @msindex{car}
10782 Expands to the quoted first element of the comma-separated quoted
10783 @var{list}.  Often used with @code{m4_cdr} to recursively iterate
10784 through a list.  Generally, when using quoted lists of quoted elements,
10785 @code{m4_car} should be called without any extra quotes.
10786 @end defmac
10788 @defmac m4_cdr (@var{list})
10789 @msindex{cdr}
10790 Expands to a quoted list of all but the first element of the
10791 comma-separated quoted @var{list}, or the empty string if @var{list} had
10792 only one element.  Generally, when using quoted lists of quoted
10793 elements, @code{m4_cdr} should be called without any extra quotes.
10795 For example, this is a simple implementation of @code{m4_map}; note how
10796 each iteration checks for the end of recursion, then merely applies the
10797 first argument to the first element of the list, then repeats with the
10798 rest of the list.  (The actual implementation in M4sugar is a bit more
10799 involved, to gain some speed and share code with @code{m4_map_sep}).
10800 @example
10801 m4_define([m4_map], [m4_ifval([$2],
10802   [m4_apply([$1], m4_car($2))[]$0([$1], m4_cdr($2))])])dnl
10803 m4_map([ m4_eval], [[[1]], [[1+1]], [[10],[16]]])
10804 @result{} 1 2 a
10805 @end example
10806 @end defmac
10808 @defmac m4_for (@var{var}, @var{first}, @var{last}, @ovar{step}, @
10809   @var{expression})
10810 @msindex{for}
10811 Loop over the numeric values between @var{first} and @var{last}
10812 including bounds by increments of @var{step}.  For each iteration,
10813 expand @var{expression} with the numeric value assigned to @var{var}.
10814 If @var{step} is omitted, it defaults to @samp{1} or @samp{-1} depending
10815 on the order of the limits.  If given, @var{step} has to match this
10816 order.  The number of iterations is determined independently from
10817 definition of @var{var}; iteration cannot be short-circuited or
10818 lengthened by modifying @var{var} from within @var{expression}.
10819 @end defmac
10821 @defmac m4_foreach (@var{var}, @var{list}, @var{expression})
10822 @msindex{foreach}
10823 Loop over the comma-separated M4 list @var{list}, assigning each value
10824 to @var{var}, and expand @var{expression}.  The following example
10825 outputs two lines:
10827 @example
10828 m4_foreach([myvar], [[foo], [bar, baz]],
10829            [echo myvar
10830 ])dnl
10831 @result{}echo foo
10832 @result{}echo bar, baz
10833 @end example
10834 @end defmac
10836 @anchor{m4_foreach_w}
10837 @defmac m4_foreach_w (@var{var}, @var{list}, @var{expression})
10838 @msindex{foreach_w}
10839 Loop over the white-space-separated list @var{list}, assigning each value
10840 to @var{var}, and expand @var{expression}.
10842 The deprecated macro @code{AC_FOREACH} is an alias of
10843 @code{m4_foreach_w}.
10844 @end defmac
10846 @defmac m4_map (@var{macro}, @var{list})
10847 @defmacx m4_mapall (@var{macro}, @var{list})
10848 @defmacx m4_map_sep (@var{macro}, @var{separator}, @var{list})
10849 @defmacx m4_mapall_sep (@var{macro}, @var{separator}, @var{list})
10850 @msindex{map}
10851 @msindex{mapall}
10852 @msindex{map_sep}
10853 @msindex{mapall_sep}
10854 Loop over the comma separated quoted list of argument descriptions in
10855 @var{list}, and invoke @var{macro} with the arguments.  An argument
10856 description is in turn a comma-separated quoted list of quoted elements,
10857 suitable for @code{m4_apply}.  The macros @code{m4_map} and
10858 @code{m4_map_sep} ignore empty argument descriptions, while
10859 @code{m4_mapall} and @code{m4_mapall_sep} invoke @var{macro} with no
10860 arguments.  The macros @code{m4_map_sep} and @code{m4_mapall_sep}
10861 additionally expand @var{separator} between invocations of @var{macro}.
10863 Note that @var{separator} is expanded, unlike in @code{m4_join}.  When
10864 separating output with commas, this means that the map result can be
10865 used as a series of arguments, by using a single-quoted comma as
10866 @var{separator}, or as a single string, by using a double-quoted comma.
10868 @example
10869 m4_map([m4_count], [])
10870 @result{}
10871 m4_map([ m4_count], [[],
10872                      [[1]],
10873                      [[1], [2]]])
10874 @result{} 1 2
10875 m4_mapall([ m4_count], [[],
10876                         [[1]],
10877                         [[1], [2]]])
10878 @result{} 0 1 2
10879 m4_map_sep([m4_eval], [,], [[[1+2]],
10880                             [[10], [16]]])
10881 @result{}3,a
10882 m4_map_sep([m4_echo], [,], [[[a]], [[b]]])
10883 @result{}a,b
10884 m4_count(m4_map_sep([m4_echo], [,], [[[a]], [[b]]]))
10885 @result{}2
10886 m4_map_sep([m4_echo], [[,]], [[[a]], [[b]]])
10887 @result{}a,b
10888 m4_count(m4_map_sep([m4_echo], [[,]], [[[a]], [[b]]]))
10889 @result{}1
10890 @end example
10891 @end defmac
10893 @defmac m4_shiftn (@var{count}, @dots{})
10894 @defmacx m4_shift2 (@dots{})
10895 @defmacx m4_shift3 (@dots{})
10896 @msindex{shift2}
10897 @msindex{shift3}
10898 @msindex{shiftn}
10899 @code{m4_shiftn} performs @var{count} iterations of @code{m4_shift},
10900 along with validation that enough arguments were passed in to match the
10901 shift count, and that the count is positive.  @code{m4_shift2} and
10902 @code{m4_shift3} are specializations
10903 of @code{m4_shiftn}, introduced in Autoconf 2.62, and are more efficient
10904 for two and three shifts, respectively.
10905 @end defmac
10908 @node Evaluation Macros
10909 @subsection Evaluation Macros
10911 The following macros give some control over the order of the evaluation
10912 by adding or removing levels of quotes.
10914 @defmac m4_apply (@var{macro}, @var{list})
10915 @msindex{apply}
10916 Apply the elements of the quoted, comma-separated @var{list} as the
10917 arguments to @var{macro}.  If @var{list} is empty, invoke @var{macro}
10918 without arguments.  Note the difference between @code{m4_indir}, which
10919 expects its first argument to be a macro name but can use names that are
10920 otherwise invalid, and @code{m4_apply}, where @var{macro} can contain
10921 other text, but must end in a valid macro name.
10922 @example
10923 m4_apply([m4_count], [])
10924 @result{}0
10925 m4_apply([m4_count], [[]])
10926 @result{}1
10927 m4_apply([m4_count], [[1], [2]])
10928 @result{}2
10929 m4_apply([m4_join], [[|], [1], [2]])
10930 @result{}1|2
10931 @end example
10932 @end defmac
10934 @defmac m4_count (@var{arg}, @dots{})
10935 @msindex{count}
10936 This macro returns the decimal count of the number of arguments it was
10937 passed.
10938 @end defmac
10940 @defmac m4_do (@var{arg}, @dots{})
10941 @msindex{do}
10942 This macro loops over its arguments and expands each @var{arg} in
10943 sequence.  Its main use is for readability; it allows the use of
10944 indentation and fewer @code{dnl} to result in the same expansion.  This
10945 macro guarantees that no expansion will be concatenated with subsequent
10946 text; to achieve full concatenation, use @code{m4_unquote(m4_join([],
10947 @var{arg@dots{}}))}.
10949 @example
10950 m4_define([ab],[1])m4_define([bc],[2])m4_define([abc],[3])dnl
10951 m4_do([a],[b])c
10952 @result{}abc
10953 m4_unquote(m4_join([],[a],[b]))c
10954 @result{}3
10955 m4_define([a],[A])m4_define([b],[B])m4_define([c],[C])dnl
10956 m4_define([AB],[4])m4_define([BC],[5])m4_define([ABC],[6])dnl
10957 m4_do([a],[b])c
10958 @result{}ABC
10959 m4_unquote(m4_join([],[a],[b]))c
10960 @result{}3
10961 @end example
10962 @end defmac
10964 @defmac m4_dquote (@var{arg}, @dots{})
10965 @msindex{dquote}
10966 Return the arguments as a quoted list of quoted arguments.
10967 Conveniently, if there is just one @var{arg}, this effectively adds a
10968 level of quoting.
10969 @end defmac
10971 @defmac m4_dquote_elt (@var{arg}, @dots{})
10972 @msindex{dquote_elt}
10973 Return the arguments as a series of double-quoted arguments.  Whereas
10974 @code{m4_dquote} returns a single argument, @code{m4_dquote_elt} returns
10975 as many arguments as it was passed.
10976 @end defmac
10978 @defmac m4_echo (@var{arg}, @dots{})
10979 @msindex{echo}
10980 Return the arguments, with the same level of quoting.  Other than
10981 discarding whitespace after unquoted commas, this macro is a no-op.
10982 @end defmac
10984 @defmac m4_expand (@var{arg})
10985 @msindex{expand}
10986 Return the expansion of @var{arg} as a quoted string.  Whereas
10987 @code{m4_quote} is designed to collect expanded text into a single
10988 argument, @code{m4_expand} is designed to perform one level of expansion
10989 on quoted text.  The distinction is in the treatment of whitespace
10990 following a comma in the original @var{arg}.  Any time multiple
10991 arguments are collected into one with @code{m4_quote}, the M4 argument
10992 collection rules discard the whitespace.  However, with @code{m4_expand},
10993 whitespace is preserved, even after the expansion of macros contained in
10994 @var{arg}.
10996 @example
10997 m4_define([active], [ACT, IVE])dnl
10998 m4_define([active2], [[ACT, IVE]])dnl
10999 m4_quote(active, active)
11000 @result{}ACT,IVE,ACT,IVE
11001 m4_expand([active, active])
11002 @result{}ACT, IVE, ACT, IVE
11003 m4_quote(active2, active2)
11004 @result{}ACT, IVE,ACT, IVE
11005 m4_expand([active2, active2])
11006 @result{}ACT, IVE, ACT, IVE
11007 @end example
11009 Note that @code{m4_expand} cannot handle an @var{arg} that expands to
11010 literal unbalanced quotes, but that quadrigraphs can be used when
11011 unbalanced output is necessary.  Likewise, unbalanced parentheses must
11012 be supplied with double quoting or a quadrigraph.
11014 @example
11015 m4_define([pattern], [[!@@<:@@]])dnl
11016 m4_define([bar], [BAR])dnl
11017 m4_expand([case $foo in
11018   m4_defn([pattern])@@:@}@@ bar ;;
11019   *[)] blah ;;
11020 esac])
11021 @result{}case $foo in
11022 @result{}  [![]) BAR ;;
11023 @result{}  *) blah ;;
11024 @result{}esac
11025 @end example
11026 @end defmac
11028 @defmac m4_ignore (@dots{})
11029 @msindex{ignore}
11030 This macro was introduced in Autoconf 2.62.  Expands to nothing,
11031 ignoring all of its arguments.  By itself, this isn't very useful.
11032 However, it can be used to conditionally ignore an arbitrary number of
11033 arguments, by deciding which macro name to apply to a list of arguments.
11034 @example
11035 dnl foo outputs a message only if [debug] is defined.
11036 m4_define([foo],
11037 [m4_ifdef([debug],[AC_MSG_NOTICE],[m4_ignore])([debug message])])
11038 @end example
11040 Note that for earlier versions of Autoconf, the macro @code{__gnu__} can
11041 serve the same purpose, although it is less readable.
11042 @end defmac
11044 @defmac m4_make_list (@var{arg}, @dots{})
11045 @msindex{make_list}
11046 This macro exists to aid debugging of M4sugar algorithms.  Its net
11047 effect is similar to @code{m4_dquote}---it produces a quoted list of
11048 quoted arguments, for each @var{arg}.  The difference is that this
11049 version uses a comma-newline separator instead of just comma, to improve
11050 readability of the list; with the result that it is less efficient than
11051 @code{m4_dquote}.
11052 @example
11053 m4_define([zero],[0])m4_define([one],[1])m4_define([two],[2])dnl
11054 m4_dquote(zero, [one], [[two]])
11055 @result{}[0],[one],[[two]]
11056 m4_make_list(zero, [one], [[two]])
11057 @result{}[0],
11058 @result{}[one],
11059 @result{}[[two]]
11060 m4_foreach([number], m4_dquote(zero, [one], [[two]]), [ number])
11061 @result{} 0 1 two
11062 m4_foreach([number], m4_make_list(zero, [one], [[two]]), [ number])
11063 @result{} 0 1 two
11064 @end example
11065 @end defmac
11067 @c m4_noquote is too dangerous to document - it invokes macros that
11068 @c probably rely on @samp{[]} nested quoting for proper operation.  The
11069 @c user should generally prefer m4_unquote instead.
11071 @defmac m4_quote (@var{arg}, @dots{})
11072 @msindex{quote}
11073 Return the arguments as a single entity, i.e., wrap them into a pair of
11074 quotes.  This effectively collapses multiple arguments into one,
11075 although it loses whitespace after unquoted commas in the process.
11076 @end defmac
11078 @defmac m4_reverse (@var{arg}, @dots{})
11079 @msindex{reverse}
11080 Outputs each argument with the same level of quoting, but in reverse
11081 order, and with space following each comma for readability.
11083 @example
11084 m4_define([active], [ACT,IVE])
11085 @result{}
11086 m4_reverse(active, [active])
11087 @result{}active, IVE, ACT
11088 @end example
11089 @end defmac
11091 @defmac m4_unquote (@var{arg}, @dots{})
11092 @msindex{unquote}
11093 This macro was introduced in Autoconf 2.62.  Expand each argument,
11094 separated by commas.  For a single @var{arg}, this effectively removes a
11095 layer of quoting, and @code{m4_unquote([@var{arg}])} is more efficient
11096 than the equivalent @code{m4_do([@var{arg}])}.  For multiple arguments,
11097 this results in an unquoted list of expansions.  This is commonly used
11098 with @code{m4_split}, in order to convert a single quoted list into a
11099 series of quoted elements.
11100 @end defmac
11102 The following example aims at emphasizing the difference between several
11103 scenarios: not using these macros, using @code{m4_defn}, using
11104 @code{m4_quote}, using @code{m4_dquote}, and using @code{m4_expand}.
11106 @example
11107 $ @kbd{cat example.m4}
11108 dnl Overquote, so that quotes are visible.
11109 m4_define([show], [$[]1 = [$1], $[]@@ = [$@@]])
11110 m4_define([a], [A])
11111 m4_define([mkargs], [1, 2[,] 3])
11112 m4_define([arg1], [[$1]])
11113 m4_divert([0])dnl
11114 show(a, b)
11115 show([a, b])
11116 show(m4_quote(a, b))
11117 show(m4_dquote(a, b))
11118 show(m4_expand([a, b]))
11120 arg1(mkargs)
11121 arg1([mkargs])
11122 arg1(m4_defn([mkargs]))
11123 arg1(m4_quote(mkargs))
11124 arg1(m4_dquote(mkargs))
11125 arg1(m4_expand([mkargs]))
11126 $ @kbd{autom4te -l m4sugar example.m4}
11127 $1 = A, $@@ = [A],[b]
11128 $1 = a, b, $@@ = [a, b]
11129 $1 = A,b, $@@ = [A,b]
11130 $1 = [A],[b], $@@ = [[A],[b]]
11131 $1 = A, b, $@@ = [A, b]
11134 mkargs
11135 1, 2[,] 3
11136 1,2, 3
11137 [1],[2, 3]
11138 1, 2, 3
11139 @end example
11142 @node Text processing Macros
11143 @subsection String manipulation in M4
11145 The following macros may be used to manipulate strings in M4.  Many of
11146 the macros in this section intentionally result in quoted strings as
11147 output, rather than subjecting the arguments to further expansions.  As
11148 a result, if you are manipulating text that contains active M4
11149 characters, the arguments are passed with single quoting rather than
11150 double.
11152 @defmac m4_append (@var{macro-name}, @var{string}, @ovar{separator})
11153 @defmacx m4_append_uniq (@var{macro-name}, @var{string}, @ovar{separator} @
11154   @ovar{if-uniq}, @ovar{if-duplicate})
11155 @msindex{append}
11156 @msindex{append_uniq}
11157 Redefine @var{macro-name} to its former contents with @var{separator}
11158 and @var{string} added at the end.  If @var{macro-name} was undefined
11159 before (but not if it was defined but empty), then no @var{separator} is
11160 added.  As of Autoconf 2.62, neither @var{string} nor @var{separator}
11161 are expanded during this macro; instead, they are expanded when
11162 @var{macro-name} is invoked.
11164 @code{m4_append} can be used to grow strings, and @code{m4_append_uniq}
11165 to grow strings without duplicating substrings.  Additionally,
11166 @code{m4_append_uniq} takes two optional parameters as of Autoconf 2.62;
11167 @var{if-uniq} is expanded if @var{string} was appended, and
11168 @var{if-duplicate} is expanded if @var{string} was already present.
11169 Also, @code{m4_append_uniq} warns if @var{separator} is not empty, but
11170 occurs within @var{string}, since that can lead to duplicates.
11172 Note that @code{m4_append} can scale linearly in the length of the final
11173 string, depending on the quality of the underlying M4 implementation,
11174 while @code{m4_append_uniq} has an inherent quadratic scaling factor.
11175 If an algorithm can tolerate duplicates in the final string, use the
11176 former for speed.  If duplicates must be avoided, consider using
11177 @code{m4_set_add} instead (@pxref{Set manipulation Macros}).
11179 @example
11180 m4_define([active], [ACTIVE])dnl
11181 m4_append([sentence], [This is an])dnl
11182 m4_append([sentence], [ active ])dnl
11183 m4_append([sentence], [symbol.])dnl
11184 sentence
11185 @result{}This is an ACTIVE symbol.
11186 m4_undefine([active])dnl
11187 @result{}This is an active symbol.
11188 m4_append_uniq([list], [one], [, ], [new], [existing])
11189 @result{}new
11190 m4_append_uniq([list], [one], [, ], [new], [existing])
11191 @result{}existing
11192 m4_append_uniq([list], [two], [, ], [new], [existing])
11193 @result{}new
11194 m4_append_uniq([list], [three], [, ], [new], [existing])
11195 @result{}new
11196 m4_append_uniq([list], [two], [, ], [new], [existing])
11197 @result{}existing
11198 list
11199 @result{}one, two, three
11200 m4_dquote(list)
11201 @result{}[one],[two],[three]
11202 m4_append([list2], [one], [[, ]])dnl
11203 m4_append_uniq([list2], [two], [[, ]])dnl
11204 m4_append([list2], [three], [[, ]])dnl
11205 list2
11206 @result{}one, two, three
11207 m4_dquote(list2)
11208 @result{}[one, two, three]
11209 @end example
11210 @end defmac
11212 @defmac m4_append_uniq_w (@var{macro-name}, @var{strings})
11213 @msindex{append_uniq_w}
11214 This macro was introduced in Autoconf 2.62.  It is similar to
11215 @code{m4_append_uniq}, but treats @var{strings} as a whitespace
11216 separated list of words to append, and only appends unique words.
11217 @var{macro-name} is updated with a single space between new words.
11218 @example
11219 m4_append_uniq_w([numbers], [1 1 2])dnl
11220 m4_append_uniq_w([numbers], [ 2 3 ])dnl
11221 numbers
11222 @result{}1 2 3
11223 @end example
11224 @end defmac
11226 @defmac m4_combine (@ovar{separator}, @var{prefix-list}, @ovar{infix}, @
11227   @var{suffix-1}, @ovar{suffix-2}, @dots{})
11228 @msindex{combine}
11229 This macro produces a quoted string containing the pairwise combination
11230 of every element of the quoted, comma-separated @var{prefix-list}, and
11231 every element from the @var{suffix} arguments.  Each pairwise
11232 combination is joined with @var{infix} in the middle, and successive
11233 pairs are joined by @var{separator}.  No expansion occurs on any of the
11234 arguments.  No output occurs if either the @var{prefix} or @var{suffix}
11235 list is empty, but the lists can contain empty elements.
11236 @example
11237 m4_define([a], [oops])dnl
11238 m4_combine([, ], [[a], [b], [c]], [-], [1], [2], [3])
11239 @result{}a-1, a-2, a-3, b-1, b-2, b-3, c-1, c-2, c-3
11240 m4_combine([, ], [[a], [b]], [-])
11241 @result{}
11242 m4_combine([, ], [[a], [b]], [-], [])
11243 @result{}a-, b-
11244 m4_combine([, ], [], [-], [1], [2])
11245 @result{}
11246 m4_combine([, ], [[]], [-], [1], [2])
11247 @result{}-1, -2
11248 @end example
11249 @end defmac
11251 @defmac m4_flatten (@var{string})
11252 @msindex{flatten}
11253 Flatten @var{string} into a single line.  Delete all backslash-newline
11254 pairs, and replace all remaining newlines with a space.  The result is
11255 still a quoted string.
11256 @end defmac
11258 @defmac m4_join (@ovar{separator}, @var{args}@dots{})
11259 @defmacx m4_joinall (@ovar{separator}, @var{args}@dots{})
11260 @msindex{join}
11261 @msindex{joinall}
11262 Concatenate each @var{arg}, separated by @var{separator}.
11263 @code{joinall} uses every argument, while @code{join} omits empty
11264 arguments so that there are no back-to-back separators in the output.
11265 The result is a quoted string.
11266 @example
11267 m4_define([active], [ACTIVE])dnl
11268 m4_join([|], [one], [], [active], [two])
11269 @result{}one|active|two
11270 m4_joinall([|], [one], [], [active], [two])
11271 @result{}one||active|two
11272 @end example
11274 Note that if all you intend to do is join @var{args} with commas between
11275 them, to form a quoted list suitable for @code{m4_foreach}, it is more
11276 efficient to use @code{m4_dquote}.
11277 @end defmac
11279 @defmac m4_newline
11280 @msindex{newline}
11281 This macro was introduced in Autoconf 2.62, and expands to a newline.
11282 It is primarily useful for maintaining macro formatting, and ensuring
11283 that M4 does not discard leading whitespace during argument collection.
11284 @end defmac
11286 @defmac m4_normalize (@var{string})
11287 @msindex{normalize}
11288 Remove leading and trailing spaces and tabs, sequences of
11289 backslash-then-newline, and replace multiple spaces, tabs, and newlines
11290 with a single space.  This is a combination of @code{m4_flatten} and
11291 @code{m4_strip}.
11292 @end defmac
11294 @defmac m4_re_escape (@var{string})
11295 @msindex{re_escape}
11296 Backslash-escape all characters in @var{string} that are active in
11297 regexps.
11298 @end defmac
11300 @defmac m4_split (@var{string}, @dvar{regexp, [\t ]+})
11301 @msindex{split}
11302 Split @var{string} into an M4 list of elements quoted by @samp{[} and
11303 @samp{]}, while keeping white space at the beginning and at the end.
11304 If @var{regexp} is given, use it instead of @samp{[\t ]+} for splitting.
11305 If @var{string} is empty, the result is an empty list.
11306 @end defmac
11308 @defmac m4_strip (@var{string})
11309 @msindex{strip}
11310 Strip whitespace from @var{string}.  Sequences of spaces and tabs are
11311 reduced to a single space, then leading and trailing spaces are removed.
11312 The result is still a quoted string.  Note that this does not interfere
11313 with newlines; if you want newlines stripped as well, consider
11314 @code{m4_flatten}, or do it all at once with @code{m4_normalize}.
11315 @end defmac
11317 @defmac m4_text_box (@var{message}, @dvar{frame, -})
11318 @msindex{text_box}
11319 Add a text box around @var{message}, using @var{frame} as the border
11320 character above and below the message.  The frame correctly accounts for
11321 the subsequent expansion of @var{message}.  For example:
11322 @example
11323 m4_define([macro], [abc])dnl
11324 m4_text_box([macro])
11325 @result{}## --- ##
11326 @result{}## abc ##
11327 @result{}## --- ##
11328 @end example
11330 The @var{message} must contain balanced quotes and parentheses, although
11331 quadrigraphs can be used to work around this.
11332 @end defmac
11334 @defmac m4_text_wrap (@var{string}, @ovar{prefix}, @
11335   @dvar{prefix1, @var{prefix}}, @dvar{width, 79})
11336 @msindex{text_wrap}
11337 Break @var{string} into a series of whitespace-separated words, then
11338 output those words separated by spaces, and wrapping lines any time the
11339 output would exceed @var{width} columns.  If given, @var{prefix1} begins
11340 the first line, and @var{prefix} begins all wrapped lines.  If
11341 @var{prefix1} is longer than @var{prefix}, then the first line consists
11342 of just @var{prefix1}.  If @var{prefix} is longer than @var{prefix1},
11343 padding is inserted so that the first word of @var{string} begins at the
11344 same indentation as all wrapped lines.  Note that using literal tab
11345 characters in any of the arguments will interfere with the calculation
11346 of width.  No expansions occur on @var{prefix}, @var{prefix1}, or the
11347 words of @var{string}, although quadrigraphs are recognized.
11349 For some examples:
11350 @example
11351 m4_text_wrap([Short string */], [   ], [/* ], [20])
11352 @result{}/* Short string */
11353 m4_text_wrap([Much longer string */], [   ], [/* ], [20])
11354 @result{}/* Much longer
11355 @result{}   string */
11356 m4_text_wrap([Short doc.], [          ], [  --short ], [30])
11357 @result{}  --short Short doc.
11358 m4_text_wrap([Short doc.], [          ], [  --too-wide ], [30])
11359 @result{}  --too-wide
11360 @result{}          Short doc.
11361 m4_text_wrap([Super long documentation.], [     ],
11362              [  --too-wide ], 30)
11363 @result{}  --too-wide
11364 @result{}     Super long
11365 @result{}     documentation.
11366 @end example
11367 @end defmac
11369 @defmac m4_tolower (@var{string})
11370 @defmacx m4_toupper (@var{string})
11371 @msindex{tolower}
11372 @msindex{toupper}
11373 Return @var{string} with letters converted to upper or lower case,
11374 respectively.
11375 @end defmac
11377 @node Number processing Macros
11378 @subsection Arithmetic computation in M4
11380 The following macros facilitate integer arithmetic operations.
11381 Where a parameter is documented as taking an arithmetic expression, you
11382 can use anything that can be parsed by @code{m4_eval}.
11384 @defmac m4_cmp (@var{expr-1}, @var{expr-2})
11385 @msindex{cmp}
11386 Compare the arithmetic expressions @var{expr-1} and @var{expr-2}, and
11387 expand to @samp{-1} if @var{expr-1} is smaller, @samp{0} if they are
11388 equal, and @samp{1} if @var{expr-1} is larger.
11389 @end defmac
11391 @defmac m4_list_cmp (@var{list-1}, @var{list-2})
11392 @msindex{list_cmp}
11393 Compare the two M4 lists consisting of comma-separated arithmetic
11394 expressions, left to right.  Expand to @samp{-1} for the first element
11395 pairing where the value from @var{list-1} is smaller, @samp{1} where the
11396 value from @var{list-2} is smaller, or @samp{0} if both lists have the
11397 same values.  If one list is shorter than the other, the remaining
11398 elements of the longer list are compared against zero.
11399 @example
11400 m4_list_cmp([1, 0],       [1])
11401 @result{}0
11402 m4_list_cmp([1, [1 * 0]], [1, 0])
11403 @result{}0
11404 m4_list_cmp([1, 2],       [1, 0])
11405 @result{}1
11406 m4_list_cmp([1, [1+1], 3],[1, 2])
11407 @result{}1
11408 m4_list_cmp([1, 2, -3],   [1, 2])
11409 @result{}-1
11410 m4_list_cmp([1, 0],       [1, 2])
11411 @result{}-1
11412 m4_list_cmp([1],          [1, 2])
11413 @result{}-1
11414 @end example
11415 @end defmac
11417 @defmac m4_max (@var{arg}, @dots{})
11418 @msindex{max}
11419 This macro was introduced in Autoconf 2.62.  Expand to the decimal value
11420 of the maximum arithmetic expression among all the arguments.
11421 @end defmac
11423 @defmac m4_min (@var{arg}, @dots{})
11424 @msindex{min}
11425 This macro was introduced in Autoconf 2.62.  Expand to the decimal value
11426 of the minimum arithmetic expression among all the arguments.
11427 @end defmac
11429 @defmac m4_sign (@var{expr})
11430 @msindex{sign}
11431 Expand to @samp{-1} if the arithmetic expression @var{expr} is negative,
11432 @samp{1} if it is positive, and @samp{0} if it is zero.
11433 @end defmac
11435 @anchor{m4_version_compare}
11436 @defmac m4_version_compare (@var{version-1}, @var{version-2})
11437 @msindex{version_compare}
11438 This macro was introduced in Autoconf 2.53, but had a number of
11439 usability limitations that were not lifted until Autoconf 2.62.  Compare
11440 the version strings @var{version-1} and @var{version-2}, and expand to
11441 @samp{-1} if @var{version-1} is smaller, @samp{0} if they are the same,
11442 or @samp{1} @var{version-2} is smaller.  Version strings must be a list
11443 of elements separated by @samp{.}, @samp{,} or @samp{-}, where each
11444 element is a number along with optional case-insensitive letters
11445 designating beta releases.  The comparison stops at the leftmost element
11446 that contains a difference, although a 0 element compares equal to a
11447 missing element.
11449 It is permissible to include commit identifiers in @var{version}, such
11450 as an abbreviated SHA1 of the commit, provided there is still a
11451 monotonically increasing prefix to allow for accurate version-based
11452 comparisons.  For example, this paragraph was written when the
11453 development snapshot of autoconf claimed to be at version
11454 @samp{2.61a-248-dc51}, or 248 commits after the 2.61a release, with an
11455 abbreviated commit identification of @samp{dc51}.
11457 @example
11458 m4_version_compare([1.1], [2.0])
11459 @result{}-1
11460 m4_version_compare([2.0b], [2.0a])
11461 @result{}1
11462 m4_version_compare([1.1.1], [1.1.1a])
11463 @result{}-1
11464 m4_version_compare([1.2], [1.1.1a])
11465 @result{}1
11466 m4_version_compare([1.0], [1])
11467 @result{}0
11468 m4_version_compare([1.1pre], [1.1PRE])
11469 @result{}0
11470 m4_version_compare([1.1a], [1,10])
11471 @result{}-1
11472 m4_version_compare([2.61a], [2.61a-248-dc51])
11473 @result{}-1
11474 m4_version_compare([2.61b], [2.61a-248-dc51])
11475 @result{}1
11476 @end example
11477 @end defmac
11480 @node Set manipulation Macros
11481 @subsection Set manipulation in M4
11482 @cindex Set manipulation
11483 @cindex Data structure, set
11484 @cindex Unordered set manipulation
11486 Sometimes, it is necessary to track a set of data, where the order does
11487 not matter and where there are no duplicates in the set.  The following
11488 macros facilitate set manipulations.  Each set is an opaque object,
11489 which can only be accessed via these basic operations.  The underlying
11490 implementation guarantees linear scaling for set creation, which is more
11491 efficient than using the quadratic @code{m4_append_uniq}.  Both set
11492 names and values can be arbitrary strings, except for unbalanced quotes.
11493 This implementation ties up memory for removed elements until the next
11494 operation that must traverse all the elements of a set; and although
11495 that may slow down some operations until the memory for removed elements
11496 is pruned, it still guarantees linear performance.
11498 @defmac m4_set_add (@var{set}, @var{value}, @ovar{if-uniq}, @ovar{if-dup})
11499 @msindex{set_add}
11500 Adds the string @var{value} as a member of set @var{set}.  Expand
11501 @var{if-uniq} if the element was added, or @var{if-dup} if it was
11502 previously in the set.  Operates in amortized constant time, so that set
11503 creation scales linearly.
11504 @end defmac
11506 @defmac m4_set_add_all (@var{set}, @var{value}@dots{})
11507 @msindex{set_add_all}
11508 Adds each @var{value} to the set @var{set}.  This is slightly more
11509 efficient than repeatedly invoking @code{m4_set_add}.
11510 @end defmac
11512 @defmac m4_set_contains (@var{set}, @var{value}, @ovar{if-present}, @
11513  @ovar{if-absent})
11514 @msindex{set_contains}
11515 Expands @var{if-present} if the string @var{value} is a member of
11516 @var{set}, otherwise @var{if-absent}.
11518 @example
11519 m4_set_contains([a], [1], [yes], [no])
11520 @result{}no
11521 m4_set_add([a], [1], [added], [dup])
11522 @result{}added
11523 m4_set_add([a], [1], [added], [dup])
11524 @result{}dup
11525 m4_set_contains([a], [1], [yes], [no])
11526 @result{}yes
11527 m4_set_remove([a], [1], [removed], [missing])
11528 @result{}removed
11529 m4_set_contains([a], [1], [yes], [no])
11530 @result{}no
11531 m4_set_remove([a], [1], [removed], [missing])
11532 @result{}missing
11533 @end example
11534 @end defmac
11536 @defmac m4_set_contents (@var{set}, @ovar{sep})
11537 @defmacx m4_set_dump (@var{set}, @ovar{sep})
11538 @msindex{set_contents}
11539 @msindex{set_dump}
11540 Expands to a single string consisting of all the members of the set
11541 @var{set}, each separated by @var{sep}, which is not expanded.
11542 @code{m4_set_contents} leaves the elements in @var{set} but reclaims any
11543 memory occupied by removed elements, while @code{m4_set_dump} is a
11544 faster one-shot action that also deletes the set.  No provision is made
11545 for disambiguating members that contain a non-empty @var{sep} as a
11546 substring; use @code{m4_set_empty} to distinguish between an empty set
11547 and the set containing only the empty string.  The order of the output
11548 is unspecified; in the current implementation, part of the speed of
11549 @code{m4_set_dump} results from using a different output order than
11550 @code{m4_set_contents}.  These macros scale linearly in the size of the
11551 set before memory pruning, and @code{m4_set_contents([@var{set}],
11552 [@var{sep}])} is faster than
11553 @code{m4_joinall([@var{sep}]m4_set_listc([@var{set}]))}.
11555 @example
11556 m4_set_add_all([a], [1], [2], [3])
11557 @result{}
11558 m4_set_contents([a], [-])
11559 @result{}1-2-3
11560 m4_joinall([-]m4_set_listc([a]))
11561 @result{}1-2-3
11562 m4_set_dump([a], [-])
11563 @result{}3-2-1
11564 m4_set_contents([a])
11565 @result{}
11566 m4_set_add([a], [])
11567 @result{}
11568 m4_set_contents([a], [-])
11569 @result{}
11570 @end example
11571 @end defmac
11573 @defmac m4_set_delete (@var{set})
11574 @msindex{set_delete}
11575 Delete all elements and memory associated with @var{set}.  This is
11576 linear in the set size, and faster than removing one element at a time.
11577 @end defmac
11579 @defmac m4_set_difference (@var{seta}, @var{setb})
11580 @defmacx m4_set_intersection (@var{seta}, @var{setb})
11581 @defmacx m4_set_union (@var{seta}, @var{setb})
11582 @msindex{set_difference}
11583 @msindex{set_intersection}
11584 @msindex{set_union}
11585 Compute the relation between @var{seta} and @var{setb}, and output the
11586 result as a list of quoted arguments without duplicates and with a
11587 leading comma.  Set difference selects the elements in @var{seta} but
11588 not @var{setb}, intersection selects only elements in both sets, and
11589 union selects elements in either set.  These actions are linear in the
11590 sum of the set sizes.  The leading comma is necessary to distinguish
11591 between no elements and the empty string as the only element.
11593 @example
11594 m4_set_add_all([a], [1], [2], [3])
11595 @result{}
11596 m4_set_add_all([b], [3], [], [4])
11597 @result{}
11598 m4_set_difference([a], [b])
11599 @result{},1,2
11600 m4_set_difference([b], [a])
11601 @result{},,4
11602 m4_set_intersection([a], [b])
11603 @result{},3
11604 m4_set_union([a], [b])
11605 @result{},1,2,3,,4
11606 @end example
11607 @end defmac
11609 @defmac m4_set_empty (@var{set}, @ovar{if-empty}, @ovar{if-elements})
11610 @msindex{set_empty}
11611 Expand @var{if-empty} if the set @var{set} has no elements, otherwise
11612 expand @var{if-elements}.  This macro operates in constant time.  Using
11613 this macro can help disambiguate output from @code{m4_set_contents} or
11614 @code{m4_set_list}.
11615 @end defmac
11617 @defmac m4_set_foreach (@var{set}, @var{variable}, @var{action})
11618 @msindex{set_foreach}
11619 For each element in the set @var{set}, expand @var{action} with the
11620 macro @var{variable} defined as the set element.  Behavior is
11621 unspecified if @var{action} recursively lists the contents of @var{set}
11622 (although listing other sets is acceptable), or if it modifies the set
11623 in any way other than removing the element currently contained in
11624 @var{variable}.  This macro is faster than the corresponding
11625 @code{m4_foreach([@var{variable}],
11626 m4_indir([m4_dquote]m4_set_listc([@var{set}])), [@var{action}])}.
11628 @example
11629 m4_set_add_all([a]m4_for([i], [1], [5], [], [,i]))
11630 @result{}
11631 m4_set_contents([a])
11632 @result{}12345
11633 m4_set_foreach([a], [i],
11634   [m4_if(m4_eval(i&1), [0], [m4_set_remove([a], i, [i])])])
11635 @result{}24
11636 m4_set_contents([a])
11637 @result{}135
11638 @end example
11639 @end defmac
11641 @defmac m4_set_list (@var{set})
11642 @defmacx m4_set_listc (@var{set})
11643 @msindex{set_list}
11644 @msindex{set_listc}
11645 Produce a list of arguments, where each argument is a quoted element
11646 from the set @var{set}.  The variant @code{m4_set_listc} is unambiguous,
11647 by adding a leading comma if there are any set elements, whereas the
11648 variant @code{m4_set_list} cannot distinguish between an empty set and a
11649 set containing only the empty string.  These can be directly used in
11650 macros that take multiple arguments, such as @code{m4_join} or
11651 @code{m4_set_add_all}, or wrapped by @code{m4_dquote} for macros that
11652 take a quoted list, such as @code{m4_map} or @code{m4_foreach}.  Any
11653 memory occupied by removed elements is reclaimed during these macros.
11655 @example
11656 m4_set_add_all([a], [1], [2], [3])
11657 @result{}
11658 m4_set_list([a])
11659 @result{}1,2,3
11660 m4_set_list([b])
11661 @result{}
11662 m4_set_listc([b])
11663 @result{}
11664 m4_count(m4_set_list([b]))
11665 @result{}1
11666 m4_set_empty([b], [0], [m4_count(m4_set_list([b]))])
11667 @result{}0
11668 m4_set_add([b], [])
11669 @result{}
11670 m4_set_list([b])
11671 @result{}
11672 m4_set_listc([b])
11673 @result{},
11674 m4_count(m4_set_list([b]))
11675 @result{}1
11676 m4_set_empty([b], [0], [m4_count(m4_set_list([b]))])
11677 @result{}1
11678 @end example
11679 @end defmac
11681 @defmac m4_set_remove (@var{set}, @var{value}, @ovar{if-present}, @
11682  @ovar{if-absent})
11683 @msindex{set_remove}
11684 If @var{value} is an element in the set @var{set}, then remove it and
11685 expand @var{if-present}.  Otherwise expand @var{if-absent}.  This macro
11686 operates in constant time so that multiple removals will scale linearly
11687 rather than quadratically; but when used outside of
11688 @code{m4_set_foreach}, it leaves memory occupied until the set is later
11689 compacted by @code{m4_set_contents} or @code{m4_set_list}.  Several
11690 other set operations are then less efficient between the time of element
11691 removal and subsequent memory compaction, but still maintain their
11692 guaranteed scaling performance.
11693 @end defmac
11695 @defmac m4_set_size (@var{set})
11696 @msindex{set_size}
11697 Expand to the size of the set @var{set}.  This implementation operates
11698 in constant time, and is thus more efficient than
11699 @code{m4_eval(m4_count(m4_set_listc([set])) - 1)}.
11700 @end defmac
11703 @node Forbidden Patterns
11704 @subsection Forbidden Patterns
11705 @cindex Forbidden patterns
11706 @cindex Patterns, forbidden
11708 M4sugar provides a means to define suspicious patterns, patterns
11709 describing tokens which should not be found in the output.  For
11710 instance, if an Autoconf @file{configure} script includes tokens such as
11711 @samp{AC_DEFINE}, or @samp{dnl}, then most probably something went
11712 wrong (typically a macro was not evaluated because of overquotation).
11714 M4sugar forbids all the tokens matching @samp{^_?m4_} and @samp{^dnl$}.
11715 Additional layers, such as M4sh and Autoconf, add additional forbidden
11716 patterns to the list.
11718 @defmac m4_pattern_forbid (@var{pattern})
11719 @msindex{pattern_forbid}
11720 Declare that no token matching @var{pattern} must be found in the output.
11721 Comments are not checked; this can be a problem if, for instance, you
11722 have some macro left unexpanded after an @samp{#include}.  No consensus
11723 is currently found in the Autoconf community, as some people consider it
11724 should be valid to name macros in comments (which doesn't make sense to
11725 the authors of this documentation: input, such as macros, should be
11726 documented by @samp{dnl} comments; reserving @samp{#}-comments to
11727 document the output).
11728 @end defmac
11730 Of course, you might encounter exceptions to these generic rules, for
11731 instance you might have to refer to @samp{$m4_flags}.
11733 @defmac m4_pattern_allow (@var{pattern})
11734 @msindex{pattern_allow}
11735 Any token matching @var{pattern} is allowed, including if it matches an
11736 @code{m4_pattern_forbid} pattern.
11737 @end defmac
11739 @node Programming in M4sh
11740 @section Programming in M4sh
11742 @c FIXME: Eventually will become a chapter, as it is not related to
11743 @c programming in M4 per se.
11745 M4sh, pronounced ``mash'', is aiming at producing portable Bourne shell
11746 scripts.  This name was coined by Lars J. Aas, who notes that,
11747 according to the Webster's Revised Unabridged Dictionary (1913):
11749 @quotation
11750 Mash \Mash\, n.  [Akin to G. meisch, maisch, meische, maische, mash,
11751 wash, and prob.@: to AS. miscian to mix.  See ``Mix''.]
11753 @enumerate 1
11754 @item
11755 A mass of mixed ingredients reduced to a soft pulpy state by beating or
11756 pressure@enddots{}
11758 @item
11759 A mixture of meal or bran and water fed to animals.
11761 @item
11762 A mess; trouble.  [Obs.] --Beau.@: & Fl.
11763 @end enumerate
11764 @end quotation
11767 For the time being, it is not mature enough to be widely used.
11769 M4sh reserves the M4 macro namespace @samp{^_AS_} for internal use, and
11770 the namespace @samp{^AS_} for M4sh macros.  It also reserves the shell
11771 and environment variable namespace @samp{^as_}, and the here-doc
11772 delimiter namespace @samp{^_AS[A-Z]} in the output file.  You should not
11773 define your own macros or output shell code that conflicts with these
11774 namespaces.
11776 M4sh provides portable alternatives for some common shell constructs
11777 that unfortunately are not portable in practice.
11779 @c Deprecated, to be replaced by a better API
11780 @ignore
11781 @defmac AS_BASENAME (@var{file-name})
11782 @asindex{BASENAME}
11783 Output the non-directory portion of @var{file-name}.  For example,
11784 if @code{$file} is @samp{/one/two/three}, the command
11785 @code{base=`AS_BASENAME(["$file"])`} sets @code{base} to @samp{three}.
11786 @end defmac
11787 @end ignore
11789 @defmac AS_BOURNE_COMPATIBLE
11790 @asindex{BOURNE_COMPATIBLE}
11791 Set up the shell to be more compatible with the Bourne shell as
11792 standardized by Posix, if possible.  This may involve setting
11793 environment variables, or setting options, or similar
11794 implementation-specific actions.
11795 @end defmac
11797 @defmac AS_CASE (@var{word}, @ovar{pattern1}, @ovar{if-matched1}, @
11798   @dots{}, @ovar{default})
11799 @asindex{CASE}
11800 Expand into a shell @samp{case} statement, where @var{word} is matched
11801 against one or more patterns.  @var{if-matched} is run if the
11802 corresponding pattern matched @var{word}, else @var{default} is run.
11803 @end defmac
11805 @defmac AS_DIRNAME (@var{file-name})
11806 @asindex{DIRNAME}
11807 Output the directory portion of @var{file-name}.  For example,
11808 if @code{$file} is @samp{/one/two/three}, the command
11809 @code{dir=`AS_DIRNAME(["$file"])`} sets @code{dir} to @samp{/one/two}.
11810 @end defmac
11812 @defmac AS_IF (@var{test1}, @ovar{run-if-true1}, @dots{}, @ovar{run-if-false})
11813 @asindex{IF}
11814 Run shell code @var{test1}.  If @var{test1} exits with a zero status then
11815 run shell code @var{run-if-true1}, else examine further tests.  If no test
11816 exits with a zero status, run shell code @var{run-if-false}, with
11817 simplifications if either @var{run-if-true1} or @var{run-if-false1}
11818 is empty.  For example,
11820 @example
11821 AS_IF([test "$foo" = yes], [HANDLE_FOO([yes])],
11822       [test "$foo" != no], [HANDLE_FOO([maybe])],
11823       [echo foo not specified])
11824 @end example
11826 @noindent
11827 ensures any required macros of @code{HANDLE_FOO}
11828 are expanded before the first test.
11829 @end defmac
11831 @defmac AS_INIT
11832 @asindex{INIT}
11833 Initialize the M4sh environment.  This macro calls @code{m4_init}, then
11834 outputs the @code{#! /bin/sh} line, a notice about where the output was
11835 generated from, and code to sanitize the environment for the rest of the
11836 script.  Finally, it changes the current diversion to @code{BODY}.
11837 @end defmac
11839 @defmac AS_MKDIR_P (@var{file-name})
11840 @asindex{MKDIR_P}
11841 Make the directory @var{file-name}, including intervening directories
11842 as necessary.  This is equivalent to @samp{mkdir -p @var{file-name}},
11843 except that it is portable to older versions of @command{mkdir} that
11844 lack support for the @option{-p} option.  Also, @code{AS_MKDIR_P}
11845 succeeds if @var{file-name} is a symbolic link to an existing directory,
11846 even though Posix is unclear whether @samp{mkdir -p} should
11847 succeed in that case.  If creation of @var{file-name} fails, exit the
11848 script.
11850 Also see the @code{AC_PROG_MKDIR_P} macro (@pxref{Particular Programs}).
11851 @end defmac
11853 @defmac AS_SHELL_SANITIZE
11854 @asindex{SHELL_SANITIZE}
11855 Initialize the shell suitably for @command{configure} scripts.  This has
11856 the effect of @code{AS_BOURNE_COMPATIBLE}, and sets some other
11857 environment variables for predictable results from configuration tests.
11858 For example, it sets @env{LC_ALL} to change to the default C locale.
11859 @xref{Special Shell Variables}.
11860 @end defmac
11862 @defmac AS_TR_CPP (@var{expression})
11863 @asindex{TR_CPP}
11864 Transform @var{expression} into a valid right-hand side for a C @code{#define}.
11865 For example:
11867 @example
11868 # This outputs "#define HAVE_CHAR_P 1".
11869 type="char *"
11870 echo "#define AS_TR_CPP([HAVE_$type]) 1"
11871 @end example
11872 @end defmac
11874 @defmac AS_TR_SH (@var{expression})
11875 @asindex{TR_SH}
11876 Transform @var{expression} into a valid shell variable name.  For example:
11878 @example
11879 # This outputs "Have it!".
11880 header="sys/some file.h"
11881 AS_TR_SH([HAVE_$header])=yes
11882 if test "$HAVE_sys_some_file_h" = yes; then echo "Have it!"; fi
11883 @end example
11884 @end defmac
11886 @defmac AS_SET_CATFILE (@var{var}, @var{dir}, @var{file})
11887 @asindex{SET_CATFILE}
11888 Set the shell variable @var{var} to @var{dir}/@var{file}, but
11889 optimizing the common cases (@var{dir} or @var{file} is @samp{.},
11890 @var{file} is absolute, etc.).
11891 @end defmac
11894 @node File Descriptor Macros
11895 @section File Descriptor Macros
11896 @cindex input
11897 @cindex standard input
11898 @cindex file descriptors
11899 @cindex descriptors
11900 @cindex low-level output
11901 @cindex output, low-level
11903 The following macros define file descriptors used to output messages
11904 (or input values) from @file{configure} scripts.
11905 For example:
11907 @example
11908 echo "$wombats found" >&AS_MESSAGE_LOG_FD
11909 echo 'Enter desired kangaroo count:' >&AS_MESSAGE_FD
11910 read kangaroos <&AS_ORIGINAL_STDIN_FD`
11911 @end example
11913 @noindent
11914 However doing so is seldom needed, because Autoconf provides higher
11915 level macros as described below.
11917 @defmac AS_MESSAGE_FD
11918 @asindex{MESSAGE_FD}
11919 The file descriptor for @samp{checking for...}  messages and results.
11920 Normally this directs messages to the standard output, however when
11921 @command{configure} is run with the @option{-q} option, messages sent to
11922 @code{AS_MESSAGE_FD} are discarded.
11924 If you want to display some messages, consider using one of the printing
11925 macros (@pxref{Printing Messages}) instead.  Copies of messages output
11926 via these macros are also recorded in @file{config.log}.
11927 @end defmac
11929 @defmac AS_MESSAGE_LOG_FD
11930 @asindex{MESSAGE_LOG_FD}
11932 The file descriptor for messages logged to @file{config.log}.  Macros
11933 that run tools, like @code{AC_COMPILE_IFELSE} (@pxref{Running the
11934 Compiler}), redirect all output to this descriptor.  You may want to do
11935 so if you develop such a low-level macro.
11936 @end defmac
11938 @defmac AS_ORIGINAL_STDIN_FD
11939 @asindex{ORIGINAL_STDIN_FD}
11940 The file descriptor for the original standard input.
11942 When @command{configure} runs, it may accidentally execute an
11943 interactive command that has the same name as the non-interactive meant
11944 to be used or checked.  If the standard input was the terminal, such
11945 interactive programs would cause @command{configure} to stop, pending
11946 some user input.  Therefore @command{configure} redirects its standard
11947 input from @file{/dev/null} during its initialization.  This is not
11948 normally a problem, since @command{configure} normally does not need
11949 user input.
11951 In the extreme case where your @file{configure} script really needs to
11952 obtain some values from the original standard input, you can read them
11953 explicitly from @code{AS_ORIGINAL_STDIN_FD}.
11954 @end defmac
11957 @c =================================================== Writing Autoconf Macros.
11959 @node Writing Autoconf Macros
11960 @chapter Writing Autoconf Macros
11962 When you write a feature test that could be applicable to more than one
11963 software package, the best thing to do is encapsulate it in a new macro.
11964 Here are some instructions and guidelines for writing Autoconf macros.
11966 @menu
11967 * Macro Definitions::           Basic format of an Autoconf macro
11968 * Macro Names::                 What to call your new macros
11969 * Reporting Messages::          Notifying @command{autoconf} users
11970 * Dependencies Between Macros::  What to do when macros depend on other macros
11971 * Obsoleting Macros::           Warning about old ways of doing things
11972 * Coding Style::                Writing Autoconf macros @`a la Autoconf
11973 @end menu
11975 @node Macro Definitions
11976 @section Macro Definitions
11978 @acindex{DEFUN}
11979 Autoconf macros are defined using the @code{AC_DEFUN} macro, which is
11980 similar to the M4 builtin @code{m4_define} macro.  In addition to
11981 defining a macro, @code{AC_DEFUN} adds to it some code that is used to
11982 constrain the order in which macros are called (@pxref{Prerequisite
11983 Macros}).
11985 An Autoconf macro definition looks like this:
11987 @example
11988 AC_DEFUN(@var{macro-name}, @var{macro-body})
11989 @end example
11991 You can refer to any arguments passed to the macro as @samp{$1},
11992 @samp{$2}, etc.  @xref{Definitions, , How to define new macros, m4.info,
11993 @acronym{GNU} M4}, for more complete information on writing M4 macros.
11995 Be sure to properly quote both the @var{macro-body} @emph{and} the
11996 @var{macro-name} to avoid any problems if the macro happens to have
11997 been previously defined.
11999 Each macro should have a header comment that gives its prototype, and a
12000 brief description.  When arguments have default values, display them in
12001 the prototype.  For example:
12003 @example
12004 # AC_MSG_ERROR(ERROR, [EXIT-STATUS = 1])
12005 # --------------------------------------
12006 m4_define([AC_MSG_ERROR],
12007   [@{ AS_MESSAGE([error: $1], [2])
12008      exit m4_default([$2], [1]); @}])
12009 @end example
12011 Comments about the macro should be left in the header comment.  Most
12012 other comments make their way into @file{configure}, so just keep
12013 using @samp{#} to introduce comments.
12015 @cindex @code{dnl}
12016 If you have some special comments about pure M4 code, comments
12017 that make no sense in @file{configure} and in the header comment, then
12018 use the builtin @code{dnl}: it causes M4 to discard the text
12019 through the next newline.
12021 Keep in mind that @code{dnl} is rarely needed to introduce comments;
12022 @code{dnl} is more useful to get rid of the newlines following macros
12023 that produce no output, such as @code{AC_REQUIRE}.
12026 @node Macro Names
12027 @section Macro Names
12029 All of the public Autoconf macros have all-uppercase names in the
12030 namespace @samp{^AC_} to prevent them from accidentally conflicting with
12031 other text; Autoconf also reserves the namespace @samp{^_AC_} for
12032 internal macros.  All shell variables that they use for internal
12033 purposes have mostly-lowercase names starting with @samp{ac_}.  Autoconf
12034 also uses here-doc delimiters in the namespace @samp{^_AC[A-Z]}.  During
12035 @command{configure}, files produced by Autoconf make heavy use of the
12036 file system namespace @samp{^conf}.
12038 Since Autoconf is built on top of M4sugar (@pxref{Programming in
12039 M4sugar}) and M4sh (@pxref{Programming in M4sh}), you must also be aware
12040 of those namespaces (@samp{^_?\(m4\|AS\)_}).  And since
12041 @file{configure.ac} is also designed to be scanned by Autoheader,
12042 Autoscan, Autoupdate, and Automake, you should be aware of the
12043 @samp{^_?A[HNUM]_} namespaces.  In general, you @emph{should not use}
12044 the namespace of a package that does not own the macro or shell code you
12045 are writing.
12047 To ensure that your macros don't conflict with present or future
12048 Autoconf macros, you should prefix your own macro names and any shell
12049 variables they use with some other sequence.  Possibilities include your
12050 initials, or an abbreviation for the name of your organization or
12051 software package.  Historically, people have not always followed the
12052 rule of using a namespace appropriate for their package, and this has
12053 made it difficult for determining the origin of a macro (and where to
12054 report bugs about that macro), as well as difficult for the true
12055 namespace owner to add new macros without interference from pre-existing
12056 uses of third-party macros.  Perhaps the best example of this confusion
12057 is the @code{AM_GNU_GETTEXT} macro, which belongs, not to Automake, but
12058 to Gettext.
12060 Most of the Autoconf macros' names follow a structured naming convention
12061 that indicates the kind of feature check by the name.  The macro names
12062 consist of several words, separated by underscores, going from most
12063 general to most specific.  The names of their cache variables use the
12064 same convention (@pxref{Cache Variable Names}, for more information on
12065 them).
12067 The first word of the name after the namepace initials (such as
12068 @samp{AC_}) usually tells the category
12069 of the feature being tested.  Here are the categories used in Autoconf for
12070 specific test macros, the kind of macro that you are more likely to
12071 write.  They are also used for cache variables, in all-lowercase.  Use
12072 them where applicable; where they're not, invent your own categories.
12074 @table @code
12075 @item C
12076 C language builtin features.
12077 @item DECL
12078 Declarations of C variables in header files.
12079 @item FUNC
12080 Functions in libraries.
12081 @item GROUP
12082 Posix group owners of files.
12083 @item HEADER
12084 Header files.
12085 @item LIB
12086 C libraries.
12087 @item PROG
12088 The base names of programs.
12089 @item MEMBER
12090 Members of aggregates.
12091 @item SYS
12092 Operating system features.
12093 @item TYPE
12094 C builtin or declared types.
12095 @item VAR
12096 C variables in libraries.
12097 @end table
12099 After the category comes the name of the particular feature being
12100 tested.  Any further words in the macro name indicate particular aspects
12101 of the feature.  For example, @code{AC_PROG_CC_STDC} checks whether the
12102 C compiler supports @acronym{ISO} Standard C.
12104 An internal macro should have a name that starts with an underscore;
12105 Autoconf internals should therefore start with @samp{_AC_}.
12106 Additionally, a macro that is an internal subroutine of another macro
12107 should have a name that starts with an underscore and the name of that
12108 other macro, followed by one or more words saying what the internal
12109 macro does.  For example, @code{AC_PATH_X} has internal macros
12110 @code{_AC_PATH_X_XMKMF} and @code{_AC_PATH_X_DIRECT}.
12112 @node Reporting Messages
12113 @section Reporting Messages
12114 @cindex Messages, from @command{autoconf}
12116 When macros statically diagnose abnormal situations, benign or fatal, it
12117 is possible to make @command{autoconf} detect the problem, and refuse to
12118 create @file{configure} in the case of an error.  The macros in this
12119 section are considered obsolescent, and new code should use M4sugar
12120 macros for this purpose, see @ref{Diagnostic Macros}.
12122 On the other hand, it is possible to want to detect errors when
12123 @command{configure} is run, which are dependent on the environment of
12124 the user rather than the maintainer.  For dynamic diagnostics, see
12125 @ref{Printing Messages}.
12127 @defmac AC_DIAGNOSE (@var{category}, @var{message})
12128 @acindex{DIAGNOSE}
12129 Report @var{message} as a warning (or as an error if requested by the
12130 user) if warnings of the @var{category} are turned on.  This macro is
12131 obsolescent; you are encouraged to use:
12132 @example
12133 m4_warn([@var{category}], [@var{message}])
12134 @end example
12135 @noindent
12136 instead.  @xref{m4_warn}, for more details, including valid
12137 @var{category} names.
12138 @end defmac
12140 @defmac AC_WARNING (@var{message})
12141 @acindex{WARNING}
12142 Report @var{message} as a syntax warning.  This macro is obsolescent;
12143 you are encouraged to use:
12144 @example
12145 m4_warn([syntax], [@var{message}])
12146 @end example
12147 @noindent
12148 instead.  @xref{m4_warn}, for more details, as well as better
12149 finer-grained categories of warnings (not all problems have to do with
12150 syntax).
12151 @end defmac
12153 @defmac AC_FATAL (@var{message})
12154 @acindex{FATAL}
12155 Report a severe error @var{message}, and have @command{autoconf} die.
12156 This macro is obsolescent; you are encouraged to use:
12157 @example
12158 m4_fatal([@var{message}])
12159 @end example
12160 @noindent
12161 instead.  @xref{m4_fatal}, for more details.
12162 @end defmac
12164 When the user runs @samp{autoconf -W error}, warnings from
12165 @code{m4_warn} (including those issued through @code{AC_DIAGNOSE} and
12166 @code{AC_WARNING}) are reported as errors, see @ref{autoconf Invocation}.
12168 @node Dependencies Between Macros
12169 @section Dependencies Between Macros
12170 @cindex Dependencies between macros
12172 Some Autoconf macros depend on other macros having been called first in
12173 order to work correctly.  Autoconf provides a way to ensure that certain
12174 macros are called if needed and a way to warn the user if macros are
12175 called in an order that might cause incorrect operation.
12177 @menu
12178 * Prerequisite Macros::         Ensuring required information
12179 * Suggested Ordering::          Warning about possible ordering problems
12180 * One-Shot Macros::             Ensuring a macro is called only once
12181 @end menu
12183 @node Prerequisite Macros
12184 @subsection Prerequisite Macros
12185 @cindex Prerequisite macros
12186 @cindex Macros, prerequisites
12188 A macro that you write might need to use values that have previously
12189 been computed by other macros.  For example, @code{AC_DECL_YYTEXT}
12190 examines the output of @code{flex} or @code{lex}, so it depends on
12191 @code{AC_PROG_LEX} having been called first to set the shell variable
12192 @code{LEX}.
12194 Rather than forcing the user of the macros to keep track of the
12195 dependencies between them, you can use the @code{AC_REQUIRE} macro to do
12196 it automatically.  @code{AC_REQUIRE} can ensure that a macro is only
12197 called if it is needed, and only called once.
12199 @defmac AC_REQUIRE (@var{macro-name})
12200 @acindex{REQUIRE}
12201 If the M4 macro @var{macro-name} has not already been called, call it
12202 (without any arguments).  Make sure to quote @var{macro-name} with
12203 square brackets.  @var{macro-name} must have been defined using
12204 @code{AC_DEFUN} or else contain a call to @code{AC_PROVIDE} to indicate
12205 that it has been called.
12207 @code{AC_REQUIRE} must be used inside a macro defined by @code{AC_DEFUN}; it
12208 must not be called from the top level.
12209 @end defmac
12211 @code{AC_REQUIRE} is often misunderstood.  It really implements
12212 dependencies between macros in the sense that if one macro depends upon
12213 another, the latter is expanded @emph{before} the body of the
12214 former.  To be more precise, the required macro is expanded before
12215 the outermost defined macro in the current expansion stack.
12216 In particular, @samp{AC_REQUIRE([FOO])} is not replaced with the body of
12217 @code{FOO}.  For instance, this definition of macros:
12219 @example
12220 @group
12221 AC_DEFUN([TRAVOLTA],
12222 [test "$body_temperature_in_celsius" -gt "38" &&
12223   dance_floor=occupied])
12224 AC_DEFUN([NEWTON_JOHN],
12225 [test "$hair_style" = "curly" &&
12226   dance_floor=occupied])
12227 @end group
12229 @group
12230 AC_DEFUN([RESERVE_DANCE_FLOOR],
12231 [if date | grep '^Sat.*pm' >/dev/null 2>&1; then
12232   AC_REQUIRE([TRAVOLTA])
12233   AC_REQUIRE([NEWTON_JOHN])
12234 fi])
12235 @end group
12236 @end example
12238 @noindent
12239 with this @file{configure.ac}
12241 @example
12242 AC_INIT([Dance Manager], [1.0], [bug-dance@@example.org])
12243 RESERVE_DANCE_FLOOR
12244 if test "$dance_floor" = occupied; then
12245   AC_MSG_ERROR([cannot pick up here, let's move])
12247 @end example
12249 @noindent
12250 does not leave you with a better chance to meet a kindred soul at
12251 other times than Saturday night since it expands into:
12253 @example
12254 @group
12255 test "$body_temperature_in_Celsius" -gt "38" &&
12256   dance_floor=occupied
12257 test "$hair_style" = "curly" &&
12258   dance_floor=occupied
12260 if date | grep '^Sat.*pm' >/dev/null 2>&1; then
12264 @end group
12265 @end example
12267 This behavior was chosen on purpose: (i) it prevents messages in
12268 required macros from interrupting the messages in the requiring macros;
12269 (ii) it avoids bad surprises when shell conditionals are used, as in:
12271 @example
12272 @group
12273 if @dots{}; then
12274   AC_REQUIRE([SOME_CHECK])
12276 @dots{}
12277 SOME_CHECK
12278 @end group
12279 @end example
12281 The helper macros @code{AS_IF} and @code{AS_CASE} may be used to
12282 enforce expansion of required macros outside of shell conditional
12283 constructs.  You are furthermore encouraged to put all @code{AC_REQUIRE} calls
12284 at the beginning of a macro.  You can use @code{dnl} to avoid the empty
12285 lines they leave.
12287 @node Suggested Ordering
12288 @subsection Suggested Ordering
12289 @cindex Macros, ordering
12290 @cindex Ordering macros
12292 Some macros should be run before another macro if both are called, but
12293 neither @emph{requires} that the other be called.  For example, a macro
12294 that changes the behavior of the C compiler should be called before any
12295 macros that run the C compiler.  Many of these dependencies are noted in
12296 the documentation.
12298 Autoconf provides the @code{AC_BEFORE} macro to warn users when macros
12299 with this kind of dependency appear out of order in a
12300 @file{configure.ac} file.  The warning occurs when creating
12301 @command{configure} from @file{configure.ac}, not when running
12302 @command{configure}.
12304 For example, @code{AC_PROG_CPP} checks whether the C compiler
12305 can run the C preprocessor when given the @option{-E} option.  It should
12306 therefore be called after any macros that change which C compiler is
12307 being used, such as @code{AC_PROG_CC}.  So @code{AC_PROG_CC} contains:
12309 @example
12310 AC_BEFORE([$0], [AC_PROG_CPP])dnl
12311 @end example
12313 @noindent
12314 This warns the user if a call to @code{AC_PROG_CPP} has already occurred
12315 when @code{AC_PROG_CC} is called.
12317 @defmac AC_BEFORE (@var{this-macro-name}, @var{called-macro-name})
12318 @acindex{BEFORE}
12319 Make M4 print a warning message to the standard error output if
12320 @var{called-macro-name} has already been called.  @var{this-macro-name}
12321 should be the name of the macro that is calling @code{AC_BEFORE}.  The
12322 macro @var{called-macro-name} must have been defined using
12323 @code{AC_DEFUN} or else contain a call to @code{AC_PROVIDE} to indicate
12324 that it has been called.
12325 @end defmac
12327 @node One-Shot Macros
12328 @subsection One-Shot Macros
12329 @cindex One-shot macros
12330 @cindex Macros, called once
12332 Some macros should be called only once, either because calling them
12333 multiple time is unsafe, or because it is bad style.  For instance
12334 Autoconf ensures that @code{AC_CANONICAL_BUILD} and cousins
12335 (@pxref{Canonicalizing}) are evaluated only once, because it makes no
12336 sense to run these expensive checks more than once.  Such one-shot
12337 macros can be defined using @code{AC_DEFUN_ONCE}.
12339 @defmac AC_DEFUN_ONCE (@var{macro-name}, @var{macro-body})
12340 @acindex{DEFUN_ONCE}
12342 Declare macro @var{macro-name} like @code{AC_DEFUN} would (@pxref{Macro
12343 Definitions}), and emit a warning any time the macro is called more than
12344 once.
12345 @end defmac
12347 Obviously it is not sensible to evaluate a macro defined by
12348 @code{AC_DEFUN_ONCE} in a macro defined by @code{AC_DEFUN}.
12349 Most of the time you want to use @code{AC_REQUIRE} (@pxref{Prerequisite
12350 Macros}).
12352 @node Obsoleting Macros
12353 @section Obsoleting Macros
12354 @cindex Obsoleting macros
12355 @cindex Macros, obsoleting
12357 Configuration and portability technology has evolved over the years.
12358 Often better ways of solving a particular problem are developed, or
12359 ad-hoc approaches are systematized.  This process has occurred in many
12360 parts of Autoconf.  One result is that some of the macros are now
12361 considered @dfn{obsolete}; they still work, but are no longer considered
12362 the best thing to do, hence they should be replaced with more modern
12363 macros.  Ideally, @command{autoupdate} should replace the old macro calls
12364 with their modern implementation.
12366 Autoconf provides a simple means to obsolete a macro.
12368 @anchor{AU_DEFUN}
12369 @defmac AU_DEFUN (@var{old-macro}, @var{implementation}, @ovar{message})
12370 @auindex{DEFUN}
12371 Define @var{old-macro} as @var{implementation}.  The only difference
12372 with @code{AC_DEFUN} is that the user is warned that
12373 @var{old-macro} is now obsolete.
12375 If she then uses @command{autoupdate}, the call to @var{old-macro} is
12376 replaced by the modern @var{implementation}.  @var{message} should
12377 include information on what to do after running @command{autoupdate};
12378 @command{autoupdate} prints it as a warning, and includes it
12379 in the updated @file{configure.ac} file.
12381 The details of this macro are hairy: if @command{autoconf} encounters an
12382 @code{AU_DEFUN}ed macro, all macros inside its second argument are expanded
12383 as usual.  However, when @command{autoupdate} is run, only M4 and M4sugar
12384 macros are expanded here, while all other macros are disabled and
12385 appear literally in the updated @file{configure.ac}.
12386 @end defmac
12388 @defmac AU_ALIAS (@var{old-name}, @var{new-name})
12389 @auindex{ALIAS}
12390 Used if the @var{old-name} is to be replaced by a call to @var{new-macro}
12391 with the same parameters.  This happens for example if the macro was renamed.
12392 @end defmac
12394 @node Coding Style
12395 @section Coding Style
12396 @cindex Coding style
12398 The Autoconf macros follow a strict coding style.  You are encouraged to
12399 follow this style, especially if you intend to distribute your macro,
12400 either by contributing it to Autoconf itself, or via other means.
12402 The first requirement is to pay great attention to the quotation.  For
12403 more details, see @ref{Autoconf Language}, and @ref{M4 Quotation}.
12405 Do not try to invent new interfaces.  It is likely that there is a macro
12406 in Autoconf that resembles the macro you are defining: try to stick to
12407 this existing interface (order of arguments, default values, etc.).  We
12408 @emph{are} conscious that some of these interfaces are not perfect;
12409 nevertheless, when harmless, homogeneity should be preferred over
12410 creativity.
12412 Be careful about clashes both between M4 symbols and between shell
12413 variables.
12415 If you stick to the suggested M4 naming scheme (@pxref{Macro Names}),
12416 you are unlikely to generate conflicts.  Nevertheless, when you need to
12417 set a special value, @emph{avoid using a regular macro name}; rather,
12418 use an ``impossible'' name.  For instance, up to version 2.13, the macro
12419 @code{AC_SUBST} used to remember what @var{symbol} macros were already defined
12420 by setting @code{AC_SUBST_@var{symbol}}, which is a regular macro name.
12421 But since there is a macro named @code{AC_SUBST_FILE}, it was just
12422 impossible to @samp{AC_SUBST(FILE)}!  In this case,
12423 @code{AC_SUBST(@var{symbol})} or @code{_AC_SUBST(@var{symbol})} should
12424 have been used (yes, with the parentheses).
12425 @c or better yet, high-level macros such as @code{m4_expand_once}
12427 No Autoconf macro should ever enter the user-variable name space; i.e.,
12428 except for the variables that are the actual result of running the
12429 macro, all shell variables should start with @code{ac_}.  In
12430 addition, small macros or any macro that is likely to be embedded in
12431 other macros should be careful not to use obvious names.
12433 @cindex @code{dnl}
12434 Do not use @code{dnl} to introduce comments: most of the comments you
12435 are likely to write are either header comments which are not output
12436 anyway, or comments that should make their way into @file{configure}.
12437 There are exceptional cases where you do want to comment special M4
12438 constructs, in which case @code{dnl} is right, but keep in mind that it
12439 is unlikely.
12441 M4 ignores the leading blanks and newlines before each argument.
12442 Use this feature to
12443 indent in such a way that arguments are (more or less) aligned with the
12444 opening parenthesis of the macro being called.  For instance, instead of
12446 @example
12447 AC_CACHE_CHECK(for EMX OS/2 environment,
12448 ac_cv_emxos2,
12449 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM(, [return __EMX__;])],
12450 [ac_cv_emxos2=yes], [ac_cv_emxos2=no])])
12451 @end example
12453 @noindent
12454 write
12456 @example
12457 AC_CACHE_CHECK([for EMX OS/2 environment], [ac_cv_emxos2],
12458 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([], [return __EMX__;])],
12459                    [ac_cv_emxos2=yes],
12460                    [ac_cv_emxos2=no])])
12461 @end example
12463 @noindent
12464 or even
12466 @example
12467 AC_CACHE_CHECK([for EMX OS/2 environment],
12468                [ac_cv_emxos2],
12469                [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([],
12470                                                    [return __EMX__;])],
12471                                   [ac_cv_emxos2=yes],
12472                                   [ac_cv_emxos2=no])])
12473 @end example
12475 When using @code{AC_RUN_IFELSE} or any macro that cannot work when
12476 cross-compiling, provide a pessimistic value (typically @samp{no}).
12478 Feel free to use various tricks to prevent auxiliary tools, such as
12479 syntax-highlighting editors, from behaving improperly.  For instance,
12480 instead of:
12482 @example
12483 m4_bpatsubst([$1], [$"])
12484 @end example
12486 @noindent
12489 @example
12490 m4_bpatsubst([$1], [$""])
12491 @end example
12493 @noindent
12494 so that Emacsen do not open an endless ``string'' at the first quote.
12495 For the same reasons, avoid:
12497 @example
12498 test $[#] != 0
12499 @end example
12501 @noindent
12502 and use:
12504 @example
12505 test $[@@%:@@] != 0
12506 @end example
12508 @noindent
12509 Otherwise, the closing bracket would be hidden inside a @samp{#}-comment,
12510 breaking the bracket-matching highlighting from Emacsen.  Note the
12511 preferred style to escape from M4: @samp{$[1]}, @samp{$[@@]}, etc.  Do
12512 not escape when it is unnecessary.  Common examples of useless quotation
12513 are @samp{[$]$1} (write @samp{$$1}), @samp{[$]var} (use @samp{$var}),
12514 etc.  If you add portability issues to the picture, you'll prefer
12515 @samp{$@{1+"$[@@]"@}} to @samp{"[$]@@"}, and you'll prefer do something
12516 better than hacking Autoconf @code{:-)}.
12518 When using @command{sed}, don't use @option{-e} except for indenting
12519 purposes.  With the @code{s} and @code{y} commands, the preferred
12520 separator is @samp{/} unless @samp{/} itself might appear in the pattern
12521 or replacement, in which case you should use @samp{|}, or optionally
12522 @samp{,} if you know the pattern and replacement cannot contain a file
12523 name.  If none of these characters will do, choose a printable character
12524 that cannot appear in the pattern or replacement.  Characters from the
12525 set @samp{"#$&'()*;<=>?`|~} are good choices if the pattern or
12526 replacement might contain a file name, since they have special meaning
12527 to the shell and are less likely to occur in file names.
12529 @xref{Macro Definitions}, for details on how to define a macro.  If a
12530 macro doesn't use @code{AC_REQUIRE}, is expected to never be the object
12531 of an @code{AC_REQUIRE} directive, and macros required by other macros
12532 inside arguments do not need to be expanded before this macro, then
12533 use @code{m4_define}.  In case of doubt, use @code{AC_DEFUN}.
12534 All the @code{AC_REQUIRE} statements should be at the beginning of the
12535 macro, and each statement should be followed by @code{dnl}.
12537 You should not rely on the number of arguments: instead of checking
12538 whether an argument is missing, test that it is not empty.  It provides
12539 both a simpler and a more predictable interface to the user, and saves
12540 room for further arguments.
12542 Unless the macro is short, try to leave the closing @samp{])} at the
12543 beginning of a line, followed by a comment that repeats the name of the
12544 macro being defined.  This introduces an additional newline in
12545 @command{configure}; normally, that is not a problem, but if you want to
12546 remove it you can use @samp{[]dnl} on the last line.  You can similarly
12547 use @samp{[]dnl} after a macro call to remove its newline.  @samp{[]dnl}
12548 is recommended instead of @samp{dnl} to ensure that M4 does not
12549 interpret the @samp{dnl} as being attached to the preceding text or
12550 macro output.  For example, instead of:
12552 @example
12553 AC_DEFUN([AC_PATH_X],
12554 [AC_MSG_CHECKING([for X])
12555 AC_REQUIRE_CPP()
12556 @r{# @dots{}omitted@dots{}}
12557   AC_MSG_RESULT([libraries $x_libraries, headers $x_includes])
12558 fi])
12559 @end example
12561 @noindent
12562 you would write:
12564 @example
12565 AC_DEFUN([AC_PATH_X],
12566 [AC_REQUIRE_CPP()[]dnl
12567 AC_MSG_CHECKING([for X])
12568 @r{# @dots{}omitted@dots{}}
12569   AC_MSG_RESULT([libraries $x_libraries, headers $x_includes])
12570 fi[]dnl
12571 ])# AC_PATH_X
12572 @end example
12574 If the macro is long, try to split it into logical chunks.  Typically,
12575 macros that check for a bug in a function and prepare its
12576 @code{AC_LIBOBJ} replacement should have an auxiliary macro to perform
12577 this setup.  Do not hesitate to introduce auxiliary macros to factor
12578 your code.
12580 In order to highlight the recommended coding style, here is a macro
12581 written the old way:
12583 @example
12584 dnl Check for EMX on OS/2.
12585 dnl _AC_EMXOS2
12586 AC_DEFUN(_AC_EMXOS2,
12587 [AC_CACHE_CHECK(for EMX OS/2 environment, ac_cv_emxos2,
12588 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM(, return __EMX__;)],
12589 ac_cv_emxos2=yes, ac_cv_emxos2=no)])
12590 test "$ac_cv_emxos2" = yes && EMXOS2=yes])
12591 @end example
12593 @noindent
12594 and the new way:
12596 @example
12597 # _AC_EMXOS2
12598 # ----------
12599 # Check for EMX on OS/2.
12600 m4_define([_AC_EMXOS2],
12601 [AC_CACHE_CHECK([for EMX OS/2 environment], [ac_cv_emxos2],
12602 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([], [return __EMX__;])],
12603                    [ac_cv_emxos2=yes],
12604                    [ac_cv_emxos2=no])])
12605 test "$ac_cv_emxos2" = yes && EMXOS2=yes[]dnl
12606 ])# _AC_EMXOS2
12607 @end example
12612 @c ============================================= Portable Shell Programming
12614 @node Portable Shell
12615 @chapter Portable Shell Programming
12616 @cindex Portable shell programming
12618 When writing your own checks, there are some shell-script programming
12619 techniques you should avoid in order to make your code portable.  The
12620 Bourne shell and upward-compatible shells like the Korn shell and Bash
12621 have evolved over the years, but to prevent trouble, do not take
12622 advantage of features that were added after Unix version 7, circa
12623 1977 (@pxref{Systemology}).
12625 You should not use aliases, negated character classes, or other features
12626 that are not found in all Bourne-compatible shells; restrict yourself
12627 to the lowest common denominator.  Even @code{unset} is not supported
12628 by all shells!
12630 Shell functions are considered portable nowadays, though Autoconf still
12631 does not use them (Autotest does).  However, some pitfalls have to be
12632 avoided for portable use of shell functions (@pxref{Shell Functions}).
12634 Some ancient systems have quite
12635 small limits on the length of the @samp{#!} line; for instance, 32
12636 bytes (not including the newline) on SunOS 4.
12637 A few ancient 4.2@acronym{BSD} based systems (such as Dynix circa 1984)
12638 required a single space between the @samp{#!} and the @samp{/}.
12639 However, these ancient systems are no longer of practical concern.
12641 The set of external programs you should run in a @command{configure} script
12642 is fairly small.  @xref{Utilities in Makefiles, , Utilities in
12643 Makefiles, standards, @acronym{GNU} Coding Standards}, for the list.  This
12644 restriction allows users to start out with a fairly small set of
12645 programs and build the rest, avoiding too many interdependencies between
12646 packages.
12648 Some of these external utilities have a portable subset of features; see
12649 @ref{Limitations of Usual Tools}.
12651 There are other sources of documentation about shells.  The
12652 specification for the Posix
12653 @uref{http://www.opengroup.org/@/susv3/@/utilities/@/xcu_chap02.html, Shell
12654 Command Language}, though more generous than the restrictive shell
12655 subset described above, is fairly portable nowadays.  Also please see
12656 @uref{http://www.faqs.org/@/faqs/@/unix-faq/@/shell/, the Shell FAQs}.
12658 @menu
12659 * Shellology::                  A zoology of shells
12660 * Here-Documents::              Quirks and tricks
12661 * File Descriptors::            FDs and redirections
12662 * File System Conventions::     File names
12663 * Shell Pattern Matching::      Pattern matching
12664 * Shell Substitutions::         Variable and command expansions
12665 * Assignments::                 Varying side effects of assignments
12666 * Parentheses::                 Parentheses in shell scripts
12667 * Slashes::                     Slashes in shell scripts
12668 * Special Shell Variables::     Variables you should not change
12669 * Shell Functions::             What to look out for if you use them
12670 * Limitations of Builtins::     Portable use of not so portable /bin/sh
12671 * Limitations of Usual Tools::  Portable use of portable tools
12672 @end menu
12674 @node Shellology
12675 @section Shellology
12676 @cindex Shellology
12678 There are several families of shells, most prominently the Bourne family
12679 and the C shell family which are deeply incompatible.  If you want to
12680 write portable shell scripts, avoid members of the C shell family.  The
12681 @uref{http://www.faqs.org/@/faqs/@/unix-faq/@/shell/@/shell-differences/, the
12682 Shell difference FAQ} includes a small history of Posix shells, and a
12683 comparison between several of them.
12685 Below we describe some of the members of the Bourne shell family.
12687 @table @asis
12688 @item Ash
12689 @cindex Ash
12690 Ash is often used on @acronym{GNU}/Linux and @acronym{BSD}
12691 systems as a light-weight Bourne-compatible shell.  Ash 0.2 has some
12692 bugs that are fixed in the 0.3.x series, but portable shell scripts
12693 should work around them, since version 0.2 is still shipped with many
12694 @acronym{GNU}/Linux distributions.
12696 To be compatible with Ash 0.2:
12698 @itemize @minus
12699 @item
12700 don't use @samp{$?} after expanding empty or unset variables,
12701 or at the start of an @command{eval}:
12703 @example
12704 foo=
12705 false
12706 $foo
12707 echo "Do not use it: $?"
12708 false
12709 eval 'echo "Do not use it: $?"'
12710 @end example
12712 @item
12713 don't use command substitution within variable expansion:
12715 @example
12716 cat $@{FOO=`bar`@}
12717 @end example
12719 @item
12720 beware that single builtin substitutions are not performed by a
12721 subshell, hence their effect applies to the current shell!  @xref{Shell
12722 Substitutions}, item ``Command Substitution''.
12723 @end itemize
12725 @item Bash
12726 @cindex Bash
12727 To detect whether you are running Bash, test whether
12728 @code{BASH_VERSION} is set.  To require
12729 Posix compatibility, run @samp{set -o posix}.  @xref{Bash POSIX
12730 Mode, , Bash Posix Mode, bash, The @acronym{GNU} Bash Reference
12731 Manual}, for details.
12733 @item Bash 2.05 and later
12734 @cindex Bash 2.05 and later
12735 Versions 2.05 and later of Bash use a different format for the
12736 output of the @command{set} builtin, designed to make evaluating its
12737 output easier.  However, this output is not compatible with earlier
12738 versions of Bash (or with many other shells, probably).  So if
12739 you use Bash 2.05 or higher to execute @command{configure},
12740 you'll need to use Bash 2.05 for all other build tasks as well.
12742 @item Ksh
12743 @cindex Ksh
12744 @cindex Korn shell
12745 @prindex @samp{ksh}
12746 @prindex @samp{ksh88}
12747 @prindex @samp{ksh93}
12748 The Korn shell is compatible with the Bourne family and it mostly
12749 conforms to Posix.  It has two major variants commonly
12750 called @samp{ksh88} and @samp{ksh93}, named after the years of initial
12751 release.  It is usually called @command{ksh}, but is called @command{sh}
12752 on some hosts if you set your path appropriately.
12754 Solaris systems have three variants:
12755 @prindex @command{/usr/bin/ksh} on Solaris
12756 @command{/usr/bin/ksh} is @samp{ksh88}; it is
12757 standard on Solaris 2.0 and later.
12758 @prindex @command{/usr/xpg4/bin/sh} on Solaris
12759 @command{/usr/xpg4/bin/sh} is a Posix-compliant variant of
12760 @samp{ksh88}; it is standard on Solaris 9 and later.
12761 @prindex @command{/usr/dt/bin/dtksh} on Solaris
12762 @command{/usr/dt/bin/dtksh} is @samp{ksh93}.
12763 Variants that are not standard may be parts of optional
12764 packages.  There is no extra charge for these packages, but they are
12765 not part of a minimal OS install and therefore some installations may
12766 not have it.
12768 Starting with Tru64 Version 4.0, the Korn shell @command{/usr/bin/ksh}
12769 is also available as @command{/usr/bin/posix/sh}.  If the environment
12770 variable @env{BIN_SH} is set to @code{xpg4}, subsidiary invocations of
12771 the standard shell conform to Posix.
12773 @item Pdksh
12774 @prindex @samp{pdksh}
12775 A public-domain clone of the Korn shell called @command{pdksh} is widely
12776 available: it has most of the @samp{ksh88} features along with a few of
12777 its own.  It usually sets @code{KSH_VERSION}, except if invoked as
12778 @command{/bin/sh} on Open@acronym{BSD}, and similarly to Bash you can require
12779 Posix compatibility by running @samp{set -o posix}.  Unfortunately, with
12780 @command{pdksh} 5.2.14 (the latest stable version as of January 2007)
12781 Posix mode is buggy and causes @command{pdksh} to depart from Posix in
12782 at least one respect:
12784 @example
12785 $ @kbd{echo "`echo \"hello\"`"}
12786 hello
12787 $ @kbd{set -o posix}
12788 $ @kbd{echo "`echo \"hello\"`"}
12789 "hello"
12790 @end example
12792 The last line of output contains spurious quotes.  This is yet another
12793 reason why portable shell code should not contain
12794 @code{"`@dots{}\"@dots{}\"@dots{}`"} constructs (@pxref{Shell
12795 Substitutions}).
12797 @item Zsh
12798 @cindex Zsh
12799 To detect whether you are running @command{zsh}, test whether
12800 @code{ZSH_VERSION} is set.  By default @command{zsh} is @emph{not}
12801 compatible with the Bourne shell: you must execute @samp{emulate sh},
12802 and for @command{zsh} versions before 3.1.6-dev-18 you must also
12803 set @code{NULLCMD} to @samp{:}.  @xref{Compatibility, , Compatibility,
12804 zsh, The Z Shell Manual}, for details.
12806 The default Mac OS X @command{sh} was originally Zsh; it was changed to
12807 Bash in Mac OS X 10.2.
12808 @end table
12810 The following discussion between Russ Allbery and Robert Lipe is worth
12811 reading:
12813 @noindent
12814 Russ Allbery:
12816 @quotation
12817 The @acronym{GNU} assumption that @command{/bin/sh} is the one and only shell
12818 leads to a permanent deadlock.  Vendors don't want to break users'
12819 existing shell scripts, and there are some corner cases in the Bourne
12820 shell that are not completely compatible with a Posix shell.  Thus,
12821 vendors who have taken this route will @emph{never} (OK@dots{}``never say
12822 never'') replace the Bourne shell (as @command{/bin/sh}) with a
12823 Posix shell.
12824 @end quotation
12826 @noindent
12827 Robert Lipe:
12829 @quotation
12830 This is exactly the problem.  While most (at least most System V's) do
12831 have a Bourne shell that accepts shell functions most vendor
12832 @command{/bin/sh} programs are not the Posix shell.
12834 So while most modern systems do have a shell @emph{somewhere} that meets the
12835 Posix standard, the challenge is to find it.
12836 @end quotation
12838 @node Here-Documents
12839 @section Here-Documents
12840 @cindex Here-documents
12841 @cindex Shell here-documents
12843 Don't rely on @samp{\} being preserved just because it has no special
12844 meaning together with the next symbol.  In the native @command{sh}
12845 on Open@acronym{BSD} 2.7 @samp{\"} expands to @samp{"} in here-documents with
12846 unquoted delimiter.  As a general rule, if @samp{\\} expands to @samp{\}
12847 use @samp{\\} to get @samp{\}.
12849 With Open@acronym{BSD} 2.7's @command{sh}
12851 @example
12852 @group
12853 $ @kbd{cat <<EOF
12854 > \" \\
12855 > EOF}
12856 " \
12857 @end group
12858 @end example
12860 @noindent
12861 and with Bash:
12863 @example
12864 @group
12865 bash-2.04$ @kbd{cat <<EOF
12866 > \" \\
12867 > EOF}
12868 \" \
12869 @end group
12870 @end example
12872 Some shells mishandle large here-documents: for example,
12873 Solaris 10 @command{dtksh} and the UnixWare 7.1.1 Posix shell, which are
12874 derived from Korn shell version M-12/28/93d, mishandle braced variable
12875 expansion that crosses a 1024- or 4096-byte buffer boundary
12876 within a here-document.  Only the part of the variable name after the boundary
12877 is used.  For example, @code{$@{variable@}} could be replaced by the expansion
12878 of @code{$@{ble@}}.  If the end of the variable name is aligned with the block
12879 boundary, the shell reports an error, as if you used @code{$@{@}}.
12880 Instead of @code{$@{variable-default@}}, the shell may expand
12881 @code{$@{riable-default@}}, or even @code{$@{fault@}}.  This bug can often
12882 be worked around by omitting the braces: @code{$variable}.  The bug was
12883 fixed in
12884 @samp{ksh93g} (1998-04-30) but as of 2006 many operating systems were
12885 still shipping older versions with the bug.
12887 Many shells (including the Bourne shell) implement here-documents
12888 inefficiently.  In particular, some shells can be extremely inefficient when
12889 a single statement contains many here-documents.  For instance if your
12890 @file{configure.ac} includes something like:
12892 @example
12893 @group
12894 if <cross_compiling>; then
12895   assume this and that
12896 else
12897   check this
12898   check that
12899   check something else
12900   @dots{}
12901   on and on forever
12902   @dots{}
12904 @end group
12905 @end example
12907 A shell parses the whole @code{if}/@code{fi} construct, creating
12908 temporary files for each here-document in it.  Some shells create links
12909 for such here-documents on every @code{fork}, so that the clean-up code
12910 they had installed correctly removes them.  It is creating the links
12911 that can take the shell forever.
12913 Moving the tests out of the @code{if}/@code{fi}, or creating multiple
12914 @code{if}/@code{fi} constructs, would improve the performance
12915 significantly.  Anyway, this kind of construct is not exactly the
12916 typical use of Autoconf.  In fact, it's even not recommended, because M4
12917 macros can't look into shell conditionals, so we may fail to expand a
12918 macro when it was expanded before in a conditional path, and the
12919 condition turned out to be false at runtime, and we end up not
12920 executing the macro at all.
12922 @node File Descriptors
12923 @section File Descriptors
12924 @cindex Descriptors
12925 @cindex File descriptors
12926 @cindex Shell file descriptors
12928 Most shells, if not all (including Bash, Zsh, Ash), output traces on
12929 stderr, even for subshells.  This might result in undesirable content
12930 if you meant to capture the standard-error output of the inner command:
12932 @example
12933 $ @kbd{ash -x -c '(eval "echo foo >&2") 2>stderr'}
12934 $ @kbd{cat stderr}
12935 + eval echo foo >&2
12936 + echo foo
12938 $ @kbd{bash -x -c '(eval "echo foo >&2") 2>stderr'}
12939 $ @kbd{cat stderr}
12940 + eval 'echo foo >&2'
12941 ++ echo foo
12943 $ @kbd{zsh -x -c '(eval "echo foo >&2") 2>stderr'}
12944 @i{# Traces on startup files deleted here.}
12945 $ @kbd{cat stderr}
12946 +zsh:1> eval echo foo >&2
12947 +zsh:1> echo foo
12949 @end example
12951 @noindent
12952 One workaround is to grep out uninteresting lines, hoping not to remove
12953 good ones.
12955 If you intend to redirect both standard error and standard output,
12956 redirect standard output first.  This works better with @acronym{HP-UX},
12957 since its shell mishandles tracing if standard error is redirected
12958 first:
12960 @example
12961 $ @kbd{sh -x -c ': 2>err >out'}
12962 + :
12963 + 2> err $ @kbd{cat err}
12964 1> out
12965 @end example
12967 Don't try to redirect the standard error of a command substitution.  It
12968 must be done @emph{inside} the command substitution.  When running
12969 @samp{: `cd /zorglub` 2>/dev/null} expect the error message to
12970 escape, while @samp{: `cd /zorglub 2>/dev/null`} works properly.
12972 It is worth noting that Zsh (but not Ash nor Bash) makes it possible
12973 in assignments though: @samp{foo=`cd /zorglub` 2>/dev/null}.
12975 When catering to old systems, don't redirect the same file descriptor
12976 several times, as you are doomed to failure under Ultrix.
12978 @example
12979 ULTRIX V4.4 (Rev. 69) System #31: Thu Aug 10 19:42:23 GMT 1995
12980 UWS V4.4 (Rev. 11)
12981 $ @kbd{eval 'echo matter >fullness' >void}
12982 illegal io
12983 $ @kbd{eval '(echo matter >fullness)' >void}
12984 illegal io
12985 $ @kbd{(eval '(echo matter >fullness)') >void}
12986 Ambiguous output redirect.
12987 @end example
12989 @noindent
12990 In each case the expected result is of course @file{fullness} containing
12991 @samp{matter} and @file{void} being empty.  However, this bug is
12992 probably not of practical concern to modern platforms.
12994 Don't rely on file descriptors 0, 1, and 2 remaining closed in a
12995 subsidiary program.  If any of these descriptors is closed, the
12996 operating system may open an unspecified file for the descriptor in the
12997 new process image.  Posix says this may be done only if the subsidiary
12998 program is set-user-ID or set-group-ID, but @acronym{HP-UX} 11.23 does
12999 it even for ordinary programs.
13001 Don't rely on open file descriptors being open in child processes.  In
13002 @command{ksh}, file descriptors above 2 which are opened using
13003 @samp{exec @var{n}>file} are closed by a subsequent @samp{exec} (such as
13004 that involved in the fork-and-exec which runs a program or script).
13005 Thus, using @command{sh}, we have:
13007 @example
13008 $ @kbd{cat ./descrips}
13009 #!/bin/sh -
13010 echo hello >&5
13011 $ @kbd{exec 5>t}
13012 $ @kbd{./descrips}
13013 $ @kbd{cat t}
13014 hello
13016 @end example
13018 @noindent
13019 But using ksh:
13021 @example
13022 $ @kbd{exec 5>t}
13023 $ @kbd{./descrips}
13024 hello
13025 $ @kbd{cat t}
13027 @end example
13029 @noindent
13030 Within the process which runs the @samp{descrips} script, file
13031 descriptor 5 is closed.
13033 Don't rely on redirection to a closed file descriptor to cause an
13034 error.  With Solaris @command{/bin/sh}, when the redirection fails, the
13035 output goes to the original file descriptor.
13037 @example
13038 $ @kbd{bash -c 'echo hi >&3' 3>&-; echo $?}
13039 bash: 3: Bad file descriptor
13041 $ @kbd{/bin/sh -c 'echo hi >&3' 3>&-; echo $?}
13044 @end example
13046 @acronym{DOS} variants cannot rename or remove open files, such as in
13047 @samp{mv foo bar >foo} or @samp{rm foo >foo}, even though this is
13048 perfectly portable among Posix hosts.
13050 A few ancient systems reserved some file descriptors.  By convention,
13051 file descriptor 3 was opened to @file{/dev/tty} when you logged into
13052 Eighth Edition (1985) through Tenth Edition Unix (1989).  File
13053 descriptor 4 had a special use on the Stardent/Kubota Titan (circa
13054 1990), though we don't now remember what it was.  Both these systems are
13055 obsolete, so it's now safe to treat file descriptors 3 and 4 like any
13056 other file descriptors.
13058 @node File System Conventions
13059 @section File System Conventions
13060 @cindex File system conventions
13062 Autoconf uses shell-script processing extensively, so the file names
13063 that it processes should not contain characters that are special to the
13064 shell.  Special characters include space, tab, newline, @sc{nul}, and
13065 the following:
13067 @example
13068 " # $ & ' ( ) * ; < = > ? [ \ ` |
13069 @end example
13071 Also, file names should not begin with @samp{~} or @samp{-}, and should
13072 contain neither @samp{-} immediately after @samp{/} nor @samp{~}
13073 immediately after @samp{:}.  On Posix-like platforms, directory names
13074 should not contain @samp{:}, as this runs afoul of @samp{:} used as the
13075 path separator.
13077 These restrictions apply not only to the files that you distribute, but
13078 also to the absolute file names of your source, build, and destination
13079 directories.
13081 On some Posix-like platforms, @samp{!} and @samp{^} are special too, so
13082 they should be avoided.
13084 Posix lets implementations treat leading @file{//} specially, but
13085 requires leading @file{///} and beyond to be equivalent to @file{/}.
13086 Most Unix variants treat @file{//} like @file{/}.  However, some treat
13087 @file{//} as a ``super-root'' that can provide access to files that are
13088 not otherwise reachable from @file{/}.  The super-root tradition began
13089 with Apollo Domain/OS, which died out long ago, but unfortunately Cygwin
13090 has revived it.
13092 While @command{autoconf} and friends are usually run on some Posix
13093 variety, they can be used on other systems, most notably @acronym{DOS}
13094 variants.  This impacts several assumptions regarding file names.
13096 @noindent
13097 For example, the following code:
13099 @example
13100 case $foo_dir in
13101   /*) # Absolute
13102      ;;
13103   *)
13104      foo_dir=$dots$foo_dir ;;
13105 esac
13106 @end example
13108 @noindent
13109 fails to properly detect absolute file names on those systems, because
13110 they can use a drivespec, and usually use a backslash as directory
13111 separator.  If you want to be portable to @acronym{DOS} variants (at the
13112 price of rejecting valid but oddball Posix file names like @file{a:\b}),
13113 you can check for absolute file names like this:
13115 @cindex absolute file names, detect
13116 @example
13117 case $foo_dir in
13118   [\\/]* | ?:[\\/]* ) # Absolute
13119      ;;
13120   *)
13121      foo_dir=$dots$foo_dir ;;
13122 esac
13123 @end example
13125 @noindent
13126 Make sure you quote the brackets if appropriate and keep the backslash as
13127 first character (@pxref{Limitations of Builtins}).
13129 Also, because the colon is used as part of a drivespec, these systems don't
13130 use it as path separator.  When creating or accessing paths, you can use the
13131 @code{PATH_SEPARATOR} output variable instead.  @command{configure} sets this
13132 to the appropriate value for the build system (@samp{:} or @samp{;}) when it
13133 starts up.
13135 File names need extra care as well.  While @acronym{DOS} variants
13136 that are Posixy enough to run @command{autoconf} (such as @acronym{DJGPP})
13137 are usually able to handle long file names properly, there are still
13138 limitations that can seriously break packages.  Several of these issues
13139 can be easily detected by the
13140 @uref{ftp://ftp.gnu.org/gnu/non-gnu/doschk/doschk-1.1.tar.gz, doschk}
13141 package.
13143 A short overview follows; problems are marked with @sc{sfn}/@sc{lfn} to
13144 indicate where they apply: @sc{sfn} means the issues are only relevant to
13145 plain @acronym{DOS}, not to @acronym{DOS} under Microsoft Windows
13146 variants, while @sc{lfn} identifies problems that exist even under
13147 Microsoft Windows variants.
13149 @table @asis
13150 @item No multiple dots (@sc{sfn})
13151 @acronym{DOS} cannot handle multiple dots in file names.  This is an especially
13152 important thing to remember when building a portable configure script,
13153 as @command{autoconf} uses a .in suffix for template files.
13155 This is perfectly OK on Posix variants:
13157 @example
13158 AC_CONFIG_HEADERS([config.h])
13159 AC_CONFIG_FILES([source.c foo.bar])
13160 AC_OUTPUT
13161 @end example
13163 @noindent
13164 but it causes problems on @acronym{DOS}, as it requires @samp{config.h.in},
13165 @samp{source.c.in} and @samp{foo.bar.in}.  To make your package more portable
13166 to @acronym{DOS}-based environments, you should use this instead:
13168 @example
13169 AC_CONFIG_HEADERS([config.h:config.hin])
13170 AC_CONFIG_FILES([source.c:source.cin foo.bar:foobar.in])
13171 AC_OUTPUT
13172 @end example
13174 @item No leading dot (@sc{sfn})
13175 @acronym{DOS} cannot handle file names that start with a dot.  This is usually
13176 not important for @command{autoconf}.
13178 @item Case insensitivity (@sc{lfn})
13179 @acronym{DOS} is case insensitive, so you cannot, for example, have both a
13180 file called @samp{INSTALL} and a directory called @samp{install}.  This
13181 also affects @command{make}; if there's a file called @samp{INSTALL} in
13182 the directory, @samp{make install} does nothing (unless the
13183 @samp{install} target is marked as PHONY).
13185 @item The 8+3 limit (@sc{sfn})
13186 Because the @acronym{DOS} file system only stores the first 8 characters of
13187 the file name and the first 3 of the extension, those must be unique.
13188 That means that @file{foobar-part1.c}, @file{foobar-part2.c} and
13189 @file{foobar-prettybird.c} all resolve to the same file name
13190 (@file{FOOBAR-P.C}).  The same goes for @file{foo.bar} and
13191 @file{foo.bartender}.
13193 The 8+3 limit is not usually a problem under Microsoft Windows, as it
13194 uses numeric
13195 tails in the short version of file names to make them unique.  However, a
13196 registry setting can turn this behavior off.  While this makes it
13197 possible to share file trees containing long file names between @sc{sfn}
13198 and @sc{lfn} environments, it also means the above problem applies there
13199 as well.
13201 @item Invalid characters (@sc{lfn})
13202 Some characters are invalid in @acronym{DOS} file names, and should therefore
13203 be avoided.  In a @sc{lfn} environment, these are @samp{/}, @samp{\},
13204 @samp{?}, @samp{*}, @samp{:}, @samp{<}, @samp{>}, @samp{|} and @samp{"}.
13205 In a @sc{sfn} environment, other characters are also invalid.  These
13206 include @samp{+}, @samp{,}, @samp{[} and @samp{]}.
13208 @item Invalid names (@sc{lfn})
13209 Some @acronym{DOS} file names are reserved, and cause problems if you
13210 try to use files with those names.  These names include @file{CON},
13211 @file{AUX}, @file{COM1}, @file{COM2}, @file{COM3}, @file{COM4},
13212 @file{LPT1}, @file{LPT2}, @file{LPT3}, @file{NUL}, and @file{PRN}.
13213 File names are case insensitive, so even names like
13214 @file{aux/config.guess} are disallowed.
13216 @end table
13218 @node Shell Pattern Matching
13219 @section Shell Pattern Matching
13220 @cindex Shell pattern matching
13222 Nowadays portable patterns can use negated character classes like
13223 @samp{[!-aeiou]}.  The older syntax @samp{[^-aeiou]} is supported by
13224 some shells but not others; hence portable scripts should never use
13225 @samp{^} as the first character of a bracket pattern.
13227 Outside the C locale, patterns like @samp{[a-z]} are problematic since
13228 they may match characters that are not lower-case letters.
13230 @node Shell Substitutions
13231 @section Shell Substitutions
13232 @cindex Shell substitutions
13234 Contrary to a persistent urban legend, the Bourne shell does not
13235 systematically split variables and back-quoted expressions, in particular
13236 on the right-hand side of assignments and in the argument of @code{case}.
13237 For instance, the following code:
13239 @example
13240 case "$given_srcdir" in
13241 .)  top_srcdir="`echo "$dots" | sed 's|/$||'`" ;;
13242 *)  top_srcdir="$dots$given_srcdir" ;;
13243 esac
13244 @end example
13246 @noindent
13247 is more readable when written as:
13249 @example
13250 case $given_srcdir in
13251 .)  top_srcdir=`echo "$dots" | sed 's|/$||'` ;;
13252 *)  top_srcdir=$dots$given_srcdir ;;
13253 esac
13254 @end example
13256 @noindent
13257 and in fact it is even @emph{more} portable: in the first case of the
13258 first attempt, the computation of @code{top_srcdir} is not portable,
13259 since not all shells properly understand @code{"`@dots{}"@dots{}"@dots{}`"}.
13260 Worse yet, not all shells understand @code{"`@dots{}\"@dots{}\"@dots{}`"}
13261 the same way.  There is just no portable way to use double-quoted
13262 strings inside double-quoted back-quoted expressions (pfew!).
13264 @table @code
13265 @item $@@
13266 @cindex @samp{"$@@"}
13267 One of the most famous shell-portability issues is related to
13268 @samp{"$@@"}.  When there are no positional arguments, Posix says
13269 that @samp{"$@@"} is supposed to be equivalent to nothing, but the
13270 original Unix version 7 Bourne shell treated it as equivalent to
13271 @samp{""} instead, and this behavior survives in later implementations
13272 like Digital Unix 5.0.
13274 The traditional way to work around this portability problem is to use
13275 @samp{$@{1+"$@@"@}}.  Unfortunately this method does not work with
13276 Zsh (3.x and 4.x), which is used on Mac OS X@.  When emulating
13277 the Bourne shell, Zsh performs word splitting on @samp{$@{1+"$@@"@}}:
13279 @example
13280 zsh $ @kbd{emulate sh}
13281 zsh $ @kbd{for i in "$@@"; do echo $i; done}
13282 Hello World
13284 zsh $ @kbd{for i in $@{1+"$@@"@}; do echo $i; done}
13285 Hello
13286 World
13288 @end example
13290 @noindent
13291 Zsh handles plain @samp{"$@@"} properly, but we can't use plain
13292 @samp{"$@@"} because of the portability problems mentioned above.
13293 One workaround relies on Zsh's ``global aliases'' to convert
13294 @samp{$@{1+"$@@"@}} into @samp{"$@@"} by itself:
13296 @example
13297 test "$@{ZSH_VERSION+set@}" = set && alias -g '$@{1+"$@@"@}'='"$@@"'
13298 @end example
13300 Zsh only recognizes this alias when a shell word matches it exactly;
13301 @samp{"foo"$@{1+"$@@"@}} remains subject to word splitting.  Since this
13302 case always yields at least one shell word, use plain @samp{"$@@"}.
13304 A more conservative workaround is to avoid @samp{"$@@"} if it is
13305 possible that there may be no positional arguments.  For example,
13306 instead of:
13308 @example
13309 cat conftest.c "$@@"
13310 @end example
13312 you can use this instead:
13314 @example
13315 case $# in
13316 0) cat conftest.c;;
13317 *) cat conftest.c "$@@";;
13318 esac
13319 @end example
13321 Autoconf macros often use the @command{set} command to update
13322 @samp{$@@}, so if you are writing shell code intended for
13323 @command{configure} you should not assume that the value of @samp{$@@}
13324 persists for any length of time.
13327 @item $@{10@}
13328 @cindex positional parameters
13329 The 10th, 11th, @dots{} positional parameters can be accessed only after
13330 a @code{shift}.  The 7th Edition shell reported an error if given
13331 @code{$@{10@}}, and
13332 Solaris 10 @command{/bin/sh} still acts that way:
13334 @example
13335 $ @kbd{set 1 2 3 4 5 6 7 8 9 10}
13336 $ @kbd{echo $@{10@}}
13337 bad substitution
13338 @end example
13340 @item $@{@var{var}:-@var{value}@}
13341 @c Info cannot handle `:' in index entries.
13342 @c @cindex $@{@var{var}:-@var{value}@}
13343 Old @acronym{BSD} shells, including the Ultrix @code{sh}, don't accept the
13344 colon for any shell substitution, and complain and die.
13345 Similarly for $@{@var{var}:=@var{value}@}, $@{@var{var}:?@var{value}@}, etc.
13347 @item $@{@var{var}=@var{literal}@}
13348 @cindex $@{@var{var}=@var{literal}@}
13349 Be sure to quote:
13351 @example
13352 : $@{var='Some words'@}
13353 @end example
13355 @noindent
13356 otherwise some shells, such as on Digital Unix V 5.0, die because
13357 of a ``bad substitution''.
13359 @sp 1
13361 Solaris @command{/bin/sh} has a frightening bug in its interpretation
13362 of this.  Imagine you need set a variable to a string containing
13363 @samp{@}}.  This @samp{@}} character confuses Solaris @command{/bin/sh}
13364 when the affected variable was already set.  This bug can be exercised
13365 by running:
13367 @example
13368 $ @kbd{unset foo}
13369 $ @kbd{foo=$@{foo='@}'@}}
13370 $ @kbd{echo $foo}
13372 $ @kbd{foo=$@{foo='@}'   # no error; this hints to what the bug is}
13373 $ @kbd{echo $foo}
13375 $ @kbd{foo=$@{foo='@}'@}}
13376 $ @kbd{echo $foo}
13377 @}@}
13378  ^ ugh!
13379 @end example
13381 It seems that @samp{@}} is interpreted as matching @samp{$@{}, even
13382 though it is enclosed in single quotes.  The problem doesn't happen
13383 using double quotes.
13385 @item $@{@var{var}=@var{expanded-value}@}
13386 @cindex $@{@var{var}=@var{expanded-value}@}
13387 On Ultrix,
13388 running
13390 @example
13391 default="yu,yaa"
13392 : $@{var="$default"@}
13393 @end example
13395 @noindent
13396 sets @var{var} to @samp{M-yM-uM-,M-yM-aM-a}, i.e., the 8th bit of
13397 each char is set.  You don't observe the phenomenon using a simple
13398 @samp{echo $var} since apparently the shell resets the 8th bit when it
13399 expands $var.  Here are two means to make this shell confess its sins:
13401 @example
13402 $ @kbd{cat -v <<EOF
13403 $var
13404 EOF}
13405 @end example
13407 @noindent
13410 @example
13411 $ @kbd{set | grep '^var=' | cat -v}
13412 @end example
13414 One classic incarnation of this bug is:
13416 @example
13417 default="a b c"
13418 : $@{list="$default"@}
13419 for c in $list; do
13420   echo $c
13421 done
13422 @end example
13424 @noindent
13425 You'll get @samp{a b c} on a single line.  Why?  Because there are no
13426 spaces in @samp{$list}: there are @samp{M- }, i.e., spaces with the 8th
13427 bit set, hence no IFS splitting is performed!!!
13429 One piece of good news is that Ultrix works fine with @samp{:
13430 $@{list=$default@}}; i.e., if you @emph{don't} quote.  The bad news is
13431 then that @acronym{QNX} 4.25 then sets @var{list} to the @emph{last} item of
13432 @var{default}!
13434 The portable way out consists in using a double assignment, to switch
13435 the 8th bit twice on Ultrix:
13437 @example
13438 list=$@{list="$default"@}
13439 @end example
13441 @noindent
13442 @dots{}but beware of the @samp{@}} bug from Solaris (see above).  For safety,
13443 use:
13445 @example
13446 test "$@{var+set@}" = set || var=@var{@{value@}}
13447 @end example
13449 @item $@{#@var{var}@}
13450 @itemx $@{@var{var}%@var{word}@}
13451 @itemx $@{@var{var}%%@var{word}@}
13452 @itemx $@{@var{var}#@var{word}@}
13453 @itemx $@{@var{var}##@var{word}@}
13454 @cindex $@{#@var{var}@}
13455 @cindex $@{@var{var}%@var{word}@}
13456 @cindex $@{@var{var}%%@var{word}@}
13457 @cindex $@{@var{var}#@var{word}@}
13458 @cindex $@{@var{var}##@var{word}@}
13459 Posix requires support for these usages, but they do not work with many
13460 traditional shells, e.g., Solaris 10 @command{/bin/sh}.
13462 Also, @command{pdksh} 5.2.14 mishandles some @var{word} forms.  For
13463 example if @samp{$1} is @samp{a/b} and @samp{$2} is @samp{a}, then
13464 @samp{$@{1#$2@}} should yield @samp{/b}, but with @command{pdksh} it
13465 yields the empty string.
13468 @item `@var{commands}`
13469 @cindex `@var{commands}`
13470 @cindex Command Substitution
13471 Posix requires shells to trim all trailing newlines from command
13472 output before substituting it, so assignments like
13473 @samp{dir=`echo "$file" | tr a A`} do not work as expected if
13474 @samp{$file} ends in a newline.
13476 While in general it makes no sense, do not substitute a single builtin
13477 with side effects, because Ash 0.2, trying to optimize, does not fork a
13478 subshell to perform the command.
13480 For instance, if you wanted to check that @command{cd} is silent, do not
13481 use @samp{test -z "`cd /`"} because the following can happen:
13483 @example
13484 $ @kbd{pwd}
13485 /tmp
13486 $ @kbd{test -z "`cd /`" && pwd}
13488 @end example
13490 @noindent
13491 The result of @samp{foo=`exit 1`} is left as an exercise to the reader.
13493 The MSYS shell leaves a stray byte in the expansion of a double-quoted
13494 command substitution of a native program, if the end of the substitution
13495 is not aligned with the end of the double quote.  This may be worked
13496 around by inserting another pair of quotes:
13498 @example
13499 $ @kbd{echo "`printf 'foo\r\n'` bar" > broken}
13500 $ @kbd{echo "`printf 'foo\r\n'`"" bar" | cmp - broken}
13501 - broken differ: char 4, line 1
13502 @end example
13504 Upon interrupt or SIGTERM, some shells may abort a command substitution,
13505 replace it with a null string, and wrongly evaluate the enclosing
13506 command before entering the trap or ending the script.  This can lead to
13507 spurious errors:
13509 @example
13510 $ @kbd{sh -c 'if test `sleep 5; echo hi` = hi; then echo yes; fi'}
13511 $ @kbd{^C}
13512 sh: test: hi: unexpected operator/operand
13513 @end example
13515 @noindent
13516 You can avoid this by assigning the command substitution to a temporary
13517 variable:
13519 @example
13520 $ @kbd{sh -c 'res=`sleep 5; echo hi`
13521          if test "x$res" = xhi; then echo yes; fi'}
13522 $ @kbd{^C}
13523 @end example
13525 @item $(@var{commands})
13526 @cindex $(@var{commands})
13527 This construct is meant to replace @samp{`@var{commands}`},
13528 and it has most of the problems listed under @code{`@var{commands}`}.
13530 This construct can be
13531 nested while this is impossible to do portably with back quotes.
13532 Unfortunately it is not yet universally supported.  Most notably, even recent
13533 releases of Solaris don't support it:
13535 @example
13536 $ @kbd{showrev -c /bin/sh | grep version}
13537 Command version: SunOS 5.10 Generic 121005-03 Oct 2006
13538 $ @kbd{echo $(echo blah)}
13539 syntax error: `(' unexpected
13540 @end example
13542 @noindent
13543 nor does @sc{irix} 6.5's Bourne shell:
13544 @example
13545 $ @kbd{uname -a}
13546 IRIX firebird-image 6.5 07151432 IP22
13547 $ @kbd{echo $(echo blah)}
13548 $(echo blah)
13549 @end example
13551 If you do use @samp{$(@var{commands})}, make sure that the commands
13552 do not start with a parenthesis, as that would cause confusion with
13553 a different notation @samp{$((@var{expression}))} that in modern
13554 shells is an arithmetic expression not a command.  To avoid the
13555 confusion, insert a space between the two opening parentheses.
13557 Avoid @var{commands} that contain unbalanced parentheses in
13558 here-documents, comments, or case statement patterns, as many shells
13559 mishandle them.  For example, Bash 3.1, @samp{ksh88}, @command{pdksh}
13560 5.2.14, and Zsh 4.2.6 all mishandle the following valid command:
13562 @example
13563 echo $(case x in x) echo hello;; esac)
13564 @end example
13567 @item $((@var{expression}))
13568 @cindex $((@var{expression}))
13569 Arithmetic expansion is not portable as some shells (most
13570 notably Solaris 10 @command{/bin/sh}) don't support it.
13572 Among shells that do support @samp{$(( ))}, not all of them obey the
13573 Posix rule that octal and hexadecimal constants must be recognized:
13575 @example
13576 $ @kbd{bash -c 'echo $(( 010 + 0x10 ))'}
13578 $ @kbd{zsh -c 'echo $(( 010 + 0x10 ))'}
13580 $ @kbd{zsh -c 'emulate sh; echo $(( 010 + 0x10 ))'}
13582 $ @kbd{pdksh -c 'echo $(( 010 + 0x10 ))'}
13583 pdksh:  010 + 0x10 : bad number `0x10'
13584 $ @kbd{pdksh -c 'echo $(( 010 ))'}
13586 @end example
13588 When it is available, using arithmetic expansion provides a noticeable
13589 speedup in script execution; but testing for support requires
13590 @command{eval} to avoid syntax errors.  If shell function support has
13591 also been detected, then this construct can be used to assign @samp{foo}
13592 to an arithmetic result, provided all numeric arguments are provided in
13593 decimal and without a leading zero:
13595 @example
13596 if ( eval 'test $(( 1 + 1 )) = 2' ) 2>/dev/null; then
13597   eval 'func_arith ()
13598   @{
13599     func_arith_result=$(( $* ))
13600   @}'
13601 else
13602   func_arith ()
13603   @{
13604     func_arith_result=`expr "$@@"`
13605   @}
13607 func_arith 1 + 1
13608 foo=$func_arith_result
13609 @end example
13612 @item ^
13613 @cindex ^ quoting
13614 Always quote @samp{^}, otherwise traditional shells such as
13615 @command{/bin/sh} on Solaris 10 treat this like @samp{|}.
13617 @end table
13620 @node Assignments
13621 @section Assignments
13622 @cindex Shell assignments
13624 When setting several variables in a row, be aware that the order of the
13625 evaluation is undefined.  For instance @samp{foo=1 foo=2; echo $foo}
13626 gives @samp{1} with Solaris @command{/bin/sh}, but @samp{2} with Bash.
13627 You must use
13628 @samp{;} to enforce the order: @samp{foo=1; foo=2; echo $foo}.
13630 Don't rely on the following to find @file{subdir/program}:
13632 @example
13633 PATH=subdir$PATH_SEPARATOR$PATH program
13634 @end example
13636 @noindent
13637 as this does not work with Zsh 3.0.6.  Use something like this
13638 instead:
13640 @example
13641 (PATH=subdir$PATH_SEPARATOR$PATH; export PATH; exec program)
13642 @end example
13644 Don't rely on the exit status of an assignment: Ash 0.2 does not change
13645 the status and propagates that of the last statement:
13647 @example
13648 $ @kbd{false || foo=bar; echo $?}
13650 $ @kbd{false || foo=`:`; echo $?}
13652 @end example
13654 @noindent
13655 and to make things even worse, @acronym{QNX} 4.25 just sets the exit status
13656 to 0 in any case:
13658 @example
13659 $ @kbd{foo=`exit 1`; echo $?}
13661 @end example
13663 To assign default values, follow this algorithm:
13665 @enumerate
13666 @item
13667 If the default value is a literal and does not contain any closing
13668 brace, use:
13670 @example
13671 : $@{var='my literal'@}
13672 @end example
13674 @item
13675 If the default value contains no closing brace, has to be expanded, and
13676 the variable being initialized is not intended to be IFS-split
13677 (i.e., it's not a list), then use:
13679 @example
13680 : $@{var="$default"@}
13681 @end example
13683 @item
13684 If the default value contains no closing brace, has to be expanded, and
13685 the variable being initialized is intended to be IFS-split (i.e., it's a list),
13686 then use:
13688 @example
13689 var=$@{var="$default"@}
13690 @end example
13692 @item
13693 If the default value contains a closing brace, then use:
13695 @example
13696 test "$@{var+set@}" = set || var="has a '@}'"
13697 @end example
13698 @end enumerate
13700 In most cases @samp{var=$@{var="$default"@}} is fine, but in case of
13701 doubt, just use the last form.  @xref{Shell Substitutions}, items
13702 @samp{$@{@var{var}:-@var{value}@}} and @samp{$@{@var{var}=@var{value}@}}
13703 for the rationale.
13705 @node Parentheses
13706 @section Parentheses in Shell Scripts
13707 @cindex Shell parentheses
13709 Beware of two opening parentheses in a row, as many shell
13710 implementations treat them specially.  Posix requires that the command
13711 @samp{((cat))} must behave like @samp{(cat)}, but many shells, including
13712 Bash and the Korn shell, treat @samp{((cat))} as an arithmetic
13713 expression equivalent to @samp{let "cat"}, and may or may not report an
13714 error when they detect that @samp{cat} is not a number.  As another
13715 example, @samp{pdksh} 5.2.14 misparses the following code:
13717 @example
13718 if ((true) || false); then
13719   echo ok
13721 @end example
13723 @noindent
13724 To work around this problem, insert a space between the two opening
13725 parentheses.  There is a similar problem and workaround with
13726 @samp{$((}; see @ref{Shell Substitutions}.
13728 @node Slashes
13729 @section Slashes in Shell Scripts
13730 @cindex Shell slashes
13732 Unpatched Tru64 5.1 @command{sh} omits the last slash of command-line
13733 arguments that contain two trailing slashes:
13735 @example
13736 $ @kbd{echo / // /// //// .// //.}
13737 / / // /// ./ //.
13738 $ @kbd{x=//}
13739 $ @kbd{eval "echo \$x"}
13741 $ @kbd{set -x}
13742 $ @kbd{echo abc | tr -t ab //}
13743 + echo abc
13744 + tr -t ab /
13746 @end example
13748 Unpatched Tru64 4.0 @command{sh} adds a slash after @samp{"$var"} if the
13749 variable is empty and the second double-quote is followed by a word that
13750 begins and ends with slash:
13752 @example
13753 $ @kbd{sh -xc 'p=; echo "$p"/ouch/'}
13755 + echo //ouch/
13756 //ouch/
13757 @end example
13759 However, our understanding is that patches are available, so perhaps
13760 it's not worth worrying about working around these horrendous bugs.
13762 @node Special Shell Variables
13763 @section Special Shell Variables
13764 @cindex Shell variables
13765 @cindex Special shell variables
13767 Some shell variables should not be used, since they can have a deep
13768 influence on the behavior of the shell.  In order to recover a sane
13769 behavior from the shell, some variables should be unset, but
13770 @command{unset} is not portable (@pxref{Limitations of Builtins}) and a
13771 fallback value is needed.
13773 As a general rule, shell variable names containing a lower-case letter
13774 are safe; you can define and use these variables without worrying about
13775 their effect on the underlying system, and without worrying about
13776 whether the shell changes them unexpectedly.  (The exception is the
13777 shell variable @code{status}, as described below.)
13779 Here is a list of names that are known to cause trouble.  This list is
13780 not exhaustive, but you should be safe if you avoid the name
13781 @code{status} and names containing only upper-case letters and
13782 underscores.
13784 @c Alphabetical order, case insensitive, `A' before `a'.
13785 @table @code
13786 @item _
13787 Many shells reserve @samp{$_} for various purposes, e.g., the name of
13788 the last command executed.
13790 @item BIN_SH
13791 @evindex BIN_SH
13792 In Tru64, if @env{BIN_SH} is set to @code{xpg4}, subsidiary invocations of
13793 the standard shell conform to Posix.
13795 @item CDPATH
13796 @evindex CDPATH
13797 When this variable is set it specifies a list of directories to search
13798 when invoking @code{cd} with a relative file name that did not start
13799 with @samp{./} or @samp{../}.  Posix
13800 1003.1-2001 says that if a nonempty directory name from @env{CDPATH}
13801 is used successfully, @code{cd} prints the resulting absolute
13802 file name.  Unfortunately this output can break idioms like
13803 @samp{abs=`cd src && pwd`} because @code{abs} receives the name twice.
13804 Also, many shells do not conform to this part of Posix; for
13805 example, @command{zsh} prints the result only if a directory name
13806 other than @file{.} was chosen from @env{CDPATH}.
13808 In practice the shells that have this problem also support
13809 @command{unset}, so you can work around the problem as follows:
13811 @example
13812 (unset CDPATH) >/dev/null 2>&1 && unset CDPATH
13813 @end example
13815 You can also avoid output by ensuring that your directory name is
13816 absolute or anchored at @samp{./}, as in @samp{abs=`cd ./src && pwd`}.
13818 Autoconf-generated scripts automatically unset @env{CDPATH} if
13819 possible, so you need not worry about this problem in those scripts.
13821 @item DUALCASE
13822 @evindex DUALCASE
13823 In the MKS shell, case statements and file name generation are
13824 case-insensitive unless @env{DUALCASE} is nonzero.
13825 Autoconf-generated scripts export this variable when they start up.
13827 @item ENV
13828 @itemx MAIL
13829 @itemx MAILPATH
13830 @itemx PS1
13831 @itemx PS2
13832 @itemx PS4
13833 @evindex ENV
13834 @evindex MAIL
13835 @evindex MAILPATH
13836 @evindex PS1
13837 @evindex PS2
13838 @evindex PS4
13839 These variables should not matter for shell scripts, since they are
13840 supposed to affect only interactive shells.  However, at least one
13841 shell (the pre-3.0 @sc{uwin} Korn shell) gets confused about
13842 whether it is interactive, which means that (for example) a @env{PS1}
13843 with a side effect can unexpectedly modify @samp{$?}.  To work around
13844 this bug, Autoconf-generated scripts do something like this:
13846 @example
13847 (unset ENV) >/dev/null 2>&1 && unset ENV MAIL MAILPATH
13848 PS1='$ '
13849 PS2='> '
13850 PS4='+ '
13851 @end example
13853 @item FPATH
13854 The Korn shell uses @env{FPATH} to find shell functions, so avoid
13855 @env{FPATH} in portable scripts.  @env{FPATH} is consulted after
13856 @env{PATH}, but you still need to be wary of tests that use @env{PATH}
13857 to find whether a command exists, since they might report the wrong
13858 result if @env{FPATH} is also set.
13860 @item IFS
13861 @evindex IFS
13862 Long ago, shell scripts inherited @env{IFS} from the environment,
13863 but this caused many problems so modern shells ignore any environment
13864 settings for @env{IFS}.
13866 Don't set the first character of @code{IFS} to backslash.  Indeed,
13867 Bourne shells use the first character (backslash) when joining the
13868 components in @samp{"$@@"} and some shells then reinterpret (!)@: the
13869 backslash escapes, so you can end up with backspace and other strange
13870 characters.
13872 The proper value for @code{IFS} (in regular code, not when performing
13873 splits) is @samp{@key{SPC}@key{TAB}@key{RET}}.  The first character is
13874 especially important, as it is used to join the arguments in @samp{$*};
13875 however, note that traditional shells, but also bash-2.04, fail to adhere
13876 to this and join with a space anyway.
13878 @item LANG
13879 @itemx LC_ALL
13880 @itemx LC_COLLATE
13881 @itemx LC_CTYPE
13882 @itemx LC_MESSAGES
13883 @itemx LC_MONETARY
13884 @itemx LC_NUMERIC
13885 @itemx LC_TIME
13886 @evindex LANG
13887 @evindex LC_ALL
13888 @evindex LC_COLLATE
13889 @evindex LC_CTYPE
13890 @evindex LC_MESSAGES
13891 @evindex LC_MONETARY
13892 @evindex LC_NUMERIC
13893 @evindex LC_TIME
13895 Autoconf-generated scripts normally set all these variables to
13896 @samp{C} because so much configuration code assumes the C locale and
13897 Posix requires that locale environment variables be set to
13898 @samp{C} if the C locale is desired.  However, some older, nonstandard
13899 systems (notably @acronym{SCO}) break if locale environment variables
13900 are set to @samp{C}, so when running on these systems
13901 Autoconf-generated scripts unset the variables instead.
13903 @item LANGUAGE
13904 @evindex LANGUAGE
13906 @env{LANGUAGE} is not specified by Posix, but it is a @acronym{GNU}
13907 extension that overrides @env{LC_ALL} in some cases, so
13908 Autoconf-generated scripts set it too.
13910 @item LC_ADDRESS
13911 @itemx LC_IDENTIFICATION
13912 @itemx LC_MEASUREMENT
13913 @itemx LC_NAME
13914 @itemx LC_PAPER
13915 @itemx LC_TELEPHONE
13916 @evindex LC_ADDRESS
13917 @evindex LC_IDENTIFICATION
13918 @evindex LC_MEASUREMENT
13919 @evindex LC_NAME
13920 @evindex LC_PAPER
13921 @evindex LC_TELEPHONE
13923 These locale environment variables are @acronym{GNU} extensions.  They
13924 are treated like their Posix brethren (@env{LC_COLLATE},
13925 etc.)@: as described above.
13927 @item LINENO
13928 Most modern shells provide the current line number in @code{LINENO}.
13929 Its value is the line number of the beginning of the current command.
13930 Autoconf attempts to execute @command{configure} with a shell that
13931 supports @code{LINENO}.
13932 If no such shell is available, it attempts to implement @code{LINENO}
13933 with a Sed prepass that replaces each instance of the string
13934 @code{$LINENO} (not followed by an alphanumeric character) with the
13935 line's number.
13937 You should not rely on @code{LINENO} within @command{eval}, as the
13938 behavior differs in practice.  Also, the possibility of the Sed
13939 prepass means that you should not rely on @code{$LINENO} when quoted,
13940 when in here-documents, or when in long commands that cross line
13941 boundaries.  Subshells should be OK, though.  In the following
13942 example, lines 1, 6, and 9 are portable, but the other instances of
13943 @code{LINENO} are not:
13945 @example
13946 @group
13947 $ @kbd{cat lineno}
13948 echo 1. $LINENO
13949 cat <<EOF
13950 3. $LINENO
13951 4. $LINENO
13953 ( echo 6. $LINENO )
13954 eval 'echo 7. $LINENO'
13955 echo 8. '$LINENO'
13956 echo 9. $LINENO '
13957 10.' $LINENO
13958 @end group
13959 @group
13960 $ @kbd{bash-2.05 lineno}
13961 1. 1
13962 3. 2
13963 4. 2
13964 6. 6
13965 7. 1
13966 8. $LINENO
13967 9. 9
13968 10. 9
13969 @end group
13970 @group
13971 $ @kbd{zsh-3.0.6 lineno}
13972 1. 1
13973 3. 2
13974 4. 2
13975 6. 6
13976 7. 7
13977 8. $LINENO
13978 9. 9
13979 10. 9
13980 @end group
13981 @group
13982 $ @kbd{pdksh-5.2.14 lineno}
13983 1. 1
13984 3. 2
13985 4. 2
13986 6. 6
13987 7. 0
13988 8. $LINENO
13989 9. 9
13990 10. 9
13991 @end group
13992 @group
13993 $ @kbd{sed '=' <lineno |}
13994 > @kbd{  sed '}
13995 > @kbd{    N}
13996 > @kbd{    s,$,-,}
13997 > @kbd{    t loop}
13998 > @kbd{    :loop}
13999 > @kbd{    s,^\([0-9]*\)\(.*\)[$]LINENO\([^a-zA-Z0-9_]\),\1\2\1\3,}
14000 > @kbd{    t loop}
14001 > @kbd{    s,-$,,}
14002 > @kbd{    s,^[0-9]*\n,,}
14003 > @kbd{  ' |}
14004 > @kbd{  sh}
14005 1. 1
14006 3. 3
14007 4. 4
14008 6. 6
14009 7. 7
14010 8. 8
14011 9. 9
14012 10. 10
14013 @end group
14014 @end example
14016 @item NULLCMD
14017 @evindex NULLCMD
14018 When executing the command @samp{>foo}, @command{zsh} executes
14019 @samp{$NULLCMD >foo} unless it is operating in Bourne shell
14020 compatibility mode and the @command{zsh} version is newer
14021 than 3.1.6-dev-18.  If you are using an older @command{zsh}
14022 and forget to set @env{NULLCMD},
14023 your script might be suspended waiting for data on its standard input.
14025 @item PATH_SEPARATOR
14026 @evindex PATH_SEPARATOR
14027 On @acronym{DJGPP} systems, the @env{PATH_SEPARATOR} environment
14028 variable can be set to either @samp{:} or @samp{;} to control the path
14029 separator Bash uses to set up certain environment variables (such as
14030 @env{PATH}).  You can set this variable to @samp{;} if you want
14031 @command{configure} to use @samp{;} as a separator; this might be useful
14032 if you plan to use non-Posix shells to execute files.  @xref{File System
14033 Conventions}, for more information about @code{PATH_SEPARATOR}.
14035 @item PWD
14036 @evindex PWD
14037 Posix 1003.1-2001 requires that @command{cd} and
14038 @command{pwd} must update the @env{PWD} environment variable to point
14039 to the logical name of the current directory, but traditional shells
14040 do not support this.  This can cause confusion if one shell instance
14041 maintains @env{PWD} but a subsidiary and different shell does not know
14042 about @env{PWD} and executes @command{cd}; in this case @env{PWD}
14043 points to the wrong directory.  Use @samp{`pwd`} rather than
14044 @samp{$PWD}.
14046 @item RANDOM
14047 Many shells provide @code{RANDOM}, a variable that returns a different
14048 integer each time it is used.  Most of the time, its value does not
14049 change when it is not used, but on @sc{irix} 6.5 the value changes all
14050 the time.  This can be observed by using @command{set}.  It is common
14051 practice to use @code{$RANDOM} as part of a file name, but code
14052 shouldn't rely on @code{$RANDOM} expanding to a nonempty string.
14054 @item status
14055 This variable is an alias to @samp{$?} for @code{zsh} (at least 3.1.6),
14056 hence read-only.  Do not use it.
14057 @end table
14059 @node Shell Functions
14060 @section Shell Functions
14061 @cindex Shell Functions
14063 Nowadays, it is difficult to find a shell that does not support
14064 shell functions at all.  However, some differences should be expected:
14066 Inside a shell function, you should not rely on the error status of a
14067 subshell if the last command of that subshell was @code{exit} or
14068 @code{trap}, as this triggers bugs in zsh 4.x; while Autoconf tries to
14069 find a shell that does not exhibit the bug, zsh might be the only shell
14070 present on the user's machine.
14072 Likewise, the state of @samp{$?} is not reliable when entering a shell
14073 function.  This has the effect that using a function as the first
14074 command in a @command{trap} handler can cause problems.
14076 @example
14077 $ @kbd{bash -c 'foo()@{ echo $?; @}; trap foo 0; (exit 2); exit 2'; echo $?}
14080 $ @kbd{ash -c 'foo()@{ echo $?; @}; trap foo 0; (exit 2); exit 2'; echo $?}
14083 @end example
14085 Shell variables and functions may share the same namespace, for example
14086 with Solaris 10 @command{/bin/sh}:
14088 @example
14089 $ @kbd{f () @{ :; @}; f=; f}
14090 f: not found
14091 @end example
14093 @noindent
14094 For this reason, Autotest uses the prefix @samp{at_func_} for its
14095 functions.
14097 Handling of positional parameters and shell options varies among shells.
14098 For example, Korn shells reset and restore trace output (@samp{set -x})
14099 and other options upon function entry and exit.  Inside a function,
14100 @acronym{IRIX} sh sets @samp{$0} to the function name.
14102 Some ancient Bourne shell variants with function support did not reset
14103 @samp{$@var{i}, @var{i} >= 0}, upon function exit, so effectively the
14104 arguments of the script were lost after the first function invocation.
14105 It is probably not worth worrying about these shells any more.
14107 With @acronym{AIX} sh, a @command{trap} on 0 installed in a shell function
14108 triggers at function exit rather than at script exit, see @xref{Limitations
14109 of Builtins}.
14111 @node Limitations of Builtins
14112 @section Limitations of Shell Builtins
14113 @cindex Shell builtins
14114 @cindex Limitations of shell builtins
14116 No, no, we are serious: some shells do have limitations!  :)
14118 You should always keep in mind that any builtin or command may support
14119 options, and therefore differ in behavior with arguments
14120 starting with a dash.  For instance, the innocent @samp{echo "$word"}
14121 can give unexpected results when @code{word} starts with a dash.  It is
14122 often possible to avoid this problem using @samp{echo "x$word"}, taking
14123 the @samp{x} into account later in the pipe.
14125 @table @asis
14126 @item @command{.}
14127 @c --------------
14128 @prindex @command{.}
14129 Use @command{.} only with regular files (use @samp{test -f}).  Bash
14130 2.03, for instance, chokes on @samp{. /dev/null}.  Remember that
14131 @command{.} uses @env{PATH} if its argument contains no slashes.  Also,
14132 some shells, including bash 3.2, implicitly append the current directory
14133 to this @env{PATH} search, even though Posix forbids it.  So if you want
14134 to use @command{.} on a file @file{foo} in the current directory, you
14135 must use @samp{. ./foo}.
14137 @item @command{!}
14138 @c --------------
14139 @prindex @command{!}
14140 The Unix version 7 shell did not support
14141 negating the exit status of commands with @command{!}, and this feature
14142 is still absent from some shells (e.g., Solaris @command{/bin/sh}).
14143 Other shells, such as FreeBSD @command{/bin/sh} or @command{ash}, have
14144 bugs when using @command{!}:
14146 @example
14147 $ @kbd{sh -c '! : | :'; echo $?}
14149 $ @kbd{ash -c '! : | :'; echo $?}
14151 $ @kbd{sh -c '! @{ :; @}'; echo $?}
14153 $ @kbd{ash -c '! @{ :; @}'; echo $?}
14154 @{: not found
14155 Syntax error: "@}" unexpected
14157 @end example
14159 Shell code like this:
14161 @example
14162 if ! cmp file1 file2 >/dev/null 2>&1; then
14163   echo files differ or trouble
14165 @end example
14167 is therefore not portable in practice.  Typically it is easy to rewrite
14168 such code, e.g.:
14170 @example
14171 cmp file1 file2 >/dev/null 2>&1 ||
14172   echo files differ or trouble
14173 @end example
14175 More generally, one can always rewrite @samp{! @var{command}} as:
14177 @example
14178 if @var{command}; then (exit 1); else :; fi
14179 @end example
14182 @item @command{@{...@}}
14183 @c --------------------
14184 @prindex @command{@{...@}}
14185 Bash 3.2 (and earlier versions) sometimes does not properly set
14186 @samp{$?} when failing to write redirected output of a compound command.
14187 This problem is most commonly observed with @samp{@{@dots{}@}}; it does
14188 not occur with @samp{(@dots{})}.  For example:
14190 @example
14191 $ @kbd{bash -c '@{ echo foo; @} >/bad; echo $?'}
14192 bash: line 1: /bad: Permission denied
14194 $ @kbd{bash -c 'while :; do echo; done >/bad; echo $?'}
14195 bash: line 1: /bad: Permission denied
14197 @end example
14199 To work around the bug, prepend @samp{:;}:
14201 @example
14202 $ @kbd{bash -c ':;@{ echo foo; @} >/bad; echo $?'}
14203 bash: line 1: /bad: Permission denied
14205 @end example
14208 @item @command{break}
14209 @c ------------------
14210 @prindex @command{break}
14211 The use of @samp{break 2} etc.@: is safe.
14214 @item @command{case}
14215 @c -----------------
14216 @prindex @command{case}
14217 You don't need to quote the argument; no splitting is performed.
14219 You don't need the final @samp{;;}, but you should use it.
14221 Posix requires support for @code{case} patterns with opening
14222 parentheses like this:
14224 @example
14225 case $file_name in
14226   (*.c) echo "C source code";;
14227 esac
14228 @end example
14230 @noindent
14231 but the @code{(} in this example is not portable to many Bourne
14232 shell implementations, which is a pity for those of us using tools that
14233 rely on balanced parentheses.  For instance, with Solaris
14234 @command{/bin/sh}:
14236 @example
14237 $ @kbd{case foo in (foo) echo foo;; esac}
14238 @error{}syntax error: `(' unexpected
14239 @end example
14241 @noindent
14242 The leading @samp{(} can be omitted safely.  In contexts where
14243 unbalanced parentheses cause other problems, such as when using a case
14244 statement as an argument to an Autoconf macro, you can also resort to
14245 creative shell comments to supply the balance:
14247 @example
14248 case $file_name in #(
14249   *.c) echo "C source code";;
14250 esac
14251 @end example
14253 Zsh handles pattern fragments derived from parameter expansions or
14254 command substitutions as though quoted:
14256 @example
14257 $ pat=\?; case aa in ?$pat) echo match;; esac
14258 $ pat=\?; case a? in ?$pat) echo match;; esac
14259 match
14260 @end example
14262 @noindent
14263 Because of a bug in its @code{fnmatch}, Bash fails to properly
14264 handle backslashes in character classes:
14266 @example
14267 bash-2.02$ @kbd{case /tmp in [/\\]*) echo OK;; esac}
14268 bash-2.02$
14269 @end example
14271 @noindent
14272 This is extremely unfortunate, since you are likely to use this code to
14273 handle Posix or @sc{ms-dos} absolute file names.  To work around this
14274 bug, always put the backslash first:
14276 @example
14277 bash-2.02$ @kbd{case '\TMP' in [\\/]*) echo OK;; esac}
14279 bash-2.02$ @kbd{case /tmp in [\\/]*) echo OK;; esac}
14281 @end example
14283 Many Bourne shells cannot handle closing brackets in character classes
14284 correctly.
14286 Some shells also have problems with backslash escaping in case you do not want
14287 to match the backslash: both a backslash and the escaped character match this
14288 pattern.  To work around this, specify the character class in a variable, so
14289 that quote removal does not apply afterwards, and the special characters don't
14290 have to be backslash-escaped:
14292 @example
14293 $ @kbd{case '\' in [\<]) echo OK;; esac}
14295 $ @kbd{scanset='[<]'; case '\' in $scanset) echo OK;; esac}
14297 @end example
14299 Even with this, Solaris @command{ksh} matches a backslash if the set
14300 contains any
14301 of the characters @samp{|}, @samp{&}, @samp{(}, or @samp{)}.
14303 Conversely, Tru64 @command{ksh} (circa 2003) erroneously always matches
14304 a closing parenthesis if not specified in a character class:
14306 @example
14307 $ @kbd{case foo in *\)*) echo fail ;; esac}
14308 fail
14309 $ @kbd{case foo in *')'*) echo fail ;; esac}
14310 fail
14311 @end example
14313 Some shells, such as Ash 0.3.8, are confused by an empty
14314 @code{case}/@code{esac}:
14316 @example
14317 ash-0.3.8 $ @kbd{case foo in esac;}
14318 @error{}Syntax error: ";" unexpected (expecting ")")
14319 @end example
14322 @item @command{cd}
14323 @c ---------------
14324 @prindex @command{cd}
14325 Posix 1003.1-2001 requires that @command{cd} must support
14326 the @option{-L} (``logical'') and @option{-P} (``physical'') options,
14327 with @option{-L} being the default.  However, traditional shells do
14328 not support these options, and their @command{cd} command has the
14329 @option{-P} behavior.
14331 Portable scripts should assume neither option is supported, and should
14332 assume neither behavior is the default.  This can be a bit tricky,
14333 since the Posix default behavior means that, for example,
14334 @samp{ls ..} and @samp{cd ..} may refer to different directories if
14335 the current logical directory is a symbolic link.  It is safe to use
14336 @code{cd @var{dir}} if @var{dir} contains no @file{..} components.
14337 Also, Autoconf-generated scripts check for this problem when computing
14338 variables like @code{ac_top_srcdir} (@pxref{Configuration Actions}),
14339 so it is safe to @command{cd} to these variables.
14341 See @xref{Special Shell Variables}, for portability problems involving
14342 @command{cd} and the @env{CDPATH} environment variable.
14343 Also please see the discussion of the @command{pwd} command.
14346 @item @command{echo}
14347 @c -----------------
14348 @prindex @command{echo}
14349 The simple @command{echo} is probably the most surprising source of
14350 portability troubles.  It is not possible to use @samp{echo} portably
14351 unless both options and escape sequences are omitted.  New applications
14352 which are not aiming at portability should use @samp{printf} instead of
14353 @samp{echo}.
14355 Don't expect any option.  @xref{Preset Output Variables}, @code{ECHO_N}
14356 etc.@: for a means to simulate @option{-n}.
14358 Do not use backslashes in the arguments, as there is no consensus on
14359 their handling.  For @samp{echo '\n' | wc -l}, the @command{sh} of
14360 Solaris outputs 2, but Bash and Zsh (in @command{sh} emulation mode) output 1.
14361 The problem is truly @command{echo}: all the shells
14362 understand @samp{'\n'} as the string composed of a backslash and an
14363 @samp{n}.
14365 Because of these problems, do not pass a string containing arbitrary
14366 characters to @command{echo}.  For example, @samp{echo "$foo"} is safe
14367 if you know that @var{foo}'s value cannot contain backslashes and cannot
14368 start with @samp{-}, but otherwise you should use a here-document like
14369 this:
14371 @example
14372 cat <<EOF
14373 $foo
14375 @end example
14378 @item @command{eval}
14379 @c -----------------
14380 @prindex @command{eval}
14381 The @command{eval} command is useful in limited circumstances, e.g.,
14382 using commands like @samp{eval table_$key=\$value} and @samp{eval
14383 value=table_$key} to simulate a hash table when the key is known to be
14384 alphanumeric.  However, @command{eval} is tricky to use on arbitrary
14385 arguments, even when it is implemented correctly.
14387 It is obviously unwise to use @samp{eval $cmd} if the string value of
14388 @samp{cmd} was derived from an untrustworthy source.  But even if the
14389 string value is valid, @samp{eval $cmd} might not work as intended,
14390 since it causes field splitting and file name expansion to occur twice,
14391 once for the @command{eval} and once for the command itself.  It is
14392 therefore safer to use @samp{eval "$cmd"}.  For example, if @var{cmd}
14393 has the value @samp{cat test?.c}, @samp{eval $cmd} might expand to the
14394 equivalent of @samp{cat test;.c} if there happens to be a file named
14395 @file{test;.c} in the current directory; and this in turn
14396 mistakenly attempts to invoke @command{cat} on the file @file{test} and
14397 then execute the command @command{.c}.  To avoid this problem, use
14398 @samp{eval "$cmd"} rather than @samp{eval $cmd}.
14400 However, suppose that you want to output the text of the evaluated
14401 command just before executing it.  Assuming the previous example,
14402 @samp{echo "Executing: $cmd"} outputs @samp{Executing: cat test?.c}, but
14403 this output doesn't show the user that @samp{test;.c} is the actual name
14404 of the copied file.  Conversely, @samp{eval "echo Executing: $cmd"}
14405 works on this example, but it fails with @samp{cmd='cat foo >bar'},
14406 since it mistakenly replaces the contents of @file{bar} by the
14407 string @samp{cat foo}.  No simple, general, and portable solution to
14408 this problem is known.
14410 You should also be wary of common bugs in @command{eval} implementations.
14411 In some shell implementations (e.g., older @command{ash}, Open@acronym{BSD} 3.8
14412 @command{sh}, @command{pdksh} v5.2.14 99/07/13.2, and @command{zsh}
14413 4.2.5), the arguments of @samp{eval} are evaluated in a context where
14414 @samp{$?} is 0, so they exhibit behavior like this:
14416 @example
14417 $ @kbd{false; eval 'echo $?'}
14419 @end example
14421 The correct behavior here is to output a nonzero value,
14422 but portable scripts should not rely on this.
14424 You should not rely on @code{LINENO} within @command{eval}.
14425 @xref{Special Shell Variables}.
14427 @item @command{exec}
14428 @c -----------------
14429 @prindex @command{exec}
14430 Posix describes several categories of shell built-ins.  Special
14431 built-ins (such as @command{exit}) must impact the environment of the
14432 current shell, and need not be available through @command{exec}.  All
14433 other built-ins are regular, and must not propagate variable assignments
14434 to the environment of the current shell.  However, the group of regular
14435 built-ins is further distinguished by commands that do not require a
14436 @env{PATH} search (such as @command{cd}), in contrast to built-ins that
14437 are offered as a more efficient version of something that must still be
14438 found in a @env{PATH} search (such as @command{echo}).  Posix is not
14439 clear on whether @command{exec} must work with the list of 17 utilities
14440 that are invoked without a @env{PATH} search, and many platforms lack an
14441 executable for some of those built-ins:
14443 @example
14444 $ @kbd{sh -c 'exec cd /tmp'}
14445 sh: line 0: exec: cd: not found
14446 @end example
14448 All other built-ins that provide utilities specified by Posix must have
14449 a counterpart executable that exists on @env{PATH}, although Posix
14450 allows @command{exec} to use the built-in instead of the executable.
14451 For example, contrast @command{bash} 3.2 and @command{pdksh} 5.2.14:
14453 @example
14454 $ @kbd{bash -c 'pwd --version' | head -n1}
14455 bash: line 0: pwd: --: invalid option
14456 pwd: usage: pwd [-LP]
14457 $ @kbd{bash -c 'exec pwd --version' | head -n1}
14458 pwd (GNU coreutils) 6.10
14459 $ @kbd{pdksh -c 'exec pwd --version' | head -n1}
14460 pdksh: pwd: --: unknown option
14461 @end example
14463 When it is desired to avoid a regular shell built-in, the workaround is
14464 to use some other forwarding command, such as @command{env} or
14465 @command{nice}, that will ensure a path search:
14467 @example
14468 $ @kbd{pdksh -c 'exec true --version' | head -n1}
14469 $ @kbd{pdksh -c 'nice true --version' | head -n1}
14470 true (GNU coreutils) 6.10
14471 $ @kbd{pdksh -c 'env true --version' | head -n1}
14472 true (GNU coreutils) 6.10
14473 @end example
14475 @item @command{exit}
14476 @c -----------------
14477 @prindex @command{exit}
14478 The default value of @command{exit} is supposed to be @code{$?};
14479 unfortunately, some shells, such as the @acronym{DJGPP} port of Bash 2.04, just
14480 perform @samp{exit 0}.
14482 @example
14483 bash-2.04$ @kbd{foo=`exit 1` || echo fail}
14484 fail
14485 bash-2.04$ @kbd{foo=`(exit 1)` || echo fail}
14486 fail
14487 bash-2.04$ @kbd{foo=`(exit 1); exit` || echo fail}
14488 bash-2.04$
14489 @end example
14491 Using @samp{exit $?} restores the expected behavior.
14493 Some shell scripts, such as those generated by @command{autoconf}, use a
14494 trap to clean up before exiting.  If the last shell command exited with
14495 nonzero status, the trap also exits with nonzero status so that the
14496 invoker can tell that an error occurred.
14498 Unfortunately, in some shells, such as Solaris @command{/bin/sh}, an exit
14499 trap ignores the @code{exit} command's argument.  In these shells, a trap
14500 cannot determine whether it was invoked by plain @code{exit} or by
14501 @code{exit 1}.  Instead of calling @code{exit} directly, use the
14502 @code{AC_MSG_ERROR} macro that has a workaround for this problem.
14505 @item @command{export}
14506 @c -------------------
14507 @prindex @command{export}
14508 The builtin @command{export} dubs a shell variable @dfn{environment
14509 variable}.  Each update of exported variables corresponds to an update
14510 of the environment variables.  Conversely, each environment variable
14511 received by the shell when it is launched should be imported as a shell
14512 variable marked as exported.
14514 Alas, many shells, such as Solaris @command{/bin/sh},
14515 @sc{irix} 6.3, @sc{irix} 5.2,
14516 @acronym{AIX} 4.1.5, and Digital Unix 4.0, forget to
14517 @command{export} the environment variables they receive.  As a result,
14518 two variables coexist: the environment variable and the shell
14519 variable.  The following code demonstrates this failure:
14521 @example
14522 #!/bin/sh
14523 echo $FOO
14524 FOO=bar
14525 echo $FOO
14526 exec /bin/sh $0
14527 @end example
14529 @noindent
14530 when run with @samp{FOO=foo} in the environment, these shells print
14531 alternately @samp{foo} and @samp{bar}, although they should print only
14532 @samp{foo} and then a sequence of @samp{bar}s.
14534 Therefore you should @command{export} again each environment variable
14535 that you update; the export can occur before or after the assignment.
14537 Posix is not clear on whether the @command{export} of an undefined
14538 variable causes the variable to be defined with the value of an empty
14539 string, or merely marks any future definition of a variable by that name
14540 for export.  Various shells behave differently in this regard:
14542 @example
14543 $ @kbd{sh -c 'export foo; env | grep foo'}
14544 $ @kbd{ash -c 'export foo; env | grep foo'}
14545 foo=
14546 @end example
14548 @item @command{false}
14549 @c ------------------
14550 @prindex @command{false}
14551 Don't expect @command{false} to exit with status 1: in native
14552 Solaris @file{/bin/false} exits with status 255.
14555 @item @command{for}
14556 @c ----------------
14557 @prindex @command{for}
14558 To loop over positional arguments, use:
14560 @example
14561 for arg
14563   echo "$arg"
14564 done
14565 @end example
14567 @noindent
14568 You may @emph{not} leave the @code{do} on the same line as @code{for},
14569 since some shells improperly grok:
14571 @example
14572 for arg; do
14573   echo "$arg"
14574 done
14575 @end example
14577 If you want to explicitly refer to the positional arguments, given the
14578 @samp{$@@} bug (@pxref{Shell Substitutions}), use:
14580 @example
14581 for arg in $@{1+"$@@"@}; do
14582   echo "$arg"
14583 done
14584 @end example
14586 @noindent
14587 But keep in mind that Zsh, even in Bourne shell emulation mode, performs
14588 word splitting on @samp{$@{1+"$@@"@}}; see @ref{Shell Substitutions},
14589 item @samp{$@@}, for more.
14592 @item @command{if}
14593 @c ---------------
14594 @prindex @command{if}
14595 Using @samp{!} is not portable.  Instead of:
14597 @example
14598 if ! cmp -s file file.new; then
14599   mv file.new file
14601 @end example
14603 @noindent
14604 use:
14606 @example
14607 if cmp -s file file.new; then :; else
14608   mv file.new file
14610 @end example
14612 There are shells that do not reset the exit status from an @command{if}:
14614 @example
14615 $ @kbd{if (exit 42); then true; fi; echo $?}
14617 @end example
14619 @noindent
14620 whereas a proper shell should have printed @samp{0}.  This is especially
14621 bad in makefiles since it produces false failures.  This is why properly
14622 written makefiles, such as Automake's, have such hairy constructs:
14624 @example
14625 if test -f "$file"; then
14626   install "$file" "$dest"
14627 else
14628   :
14630 @end example
14633 @item @command{printf}
14634 @c ------------------
14635 @prindex @command{printf}
14636 A format string starting with a @samp{-} can cause problems.
14637 Bash interprets it as an option and
14638 gives an error.  And @samp{--} to mark the end of options is not good
14639 in the Net@acronym{BSD} Almquist shell (e.g., 0.4.6) which takes that
14640 literally as the format string.  Putting the @samp{-} in a @samp{%c}
14641 or @samp{%s} is probably easiest:
14643 @example
14644 printf %s -foo
14645 @end example
14647 Bash 2.03 mishandles an escape sequence that happens to evaluate to @samp{%}:
14649 @example
14650 $ @kbd{printf '\045'}
14651 bash: printf: `%': missing format character
14652 @end example
14654 Large outputs may cause trouble.  On Solaris 2.5.1 through 10, for
14655 example, @file{/usr/bin/printf} is buggy, so when using
14656 @command{/bin/sh} the command @samp{printf %010000x 123} normally dumps
14657 core.
14660 @item @command{read}
14661 @c ------------------
14662 @prindex @command{read}
14663 Not all shells support @option{-r} (Solaris @command{/bin/sh} for example).
14666 @item @command{pwd}
14667 @c ----------------
14668 @prindex @command{pwd}
14669 With modern shells, plain @command{pwd} outputs a ``logical''
14670 directory name, some of whose components may be symbolic links.  These
14671 directory names are in contrast to ``physical'' directory names, whose
14672 components are all directories.
14674 Posix 1003.1-2001 requires that @command{pwd} must support
14675 the @option{-L} (``logical'') and @option{-P} (``physical'') options,
14676 with @option{-L} being the default.  However, traditional shells do
14677 not support these options, and their @command{pwd} command has the
14678 @option{-P} behavior.
14680 Portable scripts should assume neither option is supported, and should
14681 assume neither behavior is the default.  Also, on many hosts
14682 @samp{/bin/pwd} is equivalent to @samp{pwd -P}, but Posix
14683 does not require this behavior and portable scripts should not rely on
14686 Typically it's best to use plain @command{pwd}.  On modern hosts this
14687 outputs logical directory names, which have the following advantages:
14689 @itemize @bullet
14690 @item
14691 Logical names are what the user specified.
14692 @item
14693 Physical names may not be portable from one installation
14694 host to another due to network file system gymnastics.
14695 @item
14696 On modern hosts @samp{pwd -P} may fail due to lack of permissions to
14697 some parent directory, but plain @command{pwd} cannot fail for this
14698 reason.
14699 @end itemize
14701 Also please see the discussion of the @command{cd} command.
14704 @item @command{set}
14705 @c ----------------
14706 @prindex @command{set}
14707 With the Free@acronym{BSD} 6.0 shell, the @command{set} command (without
14708 any options) does not sort its output.
14710 The @command{set} builtin faces the usual problem with arguments
14711 starting with a
14712 dash.  Modern shells such as Bash or Zsh understand @option{--} to specify
14713 the end of the options (any argument after @option{--} is a parameter,
14714 even @samp{-x} for instance), but many traditional shells (e.g., Solaris
14715 10 @command{/bin/sh}) simply stop option
14716 processing as soon as a non-option argument is found.  Therefore, use
14717 @samp{dummy} or simply @samp{x} to end the option processing, and use
14718 @command{shift} to pop it out:
14720 @example
14721 set x $my_list; shift
14722 @end example
14724 Avoid @samp{set -}, e.g., @samp{set - $my_list}.  Posix no
14725 longer requires support for this command, and in traditional shells
14726 @samp{set - $my_list} resets the @option{-v} and @option{-x} options, which
14727 makes scripts harder to debug.
14729 Some nonstandard shells do not recognize more than one option
14730 (e.g., @samp{set -e -x} assigns @samp{-x} to the command line).  It is
14731 better to combine them:
14733 @example
14734 set -ex
14735 @end example
14737 The @acronym{BSD} shell has had several problems with the @option{-e}
14738 option, partly because @acronym{BSD} @command{make} traditionally used
14739 @option{-e} even though this was incompatible with Posix
14740 (@pxref{Failure in Make Rules}).  Older versions of the @acronym{BSD}
14741 shell (circa 1990) mishandled @samp{&&}, @samp{||}, @samp{if}, and
14742 @samp{case} when @option{-e} was in effect, causing the shell to exit
14743 unexpectedly in some cases.  This was particularly a problem with
14744 makefiles, and led to circumlocutions like @samp{sh -c 'test -f file ||
14745 touch file'}, where the seemingly-unnecessary @samp{sh -c '@dots{}'}
14746 wrapper works around the bug.
14748 Even relatively-recent versions of the @acronym{BSD} shell (e.g.,
14749 Open@acronym{BSD} 3.4) wrongly exit with @option{-e} if a command within
14750 @samp{&&} fails inside a compound statement.  For example:
14752 @example
14753 #! /bin/sh
14754 set -e
14755 foo=''
14756 test -n "$foo" && exit 1
14757 echo one
14758 if :; then
14759   test -n "$foo" && exit 1
14761 echo two
14762 @end example
14764 @noindent
14765 does not print @samp{two}.  One workaround is to use @samp{if test -n
14766 "$foo"; then exit 1; fi} rather than @samp{test -n "$foo" && exit 1}.
14767 Another possibility is to warn @acronym{BSD} users not to use @samp{sh -e}.
14770 @item @command{shift}
14771 @c ------------------
14772 @prindex @command{shift}
14773 Not only is @command{shift}ing a bad idea when there is nothing left to
14774 shift, but in addition it is not portable: the shell of @acronym{MIPS
14775 RISC/OS} 4.52 refuses to do it.
14777 Don't use @samp{shift 2} etc.; it was not in the 7th Edition Bourne shell,
14778 and it is also absent in many pre-Posix shells.
14781 @item @command{source}
14782 @c -------------------
14783 @prindex @command{source}
14784 This command is not portable, as Posix does not require it; use
14785 @command{.} instead.
14788 @item @command{test}
14789 @c -----------------
14790 @prindex @command{test}
14791 The @code{test} program is the way to perform many file and string
14792 tests.  It is often invoked by the alternate name @samp{[}, but using
14793 that name in Autoconf code is asking for trouble since it is an M4 quote
14794 character.
14796 The @option{-a}, @option{-o}, @samp{(}, and @samp{)} operands are not
14797 portable and should be avoided.  Thus, portable uses of @command{test}
14798 should never have more than four arguments, and scripts should use shell
14799 constructs like @samp{&&} and @samp{||} instead.  If you combine
14800 @samp{&&} and @samp{||} in the same statement, keep in mind that they
14801 have equal precedence, so it is often better to parenthesize even when
14802 this is redundant.  For example:
14804 @smallexample
14805 # Not portable:
14806 test "X$a" = "X$b" -a \
14807   '(' "X$c" != "X$d" -o "X$e" = "X$f" ')'
14809 # Portable:
14810 test "X$a" = "X$b" &&
14811   @{ test "X$c" != "X$d" || test "X$e" = "X$f"; @}
14812 @end smallexample
14814 @command{test} does not process options like most other commands do; for
14815 example, it does not recognize the @option{--} argument as marking the
14816 end of options.
14818 It is safe to use @samp{!} as a @command{test} operator.  For example,
14819 @samp{if test ! -d foo; @dots{}} is portable even though @samp{if ! test
14820 -d foo; @dots{}} is not.
14823 @item @command{test} (files)
14824 @c -------------------------
14825 To enable @command{configure} scripts to support cross-compilation, they
14826 shouldn't do anything that tests features of the build system instead of
14827 the host system.  But occasionally you may find it necessary to check
14828 whether some arbitrary file exists.  To do so, use @samp{test -f} or
14829 @samp{test -r}.  Do not use @samp{test -x}, because 4.3@acronym{BSD} does not
14830 have it.  Do not use @samp{test -e} either, because Solaris @command{/bin/sh}
14831 lacks it.  To test for symbolic links on systems that have them, use
14832 @samp{test -h} rather than @samp{test -L}; either form conforms to
14833 Posix 1003.1-2001, but older shells like Solaris 8
14834 @code{/bin/sh} support only @option{-h}.
14836 @item @command{test} (strings)
14837 @c ---------------------------
14838 Posix says that @samp{test "@var{string}"} succeeds if @var{string} is
14839 not null, but this usage is not portable to traditional platforms like
14840 Solaris 10 @command{/bin/sh}, which mishandle strings like @samp{!} and
14841 @samp{-n}.
14843 Posix also says that @samp{test ! "@var{string}"},
14844 @samp{test -n "@var{string}"} and
14845 @samp{test -z "@var{string}"} work with any string, but many
14846 shells (such as Solaris, @acronym{AIX} 3.2, @sc{unicos} 10.0.0.6,
14847 Digital Unix 4, etc.)@: get confused if
14848 @var{string} looks like an operator:
14850 @example
14851 $ @kbd{test -n =}
14852 test: argument expected
14853 $ @kbd{test ! -n}
14854 test: argument expected
14855 @end example
14857 Similarly, Posix says that both @samp{test "@var{string1}" = "@var{string2"}}
14858 and @samp{test "@var{string1}" != "@var{string2"}} work for any pairs of
14859 strings, but in practice this is not true for troublesome strings that
14860 look like operators or parentheses, or that begin with @samp{-}.
14862 It is best to protect such strings with a leading @samp{X}, e.g.,
14863 @samp{test "X@var{string}" != X} rather than @samp{test -n
14864 "@var{string}"} or @samp{test ! "@var{string}"}.
14866 It is common to find variations of the following idiom:
14868 @example
14869 test -n "`echo $ac_feature | sed 's/[-a-zA-Z0-9_]//g'`" &&
14870   @var{action}
14871 @end example
14873 @noindent
14874 to take an action when a token matches a given pattern.  Such constructs
14875 should be avoided by using:
14877 @example
14878 case $ac_feature in
14879   *[!-a-zA-Z0-9_]*) @var{action};;
14880 esac
14881 @end example
14883 If the pattern is a complicated regular expression that cannot be
14884 expressed as a shell pattern, use something like this instead:
14886 @example
14887 expr "X$ac_feature" : 'X.*[^-a-zA-Z0-9_]' >/dev/null &&
14888   @var{action}
14889 @end example
14891 @samp{expr "X@var{foo}" : "X@var{bar}"} is more robust than @samp{echo
14892 "X@var{foo}" | grep "^X@var{bar}"}, because it avoids problems when
14893 @samp{@var{foo}} contains backslashes.
14896 @item @command{trap}
14897 @c -----------------
14898 @prindex @command{trap}
14899 It is safe to trap at least the signals 1, 2, 13, and 15.  You can also
14900 trap 0, i.e., have the @command{trap} run when the script ends (either via an
14901 explicit @command{exit}, or the end of the script).  The trap for 0 should be
14902 installed outside of a shell function, or @acronym{AIX} 5.3 @command{/bin/sh}
14903 will invoke the trap at the end of this function.
14905 Posix says that @samp{trap - 1 2 13 15} resets the traps for the
14906 specified signals to their default values, but many common shells (e.g.,
14907 Solaris @command{/bin/sh}) misinterpret this and attempt to execute a
14908 ``command'' named @command{-} when the specified conditions arise.
14909 There is no portable workaround, except for @samp{trap - 0}, for which
14910 @samp{trap '' 0} is a portable substitute.
14912 Although Posix is not absolutely clear on this point, it is widely
14913 admitted that when entering the trap @samp{$?} should be set to the exit
14914 status of the last command run before the trap.  The ambiguity can be
14915 summarized as: ``when the trap is launched by an @command{exit}, what is
14916 the @emph{last} command run: that before @command{exit}, or
14917 @command{exit} itself?''
14919 Bash considers @command{exit} to be the last command, while Zsh and
14920 Solaris @command{/bin/sh} consider that when the trap is run it is
14921 @emph{still} in the @command{exit}, hence it is the previous exit status
14922 that the trap receives:
14924 @example
14925 $ @kbd{cat trap.sh}
14926 trap 'echo $?' 0
14927 (exit 42); exit 0
14928 $ @kbd{zsh trap.sh}
14930 $ @kbd{bash trap.sh}
14932 @end example
14934 The portable solution is then simple: when you want to @samp{exit 42},
14935 run @samp{(exit 42); exit 42}, the first @command{exit} being used to
14936 set the exit status to 42 for Zsh, and the second to trigger the trap
14937 and pass 42 as exit status for Bash.
14939 The shell in Free@acronym{BSD} 4.0 has the following bug: @samp{$?} is
14940 reset to 0 by empty lines if the code is inside @command{trap}.
14942 @example
14943 $ @kbd{trap 'false}
14945 echo $?' 0
14946 $ @kbd{exit}
14948 @end example
14950 @noindent
14951 Fortunately, this bug only affects @command{trap}.
14953 @item @command{true}
14954 @c -----------------
14955 @prindex @command{true}
14956 @c Info cannot handle `:' in index entries.
14957 @c @prindex @command{:}
14958 Don't worry: as far as we know @command{true} is portable.
14959 Nevertheless, it's not always a builtin (e.g., Bash 1.x), and the
14960 portable shell community tends to prefer using @command{:}.  This has a
14961 funny side effect: when asked whether @command{false} is more portable
14962 than @command{true} Alexandre Oliva answered:
14964 @quotation
14965 In a sense, yes, because if it doesn't exist, the shell will produce an
14966 exit status of failure, which is correct for @command{false}, but not
14967 for @command{true}.
14968 @end quotation
14971 @item @command{unset}
14972 @c ------------------
14973 @prindex @command{unset}
14974 In some nonconforming shells (e.g., Bash 2.05a), @code{unset FOO} fails
14975 when @code{FOO} is not set.  Also, Bash 2.01 mishandles @code{unset
14976 MAIL} in some cases and dumps core.
14978 A few ancient shells lack @command{unset} entirely.  Nevertheless, because
14979 it is extremely useful to disable embarrassing variables such as
14980 @code{PS1}, you can test for its existence and use
14981 it @emph{provided} you give a neutralizing value when @command{unset} is
14982 not supported:
14984 @smallexample
14985 # "|| exit" suppresses any "Segmentation fault" message.
14986 if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; then
14987   unset=unset
14988 else
14989   unset=false
14991 $unset PS1 || PS1='$ '
14992 @end smallexample
14994 @noindent
14995 @xref{Special Shell Variables}, for some neutralizing values.  Also, see
14996 @ref{Limitations of Builtins}, documentation of @command{export}, for
14997 the case of environment variables.
14998 @end table
15000 @node Limitations of Usual Tools
15001 @section Limitations of Usual Tools
15002 @cindex Limitations of usual tools
15004 The small set of tools you can expect to find on any machine can still
15005 include some limitations you should be aware of.
15007 @table @asis
15008 @item Awk
15009 @c ------
15010 @prindex Awk
15011 Don't leave white space before the opening parenthesis in a user function call.
15012 Posix does not allow this and @acronym{GNU} Awk rejects it:
15014 @example
15015 $ @kbd{gawk 'function die () @{ print "Aaaaarg!"  @}
15016         BEGIN @{ die () @}'}
15017 gawk: cmd. line:2:         BEGIN @{ die () @}
15018 gawk: cmd. line:2:                      ^ parse error
15019 $ @kbd{gawk 'function die () @{ print "Aaaaarg!"  @}
15020         BEGIN @{ die() @}'}
15021 Aaaaarg!
15022 @end example
15024 Posix says that if a program contains only @samp{BEGIN} actions, and
15025 contains no instances of @code{getline}, then the program merely
15026 executes the actions without reading input.  However, traditional Awk
15027 implementations (such as Solaris 10 @command{awk}) read and discard
15028 input in this case.  Portable scripts can redirect input from
15029 @file{/dev/null} to work around the problem.  For example:
15031 @example
15032 awk 'BEGIN @{print "hello world"@}' </dev/null
15033 @end example
15035 Posix says that in an @samp{END} action, @samp{$NF} (and presumably,
15036 @samp{$1}) retain their value from the last record read, if no
15037 intervening @samp{getline} occurred.  However, some implementations
15038 (such as Solaris 10 @samp{/usr/bin/awk}, @samp{nawk}, or Darwin
15039 @samp{awk}) reset these variables.  A workaround is to use an
15040 intermediate variable prior to the @samp{END} block.  For example:
15042 @example
15043 $ @kbd{cat end.awk}
15044 @{ tmp = $1 @}
15045 END @{ print "a", $1, $NF, "b", tmp @}
15046 $ @kbd{echo 1 | awk -f end.awk}
15047 a   b 1
15048 $ @kbd{echo 1 | gawk -f end.awk}
15049 a 1 1 b 1
15050 @end example
15052 If you want your program to be deterministic, don't depend on @code{for}
15053 on arrays:
15055 @example
15056 $ @kbd{cat for.awk}
15057 END @{
15058   arr["foo"] = 1
15059   arr["bar"] = 1
15060   for (i in arr)
15061     print i
15063 $ @kbd{gawk -f for.awk </dev/null}
15066 $ @kbd{nawk -f for.awk </dev/null}
15069 @end example
15071 Some Awk implementations, such as @acronym{HP-UX} 11.0's native one,
15072 mishandle anchors:
15074 @example
15075 $ @kbd{echo xfoo | $AWK '/foo|^bar/ @{ print @}'}
15076 $ @kbd{echo bar | $AWK '/foo|^bar/ @{ print @}'}
15078 $ @kbd{echo xfoo | $AWK '/^bar|foo/ @{ print @}'}
15079 xfoo
15080 $ @kbd{echo bar | $AWK '/^bar|foo/ @{ print @}'}
15082 @end example
15084 @noindent
15085 Either do not depend on such patterns (i.e., use @samp{/^(.*foo|bar)/},
15086 or use a simple test to reject such implementations.
15088 On @samp{ia64-hp-hpux11.23}, Awk mishandles @code{printf} conversions
15089 after @code{%u}:
15091 @example
15092 $ @kbd{awk 'BEGIN @{ printf "%u %d\n", 0, -1 @}'}
15093 0 0
15094 @end example
15096 @acronym{AIX} version 5.2 has an arbitrary limit of 399 on the
15097 length of regular expressions and literal strings in an Awk program.
15099 Traditional Awk implementations derived from Unix version 7, such as
15100 Solaris @command{/bin/awk}, have many limitations and do not
15101 conform to Posix.  Nowadays @code{AC_PROG_AWK} (@pxref{Particular
15102 Programs}) finds you an Awk that doesn't have these problems, but if
15103 for some reason you prefer not to use @code{AC_PROG_AWK} you may need to
15104 address them.
15106 Traditional Awk does not support multidimensional arrays or user-defined
15107 functions.
15109 Traditional Awk does not support the @option{-v} option.  You can use
15110 assignments after the program instead, e.g., @code{$AWK '@{print v
15111 $1@}' v=x}; however, don't forget that such assignments are not
15112 evaluated until they are encountered (e.g., after any @code{BEGIN}
15113 action).
15115 Traditional Awk does not support the keywords @code{delete} or @code{do}.
15117 Traditional Awk does not support the expressions
15118 @code{@var{a}?@var{b}:@var{c}}, @code{!@var{a}}, @code{@var{a}^@var{b}},
15119 or @code{@var{a}^=@var{b}}.
15121 Traditional Awk does not support the predefined @code{CONVFMT} variable.
15123 Traditional Awk supports only the predefined functions @code{exp}, @code{index},
15124 @code{int}, @code{length}, @code{log}, @code{split}, @code{sprintf},
15125 @code{sqrt}, and @code{substr}.
15127 Traditional Awk @code{getline} is not at all compatible with Posix;
15128 avoid it.
15130 Traditional Awk has @code{for (i in a) @dots{}} but no other uses of the
15131 @code{in} keyword.  For example, it lacks @code{if (i in a) @dots{}}.
15133 In code portable to both traditional and modern Awk, @code{FS} must be a
15134 string containing just one ordinary character, and similarly for the
15135 field-separator argument to @code{split}.
15137 Traditional Awk has a limit of 99 fields in a record.  Since some Awk
15138 implementations, like Tru64's, split the input even if you don't refer
15139 to any field in the script, to circumvent this problem, set @samp{FS}
15140 to an unusual character and use @code{split}.
15142 Traditional Awk has a limit of at most 99 bytes in a number formatted by
15143 @code{OFMT}; for example, @code{OFMT="%.300e"; print 0.1;} typically
15144 dumps core.
15146 The original version of Awk had a limit of at most 99 bytes per
15147 @code{split} field, 99 bytes per @code{substr} substring, and 99 bytes
15148 per run of non-special characters in a @code{printf} format, but these
15149 bugs have been fixed on all practical hosts that we know of.
15151 @item @command{basename}
15152 @c ---------------------
15153 @prindex @command{basename}
15154 Not all hosts have a working @command{basename}.
15155 You can use @command{expr} instead.
15157 @c AS_BASENAME is to be replaced by a better API.
15158 @ignore
15159 Not all hosts have a working @command{basename}, and you should instead
15160 use @code{AS_BASENAME} (@pxref{Programming in M4sh}), followed by
15161 @command{expr} if you need to strip a suffix.  For example:
15163 @example
15164 a=`basename "$aname"`       # This is not portable.
15165 a=`AS_BASENAME(["$aname"])` # This is more portable.
15167 # This is not portable.
15168 c=`basename "$cname" .c`
15170 # This is more portable.
15171 c=`AS_BASENAME(["$cname"])`
15172 case $c in
15173 ?*.c) c=`expr "X$c" : 'X\(.*\)\.c'`;;
15174 esac
15175 @end example
15176 @end ignore
15179 @item @command{cat}
15180 @c ----------------
15181 @prindex @command{cat}
15182 Don't rely on any option.
15185 @item @command{cc}
15186 @c ---------------
15187 @prindex @command{cc}
15188 The command @samp{cc -c foo.c} traditionally produces an object file
15189 named @file{foo.o}.  Most compilers allow @option{-c} to be combined
15190 with @option{-o} to specify a different object file name, but
15191 Posix does not require this combination and a few compilers
15192 lack support for it.  @xref{C Compiler}, for how @acronym{GNU} Make
15193 tests for this feature with @code{AC_PROG_CC_C_O}.
15195 When a compilation such as @samp{cc -o foo foo.c} fails, some compilers
15196 (such as @sc{cds} on Reliant Unix) leave a @file{foo.o}.
15198 @acronym{HP-UX} @command{cc} doesn't accept @file{.S} files to preprocess and
15199 assemble.  @samp{cc -c foo.S} appears to succeed, but in fact does
15200 nothing.
15202 The default executable, produced by @samp{cc foo.c}, can be
15204 @itemize
15205 @item @file{a.out} --- usual Posix convention.
15206 @item @file{b.out} --- i960 compilers (including @command{gcc}).
15207 @item @file{a.exe} --- @acronym{DJGPP} port of @command{gcc}.
15208 @item @file{a_out.exe} --- GNV @command{cc} wrapper for DEC C on OpenVMS.
15209 @item @file{foo.exe} --- various MS-DOS compilers.
15210 @end itemize
15212 The C compiler's traditional name is @command{cc}, but other names like
15213 @command{gcc} are common.  Posix 1003.1-2001 specifies the
15214 name @command{c99}, but older Posix editions specified
15215 @command{c89} and anyway these standard names are rarely used in
15216 practice.  Typically the C compiler is invoked from makefiles that use
15217 @samp{$(CC)}, so the value of the @samp{CC} make variable selects the
15218 compiler name.
15221 @item @command{chmod}
15222 @c ------------------
15223 @prindex @command{chmod}
15224 Avoid usages like @samp{chmod -w file}; use @samp{chmod a-w file}
15225 instead, for two reasons.  First, plain @option{-w} does not necessarily
15226 make the file unwritable, since it does not affect mode bits that
15227 correspond to bits in the file mode creation mask.  Second,
15228 Posix says that the @option{-w} might be interpreted as an
15229 implementation-specific option, not as a mode; Posix suggests
15230 using @samp{chmod -- -w file} to avoid this confusion, but unfortunately
15231 @samp{--} does not work on some older hosts.
15234 @item @command{cmp}
15235 @c ----------------
15236 @prindex @command{cmp}
15237 @command{cmp} performs a raw data comparison of two files, while
15238 @command{diff} compares two text files.  Therefore, if you might compare
15239 DOS files, even if only checking whether two files are different, use
15240 @command{diff} to avoid spurious differences due to differences of
15241 newline encoding.
15244 @item @command{cp}
15245 @c ---------------
15246 @prindex @command{cp}
15247 Avoid the @option{-r} option, since Posix 1003.1-2004 marks it as
15248 obsolescent and its behavior on special files is implementation-defined.
15249 Use @option{-R} instead.  On @acronym{GNU} hosts the two options
15250 are equivalent, but on Solaris hosts (for example) @code{cp -r}
15251 reads from pipes instead of replicating them.
15253 Some @command{cp} implementations (e.g., @acronym{BSD/OS} 4.2) do not allow
15254 trailing slashes at the end of nonexistent destination directories.  To
15255 avoid this problem, omit the trailing slashes.  For example, use
15256 @samp{cp -R source /tmp/newdir} rather than @samp{cp -R source
15257 /tmp/newdir/} if @file{/tmp/newdir} does not exist.
15259 @c This is thanks to Ian.
15260 The ancient SunOS 4 @command{cp} does not support @option{-f}, although
15261 its @command{mv} does.
15263 @cindex timestamp resolution
15264 Traditionally, file timestamps had 1-second resolution, and @samp{cp
15265 -p} copied the timestamps exactly.  However, many modern file systems
15266 have timestamps with 1-nanosecond resolution.  Unfortunately, @samp{cp
15267 -p} implementations truncate timestamps when copying files, so this
15268 can result in the destination file appearing to be older than the
15269 source.  The exact amount of truncation depends on the resolution of
15270 the system calls that @command{cp} uses; traditionally this was
15271 @code{utime}, which has 1-second resolution, but some newer
15272 @command{cp} implementations use @code{utimes}, which has
15273 1-microsecond resolution.  These newer implementations include @acronym{GNU}
15274 Core Utilities 5.0.91 or later, and Solaris 8 (sparc) patch 109933-02 or
15275 later.  Unfortunately as of January 2006 there is still no system
15276 call to set timestamps to the full nanosecond resolution.
15278 Bob Proulx notes that @samp{cp -p} always @emph{tries} to copy
15279 ownerships.  But whether it actually does copy ownerships or not is a
15280 system dependent policy decision implemented by the kernel.  If the
15281 kernel allows it then it happens.  If the kernel does not allow it then
15282 it does not happen.  It is not something @command{cp} itself has control
15283 over.
15285 In Unix System V any user can chown files to any other user, and System
15286 V also has a non-sticky @file{/tmp}.  That probably derives from the
15287 heritage of System V in a business environment without hostile users.
15288 @acronym{BSD} changed this
15289 to be a more secure model where only root can @command{chown} files and
15290 a sticky @file{/tmp} is used.  That undoubtedly derives from the heritage
15291 of @acronym{BSD} in a campus environment.
15293 @acronym{GNU}/Linux and Solaris by default follow @acronym{BSD}, but
15294 can be configured to allow a System V style @command{chown}.  On the
15295 other hand, @acronym{HP-UX} follows System V, but can
15296 be configured to use the modern security model and disallow
15297 @command{chown}.  Since it is an administrator-configurable parameter
15298 you can't use the name of the kernel as an indicator of the behavior.
15302 @item @command{date}
15303 @c -----------------
15304 @prindex @command{date}
15305 Some versions of @command{date} do not recognize special @samp{%} directives,
15306 and unfortunately, instead of complaining, they just pass them through,
15307 and exit with success:
15309 @example
15310 $ @kbd{uname -a}
15311 OSF1 medusa.sis.pasteur.fr V5.1 732 alpha
15312 $ @kbd{date "+%s"}
15314 @end example
15317 @item @command{diff}
15318 @c -----------------
15319 @prindex @command{diff}
15320 Option @option{-u} is nonportable.
15322 Some implementations, such as Tru64's, fail when comparing to
15323 @file{/dev/null}.  Use an empty file instead.
15326 @item @command{dirname}
15327 @c --------------------
15328 @prindex @command{dirname}
15329 Not all hosts have a working @command{dirname}, and you should instead
15330 use @code{AS_DIRNAME} (@pxref{Programming in M4sh}).  For example:
15332 @example
15333 dir=`dirname "$file"`       # This is not portable.
15334 dir=`AS_DIRNAME(["$file"])` # This is more portable.
15335 @end example
15338 @item @command{egrep}
15339 @c ------------------
15340 @prindex @command{egrep}
15341 Posix 1003.1-2001 no longer requires @command{egrep},
15342 but many hosts do not yet support the Posix
15343 replacement @code{grep -E}.  Also, some traditional implementations do
15344 not work on long input lines.  To work around these problems, invoke
15345 @code{AC_PROG_EGREP} and then use @code{$EGREP}.
15347 Portable extended regular expressions should use @samp{\} only to escape
15348 characters in the string @samp{$()*+.?[\^@{|}.  For example, @samp{\@}}
15349 is not portable, even though it typically matches @samp{@}}.
15351 The empty alternative is not portable.  Use @samp{?} instead.  For
15352 instance with Digital Unix v5.0:
15354 @example
15355 > printf "foo\n|foo\n" | $EGREP '^(|foo|bar)$'
15356 |foo
15357 > printf "bar\nbar|\n" | $EGREP '^(foo|bar|)$'
15358 bar|
15359 > printf "foo\nfoo|\n|bar\nbar\n" | $EGREP '^(foo||bar)$'
15361 |bar
15362 @end example
15364 @command{$EGREP} also suffers the limitations of @command{grep}.
15366 @item @command{expr}
15367 @c -----------------
15368 @prindex @command{expr}
15369 No @command{expr} keyword starts with @samp{X}, so use @samp{expr
15370 X"@var{word}" : 'X@var{regex}'} to keep @command{expr} from
15371 misinterpreting @var{word}.
15373 Don't use @code{length}, @code{substr}, @code{match} and @code{index}.
15375 @item @command{expr} (@samp{|})
15376 @prindex @command{expr} (@samp{|})
15377 You can use @samp{|}.  Although Posix does require that @samp{expr
15378 ''} return the empty string, it does not specify the result when you
15379 @samp{|} together the empty string (or zero) with the empty string.  For
15380 example:
15382 @example
15383 expr '' \| ''
15384 @end example
15386 Posix 1003.2-1992 returns the empty string
15387 for this case, but traditional Unix returns @samp{0} (Solaris is
15388 one such example).  In Posix 1003.1-2001, the specification was
15389 changed to match traditional Unix's behavior (which is
15390 bizarre, but it's too late to fix this).  Please note that the same
15391 problem does arise when the empty string results from a computation,
15392 as in:
15394 @example
15395 expr bar : foo \| foo : bar
15396 @end example
15398 @noindent
15399 Avoid this portability problem by avoiding the empty string.
15402 @item @command{expr} (@samp{:})
15403 @c ----------------------------
15404 @prindex @command{expr}
15405 Portable @command{expr} regular expressions should use @samp{\} to
15406 escape only characters in the string @samp{$()*.0123456789[\^n@{@}}.
15407 For example, alternation, @samp{\|}, is common but Posix does not
15408 require its support, so it should be avoided in portable scripts.
15409 Similarly, @samp{\+} and @samp{\?} should be avoided.
15411 Portable @command{expr} regular expressions should not begin with
15412 @samp{^}.  Patterns are automatically anchored so leading @samp{^} is
15413 not needed anyway.
15415 The Posix standard is ambiguous as to whether
15416 @samp{expr 'a' : '\(b\)'} outputs @samp{0} or the empty string.
15417 In practice, it outputs the empty string on most platforms, but portable
15418 scripts should not assume this.  For instance, the @acronym{QNX} 4.25 native
15419 @command{expr} returns @samp{0}.
15421 One might think that a way to get a uniform behavior would be to use
15422 the empty string as a default value:
15424 @example
15425 expr a : '\(b\)' \| ''
15426 @end example
15428 @noindent
15429 Unfortunately this behaves exactly as the original expression; see the
15430 @command{expr} (@samp{|}) entry for more information.
15432 Some ancient @command{expr} implementations (e.g., SunOS 4 @command{expr} and
15433 Solaris 8 @command{/usr/ucb/expr}) have a silly length limit that causes
15434 @command{expr} to fail if the matched substring is longer than 120
15435 bytes.  In this case, you might want to fall back on @samp{echo|sed} if
15436 @command{expr} fails.  Nowadays this is of practical importance only for
15437 the rare installer who mistakenly puts @file{/usr/ucb} before
15438 @file{/usr/bin} in @env{PATH}.
15440 On Mac OS X 10.4, @command{expr} mishandles the pattern @samp{[^-]} in
15441 some cases.  For example, the command
15442 @example
15443 expr Xpowerpc-apple-darwin8.1.0 : 'X[^-]*-[^-]*-\(.*\)'
15444 @end example
15446 @noindent
15447 outputs @samp{apple-darwin8.1.0} rather than the correct @samp{darwin8.1.0}.
15448 This particular case can be worked around by substituting @samp{[^--]}
15449 for @samp{[^-]}.
15451 Don't leave, there is some more!
15453 The @acronym{QNX} 4.25 @command{expr}, in addition of preferring @samp{0} to
15454 the empty string, has a funny behavior in its exit status: it's always 1
15455 when parentheses are used!
15457 @example
15458 $ @kbd{val=`expr 'a' : 'a'`; echo "$?: $val"}
15459 0: 1
15460 $ @kbd{val=`expr 'a' : 'b'`; echo "$?: $val"}
15461 1: 0
15463 $ @kbd{val=`expr 'a' : '\(a\)'`; echo "?: $val"}
15464 1: a
15465 $ @kbd{val=`expr 'a' : '\(b\)'`; echo "?: $val"}
15466 1: 0
15467 @end example
15469 @noindent
15470 In practice this can be a big problem if you are ready to catch failures
15471 of @command{expr} programs with some other method (such as using
15472 @command{sed}), since you may get twice the result.  For instance
15474 @example
15475 $ @kbd{expr 'a' : '\(a\)' || echo 'a' | sed 's/^\(a\)$/\1/'}
15476 @end example
15478 @noindent
15479 outputs @samp{a} on most hosts, but @samp{aa} on @acronym{QNX} 4.25.  A
15480 simple workaround consists of testing @command{expr} and using a variable
15481 set to @command{expr} or to @command{false} according to the result.
15483 Tru64 @command{expr} incorrectly treats the result as a number, if it
15484 can be interpreted that way:
15486 @example
15487 $ @kbd{expr 00001 : '.*\(...\)'}
15489 @end example
15492 @item @command{fgrep}
15493 @c ------------------
15494 @prindex @command{fgrep}
15495 Posix 1003.1-2001 no longer requires @command{fgrep},
15496 but many hosts do not yet support the Posix
15497 replacement @code{grep -F}.  Also, some traditional implementations do
15498 not work on long input lines.  To work around these problems, invoke
15499 @code{AC_PROG_FGREP} and then use @code{$FGREP}.
15502 @item @command{find}
15503 @c -----------------
15504 @prindex @command{find}
15505 The option @option{-maxdepth} seems to be @acronym{GNU} specific.
15506 Tru64 v5.1, Net@acronym{BSD} 1.5 and Solaris @command{find}
15507 commands do not understand it.
15509 The replacement of @samp{@{@}} is guaranteed only if the argument is
15510 exactly @emph{@{@}}, not if it's only a part of an argument.  For
15511 instance on DU, and @acronym{HP-UX} 10.20 and @acronym{HP-UX} 11:
15513 @example
15514 $ @kbd{touch foo}
15515 $ @kbd{find . -name foo -exec echo "@{@}-@{@}" \;}
15516 @{@}-@{@}
15517 @end example
15519 @noindent
15520 while @acronym{GNU} @command{find} reports @samp{./foo-./foo}.
15523 @item @command{grep}
15524 @c -----------------
15525 @prindex @command{grep}
15526 Portable scripts can rely on the @command{grep} options @option{-c},
15527 @option{-l}, @option{-n}, and @option{-v}, but should avoid other
15528 options.  For example, don't use @option{-w}, as Posix does not require
15529 it and Irix 6.5.16m's @command{grep} does not support it.  Also,
15530 portable scripts should not combine @option{-c} with @option{-l},
15531 as Posix does not allow this.
15533 Some of the options required by Posix are not portable in practice.
15534 Don't use @samp{grep -q} to suppress output, because many @command{grep}
15535 implementations (e.g., Solaris) do not support @option{-q}.
15536 Don't use @samp{grep -s} to suppress output either, because Posix
15537 says @option{-s} does not suppress output, only some error messages;
15538 also, the @option{-s} option of traditional @command{grep} behaved
15539 like @option{-q} does in most modern implementations.  Instead,
15540 redirect the standard output and standard error (in case the file
15541 doesn't exist) of @code{grep} to @file{/dev/null}.  Check the exit
15542 status of @code{grep} to determine whether it found a match.
15544 Some traditional @command{grep} implementations do not work on long
15545 input lines.  On AIX the default @code{grep} silently truncates long
15546 lines on the input before matching.
15548 Also, many implementations do not support multiple regexps
15549 with @option{-e}: they either reject @option{-e} entirely (e.g., Solaris)
15550 or honor only the last pattern (e.g., @acronym{IRIX} 6.5 and NeXT).  To
15551 work around these problems, invoke @code{AC_PROG_GREP} and then use
15552 @code{$GREP}.
15554 Another possible workaround for the multiple @option{-e} problem is to
15555 separate the patterns by newlines, for example:
15557 @example
15558 grep 'foo
15559 bar' in.txt
15560 @end example
15562 @noindent
15563 except that this fails with traditional @command{grep}
15564 implementations and with Open@acronym{BSD} 3.8 @command{grep}.
15566 Traditional @command{grep} implementations (e.g., Solaris) do not
15567 support the @option{-E} or @option{-F} options.  To work around these
15568 problems, invoke @code{AC_PROG_EGREP} and then use @code{$EGREP}, and
15569 similarly for @code{AC_PROG_FGREP} and @code{$FGREP}.  Even if you are
15570 willing to require support for Posix @command{grep}, your script should
15571 not use both @option{-E} and @option{-F}, since Posix does not allow
15572 this combination.
15574 Portable @command{grep} regular expressions should use @samp{\} only to
15575 escape characters in the string @samp{$()*.0123456789[\^@{@}}.  For example,
15576 alternation, @samp{\|}, is common but Posix does not require its
15577 support in basic regular expressions, so it should be avoided in
15578 portable scripts.  Solaris and HP-UX @command{grep} do not support it.
15579 Similarly, the following escape sequences should also be avoided:
15580 @samp{\<}, @samp{\>}, @samp{\+}, @samp{\?}, @samp{\`}, @samp{\'},
15581 @samp{\B}, @samp{\b}, @samp{\S}, @samp{\s}, @samp{\W}, and @samp{\w}.
15583 Posix does not specify the behavior of @command{grep} on binary files.
15584 An example where this matters is using @acronym{BSD} @command{grep} to
15585 search text that includes embedded @acronym{ANSI} escape sequences for
15586 colored output to terminals (@samp{\033[m} is the sequence to restore
15587 normal output); the behavior depends on whether input is seekable:
15589 @example
15590 $ @kbd{printf 'esc\033[mape\n' > sample}
15591 $ @kbd{grep . sample}
15592 Binary file sample matches
15593 $ @kbd{cat sample | grep .}
15594 escape
15595 @end example
15598 @item @command{join}
15599 @c -----------------
15600 @prindex @command{join}
15601 Solaris 8 @command{join} has bugs when the second operand is standard
15602 input, and when standard input is a pipe.  For example, the following
15603 shell script causes Solaris 8 @command{join} to loop forever:
15605 @example
15606 cat >file <<'EOF'
15607 1 x
15608 2 y
15610 cat file | join file -
15611 @end example
15613 Use @samp{join - file} instead.
15616 @item @command{ln}
15617 @c ---------------
15618 @prindex @command{ln}
15619 @cindex Symbolic links
15620 Don't rely on @command{ln} having a @option{-f} option.  Symbolic links
15621 are not available on old systems; use @samp{$(LN_S)} as a portable substitute.
15623 For versions of the @acronym{DJGPP} before 2.04,
15624 @command{ln} emulates symbolic links
15625 to executables by generating a stub that in turn calls the real
15626 program.  This feature also works with nonexistent files like in the
15627 Posix spec.  So @samp{ln -s file link} generates @file{link.exe},
15628 which attempts to call @file{file.exe} if run.  But this feature only
15629 works for executables, so @samp{cp -p} is used instead for these
15630 systems.  @acronym{DJGPP} versions 2.04 and later have full support
15631 for symbolic links.
15634 @item @command{ls}
15635 @c ---------------
15636 @prindex @command{ls}
15637 @cindex Listing directories
15638 The portable options are @option{-acdilrtu}.  Current practice is for
15639 @option{-l} to output both owner and group, even though ancient versions
15640 of @command{ls} omitted the group.
15642 On ancient hosts, @samp{ls foo} sent the diagnostic @samp{foo not found}
15643 to standard output if @file{foo} did not exist.  Hence a shell command
15644 like @samp{sources=`ls *.c 2>/dev/null`} did not always work, since it
15645 was equivalent to @samp{sources='*.c not found'} in the absence of
15646 @samp{.c} files.  This is no longer a practical problem, since current
15647 @command{ls} implementations send diagnostics to standard error.
15649 @item @command{mkdir}
15650 @c ------------------
15651 @prindex @command{mkdir}
15652 @cindex Making directories
15653 No @command{mkdir} option is portable to older systems.  Instead of
15654 @samp{mkdir -p @var{file-name}}, you should use
15655 @code{AS_MKDIR_P(@var{file-name})} (@pxref{Programming in M4sh})
15656 or @code{AC_PROG_MKDIR_P} (@pxref{Particular Programs}).
15658 Combining the @option{-m} and @option{-p} options, as in @samp{mkdir -m
15659 go-w -p @var{dir}}, often leads to trouble.  Free@acronym{BSD}
15660 @command{mkdir} incorrectly attempts to change the permissions of
15661 @var{dir} even if it already exists.  @acronym{HP-UX} 11.23 and
15662 @acronym{IRIX} 6.5 @command{mkdir} often assign the wrong permissions to
15663 any newly-created parents of @var{dir}.
15665 Posix does not clearly specify whether @samp{mkdir -p foo}
15666 should succeed when @file{foo} is a symbolic link to an already-existing
15667 directory.  The @acronym{GNU} Core Utilities 5.1.0 @command{mkdir}
15668 succeeds, but Solaris @command{mkdir} fails.
15670 Traditional @code{mkdir -p} implementations suffer from race conditions.
15671 For example, if you invoke @code{mkdir -p a/b} and @code{mkdir -p a/c}
15672 at the same time, both processes might detect that @file{a} is missing,
15673 one might create @file{a}, then the other might try to create @file{a}
15674 and fail with a @code{File exists} diagnostic.  The @acronym{GNU} Core
15675 Utilities (@samp{fileutils} version 4.1), Free@acronym{BSD} 5.0,
15676 Net@acronym{BSD} 2.0.2, and Open@acronym{BSD} 2.4 are known to be
15677 race-free when two processes invoke @code{mkdir -p} simultaneously, but
15678 earlier versions are vulnerable.  Solaris @command{mkdir} is still
15679 vulnerable as of Solaris 10, and other traditional Unix systems are
15680 probably vulnerable too.  This possible race is harmful in parallel
15681 builds when several Make rules call @code{mkdir -p} to
15682 construct directories.  You may use
15683 @code{install-sh -d} as a safe replacement, provided this script is
15684 recent enough; the copy shipped with Autoconf 2.60 and Automake 1.10 is
15685 OK, but copies from older versions are vulnerable.
15688 @item @command{mktemp}
15689 @c -------------------
15690 @prindex @command{mktemp}
15691 @cindex Creating temporary files
15692 Shell scripts can use temporary files safely with @command{mktemp}, but
15693 it does not exist on all systems.  A portable way to create a safe
15694 temporary file name is to create a temporary directory with mode 700 and
15695 use a file inside this directory.  Both methods prevent attackers from
15696 gaining control, though @command{mktemp} is far less likely to fail
15697 gratuitously under attack.
15699 Here is sample code to create a new temporary directory safely:
15701 @example
15702 # Create a temporary directory $tmp in $TMPDIR (default /tmp).
15703 # Use mktemp if possible; otherwise fall back on mkdir,
15704 # with $RANDOM to make collisions less likely.
15705 : $@{TMPDIR=/tmp@}
15707   tmp=`
15708     (umask 077 && mktemp -d "$TMPDIR/fooXXXXXX") 2>/dev/null
15709   ` &&
15710   test -n "$tmp" && test -d "$tmp"
15711 @} || @{
15712   tmp=$TMPDIR/foo$$-$RANDOM
15713   (umask 077 && mkdir "$tmp")
15714 @} || exit $?
15715 @end example
15718 @item @command{mv}
15719 @c ---------------
15720 @prindex @command{mv}
15721 @cindex Moving open files
15722 The only portable options are @option{-f} and @option{-i}.
15724 Moving individual files between file systems is portable (it was in Unix
15725 version 6),
15726 but it is not always atomic: when doing @samp{mv new existing}, there's
15727 a critical section where neither the old nor the new version of
15728 @file{existing} actually exists.
15730 On some systems moving files from @file{/tmp} can sometimes cause
15731 undesirable (but perfectly valid) warnings, even if you created these
15732 files.  This is because @file{/tmp} belongs to a group that ordinary
15733 users are not members of, and files created in @file{/tmp} inherit
15734 the group of @file{/tmp}.  When the file is copied, @command{mv} issues
15735 a diagnostic without failing:
15737 @smallexample
15738 $ @kbd{touch /tmp/foo}
15739 $ @kbd{mv /tmp/foo .}
15740 @error{}mv: ./foo: set owner/group (was: 100/0): Operation not permitted
15741 $ @kbd{echo $?}
15743 $ @kbd{ls foo}
15745 @end smallexample
15747 @noindent
15748 This annoying behavior conforms to Posix, unfortunately.
15750 Moving directories across mount points is not portable, use @command{cp}
15751 and @command{rm}.
15753 @acronym{DOS} variants cannot rename or remove open files, and do not
15754 support commands like @samp{mv foo bar >foo}, even though this is
15755 perfectly portable among Posix hosts.
15758 @item @command{od}
15759 @c ---------------
15760 @prindex @command{od}
15762 In Mac OS X 10.3, @command{od} does not support the
15763 standard Posix options @option{-A}, @option{-j}, @option{-N}, or
15764 @option{-t}, or the @acronym{XSI} option @option{-s}.  The only
15765 supported Posix option is @option{-v}, and the only supported
15766 @acronym{XSI} options are those in @option{-bcdox}.  The @acronym{BSD}
15767 @command{hexdump} program can be used instead.
15769 This problem no longer exists in Mac OS X 10.4.3.
15772 @item @command{rm}
15773 @c ---------------
15774 @prindex @command{rm}
15775 The @option{-f} and @option{-r} options are portable.
15777 It is not portable to invoke @command{rm} without operands.  For
15778 example, on many systems @samp{rm -f -r} (with no other arguments)
15779 silently succeeds without doing anything, but it fails with a diagnostic
15780 on Net@acronym{BSD} 2.0.2.
15782 A file might not be removed even if its parent directory is writable
15783 and searchable.  Many Posix hosts cannot remove a mount point, a named
15784 stream, a working directory, or a last link to a file that is being
15785 executed.
15787 @acronym{DOS} variants cannot rename or remove open files, and do not
15788 support commands like @samp{rm foo >foo}, even though this is
15789 perfectly portable among Posix hosts.
15792 @item @command{sed}
15793 @c ----------------
15794 @prindex @command{sed}
15795 Patterns should not include the separator (unless escaped), even as part
15796 of a character class.  In conformance with Posix, the Cray
15797 @command{sed} rejects @samp{s/[^/]*$//}: use @samp{s,[^/]*$,,}.
15799 Avoid empty patterns within parentheses (i.e., @samp{\(\)}).  Posix does
15800 not require support for empty patterns, and Unicos 9 @command{sed} rejects
15801 them.
15803 Unicos 9 @command{sed} loops endlessly on patterns like @samp{.*\n.*}.
15805 Sed scripts should not use branch labels longer than 7 characters and
15806 should not contain comments.  @acronym{HP-UX} sed has a limit of 99 commands
15807 (not counting @samp{:} commands) and
15808 48 labels, which can not be circumvented by using more than one script
15809 file.  It can execute up to 19 reads with the @samp{r} command per cycle.
15810 Solaris @command{/usr/ucb/sed} rejects usages that exceed an limit of
15811 about 6000 bytes for the internal representation of commands.
15813 Avoid redundant @samp{;}, as some @command{sed} implementations, such as
15814 Net@acronym{BSD} 1.4.2's, incorrectly try to interpret the second
15815 @samp{;} as a command:
15817 @example
15818 $ @kbd{echo a | sed 's/x/x/;;s/x/x/'}
15819 sed: 1: "s/x/x/;;s/x/x/": invalid command code ;
15820 @end example
15822 Input should not have unreasonably long lines, since some @command{sed}
15823 implementations have an input buffer limited to 4000 bytes.
15825 Portable @command{sed} regular expressions should use @samp{\} only to escape
15826 characters in the string @samp{$()*.0123456789[\^n@{@}}.  For example,
15827 alternation, @samp{\|}, is common but Posix does not require its
15828 support, so it should be avoided in portable scripts.  Solaris
15829 @command{sed} does not support alternation; e.g., @samp{sed '/a\|b/d'}
15830 deletes only lines that contain the literal string @samp{a|b}.
15831 Similarly, @samp{\+} and @samp{\?} should be avoided.
15833 Anchors (@samp{^} and @samp{$}) inside groups are not portable.
15835 Nested parentheses in patterns (e.g., @samp{\(\(a*\)b*)\)}) are
15836 quite portable to current hosts, but was not supported by some ancient
15837 @command{sed} implementations like SVR3.
15839 Some @command{sed} implementations, e.g., Solaris,
15840 restrict the special role of the asterisk to one-character regular expressions.
15841 This may lead to unexpected behavior:
15843 @example
15844 $ @kbd{echo '1*23*4' | /usr/bin/sed 's/\(.\)*/x/g'}
15845 x2x4
15846 $ @kbd{echo '1*23*4' | /usr/xpg4/bin/sed 's/\(.\)*/x/g'}
15848 @end example
15850 The @option{-e} option is mostly portable.
15851 However, its argument
15852 cannot start with @samp{a}, @samp{c}, or @samp{i},
15853 as this runs afoul of a Tru64 5.1 bug.
15854 Also, its argument cannot be empty, as this fails on @acronym{AIX} 5.3.
15855 Some people prefer to use @samp{-e}:
15857 @example
15858 sed -e '@var{command-1}' \
15859     -e '@var{command-2}'
15860 @end example
15862 @noindent
15863 as opposed to the equivalent:
15865 @example
15866 sed '
15867   @var{command-1}
15868   @var{command-2}
15870 @end example
15872 @noindent
15873 The following usage is sometimes equivalent:
15875 @example
15876 sed '@var{command-1};@var{command-2}'
15877 @end example
15879 but Posix says that this use of a semicolon has undefined effect if
15880 @var{command-1}'s verb is @samp{@{}, @samp{a}, @samp{b}, @samp{c},
15881 @samp{i}, @samp{r}, @samp{t}, @samp{w}, @samp{:}, or @samp{#}, so you
15882 should use semicolon only with simple scripts that do not use these
15883 verbs.
15885 Commands inside @{ @} brackets are further restricted.  Posix says that
15886 they cannot be preceded by addresses, @samp{!}, or @samp{;}, and that
15887 each command must be followed immediately by a newline, without any
15888 intervening blanks or semicolons.  The closing bracket must be alone on
15889 a line, other than white space preceding or following it.
15891 Contrary to yet another urban legend, you may portably use @samp{&} in
15892 the replacement part of the @code{s} command to mean ``what was
15893 matched''.  All descendants of Unix version 7 @command{sed}
15894 (at least; we
15895 don't have first hand experience with older @command{sed} implementations) have
15896 supported it.
15898 Posix requires that you must not have any white space between
15899 @samp{!} and the following command.  It is OK to have blanks between
15900 the address and the @samp{!}.  For instance, on Solaris:
15902 @example
15903 $ @kbd{echo "foo" | sed -n '/bar/ ! p'}
15904 @error{}Unrecognized command: /bar/ ! p
15905 $ @kbd{echo "foo" | sed -n '/bar/! p'}
15906 @error{}Unrecognized command: /bar/! p
15907 $ @kbd{echo "foo" | sed -n '/bar/ !p'}
15909 @end example
15911 Posix also says that you should not combine @samp{!} and @samp{;}.  If
15912 you use @samp{!}, it is best to put it on a command that is delimited by
15913 newlines rather than @samp{;}.
15915 Also note that Posix requires that the @samp{b}, @samp{t}, @samp{r}, and
15916 @samp{w} commands be followed by exactly one space before their argument.
15917 On the other hand, no white space is allowed between @samp{:} and the
15918 subsequent label name.
15920 If a sed script is specified on the command line and ends in an
15921 @samp{a}, @samp{c}, or @samp{i} command, the last line of inserted text
15922 should be followed by a newline.  Otherwise some @command{sed}
15923 implementations (e.g., Open@acronym{BSD} 3.9) do not append a newline to the
15924 inserted text.
15926 Many @command{sed} implementations (e.g., MacOS X 10.4,
15927 Open@acronym{BSD} 3.9, Solaris 10
15928 @command{/usr/ucb/sed}) strip leading white space from the text of
15929 @samp{a}, @samp{c}, and @samp{i} commands.  Prepend a backslash to
15930 work around this incompatibility with Posix:
15932 @example
15933 $ @kbd{echo flushleft | sed 'a\}
15934 > @kbd{   indented}
15935 > @kbd{'}
15936 flushleft
15937 indented
15938 $ @kbd{echo foo | sed 'a\}
15939 > @kbd{\   indented}
15940 > @kbd{'}
15941 flushleft
15942    indented
15943 @end example
15945 Posix requires that with an empty regular expression, the last non-empty
15946 regular expression from either an address specification or substitution
15947 command is applied.  However, busybox 1.6.1 complains when using a
15948 substitution command with a replacement containing a back-reference to
15949 an empty regular expression; the workaround is repeating the regular
15950 expression.
15952 @example
15953 $ @kbd{echo abc | busybox sed '/a\(b\)c/ s//\1/'}
15954 sed: No previous regexp.
15955 $ @kbd{echo abc | busybox sed '/a\(b\)c/ s/a\(b\)c/\1/'}
15957 @end example
15960 @item @command{sed} (@samp{t})
15961 @c ---------------------------
15962 @prindex @command{sed} (@samp{t})
15963 Some old systems have @command{sed} that ``forget'' to reset their
15964 @samp{t} flag when starting a new cycle.  For instance on @acronym{MIPS
15965 RISC/OS}, and on @sc{irix} 5.3, if you run the following @command{sed}
15966 script (the line numbers are not actual part of the texts):
15968 @example
15969 s/keep me/kept/g  # a
15970 t end             # b
15971 s/.*/deleted/g    # c
15972 :end              # d
15973 @end example
15975 @noindent
15978 @example
15979 delete me         # 1
15980 delete me         # 2
15981 keep me           # 3
15982 delete me         # 4
15983 @end example
15985 @noindent
15986 you get
15988 @example
15989 deleted
15990 delete me
15991 kept
15992 deleted
15993 @end example
15995 @noindent
15996 instead of
15998 @example
15999 deleted
16000 deleted
16001 kept
16002 deleted
16003 @end example
16005 Why?  When processing line 1, (c) matches, therefore sets the @samp{t}
16006 flag, and the output is produced.  When processing
16007 line 2, the @samp{t} flag is still set (this is the bug).  Command (a)
16008 fails to match, but @command{sed} is not supposed to clear the @samp{t}
16009 flag when a substitution fails.  Command (b) sees that the flag is set,
16010 therefore it clears it, and jumps to (d), hence you get @samp{delete me}
16011 instead of @samp{deleted}.  When processing line (3), @samp{t} is clear,
16012 (a) matches, so the flag is set, hence (b) clears the flags and jumps.
16013 Finally, since the flag is clear, line 4 is processed properly.
16015 There are two things one should remember about @samp{t} in @command{sed}.
16016 Firstly, always remember that @samp{t} jumps if @emph{some} substitution
16017 succeeded, not only the immediately preceding substitution.  Therefore,
16018 always use a fake @samp{t clear} followed by a @samp{:clear} on the next
16019 line, to reset the @samp{t} flag where needed.
16021 Secondly, you cannot rely on @command{sed} to clear the flag at each new
16022 cycle.
16024 One portable implementation of the script above is:
16026 @example
16027 t clear
16028 :clear
16029 s/keep me/kept/g
16030 t end
16031 s/.*/deleted/g
16032 :end
16033 @end example
16035 @item @command{touch}
16036 @c ------------------
16037 @prindex @command{touch}
16038 @cindex timestamp resolution
16039 If you specify the desired timestamp (e.g., with the @option{-r}
16040 option), @command{touch} typically uses the @code{utime} or
16041 @code{utimes} system call, which can result in the same kind of
16042 timestamp truncation problems that @samp{cp -p} has.
16044 On ancient @acronym{BSD} systems, @command{touch} or any command that
16045 results in an empty file does not update the timestamps, so use a
16046 command like @command{echo} as a workaround.
16047 Also,
16048 @acronym{GNU} @command{touch} 3.16r (and presumably all before that)
16049 fails to work on SunOS 4.1.3 when the empty file is on an
16050 @acronym{NFS}-mounted 4.2 volume.
16051 However, these problems are no longer of practical concern.
16053 @item @command{tr}
16054 @c ---------------
16055 @prindex @command{tr}
16056 @cindex carriage return, deleting
16057 @cindex deleting carriage return
16058 Not all versions of @command{tr} handle all backslash character escapes.
16059 For example, Solaris 10 @command{/usr/ucb/tr} falls over, even though
16060 Solaris contains more modern @command{tr} in other locations.
16061 Therefore, it is more portable to use octal escapes, even though this
16062 ties the result to @acronym{ASCII}, when using @command{tr} to delete
16063 newlines or carriage returns.
16065 @example
16066 $ @kbd{@{ echo moon; echo light; @} | /usr/ucb/tr -d '\n' ; echo}
16068 light
16069 $ @kbd{@{ echo moon; echo light; @} | /usr/bin/tr -d '\n' ; echo}
16070 moonlight
16071 $ @kbd{@{ echo moon; echo light; @} | /usr/ucb/tr -d '\012' ; echo}
16072 moonlight
16073 @end example
16075 @end table
16078 @node Portable Make
16079 @chapter Portable Make Programming
16080 @prindex @command{make}
16081 @cindex Limitations of @command{make}
16083 Writing portable makefiles is an art.  Since a makefile's commands are
16084 executed by the shell, you must consider the shell portability issues
16085 already mentioned.  However, other issues are specific to @command{make}
16086 itself.
16088 @menu
16089 * $< in Ordinary Make Rules::   $< in ordinary rules
16090 * Failure in Make Rules::       Failing portably in rules
16091 * Special Chars in Names::      Special Characters in Macro Names
16092 * Backslash-Newline-Newline::   Empty last lines in macro definitions
16093 * Backslash-Newline Comments::  Spanning comments across line boundaries
16094 * Long Lines in Makefiles::     Line length limitations
16095 * Macros and Submakes::         @code{make macro=value} and submakes
16096 * The Make Macro MAKEFLAGS::    @code{$(MAKEFLAGS)} portability issues
16097 * The Make Macro SHELL::        @code{$(SHELL)} portability issues
16098 * Comments in Make Rules::      Other problems with Make comments
16099 * obj/ and Make::               Don't name a subdirectory @file{obj}
16100 * make -k Status::              Exit status of @samp{make -k}
16101 * VPATH and Make::              @code{VPATH} woes
16102 * Single Suffix Rules::         Single suffix rules and separated dependencies
16103 * Timestamps and Make::         Subsecond timestamp resolution
16104 @end menu
16106 @node $< in Ordinary Make Rules
16107 @section @code{$<} in Ordinary Make Rules
16109 Posix says that the @samp{$<} construct in makefiles can be
16110 used only in inference rules and in the @samp{.DEFAULT} rule; its
16111 meaning in ordinary rules is unspecified.  Solaris @command{make}
16112 for instance replaces it with the empty string.  Open@acronym{BSD} (3.0 and
16113 later) @command{make} diagnoses these uses and errors out.
16115 @node Failure in Make Rules
16116 @section Failure in Make Rules
16118 Since 1992 Posix has required that @command{make} must invoke
16119 each command with the equivalent of a @samp{sh -c} subshell.  However,
16120 many @command{make} implementations, including @acronym{BSD} make through 2004,
16121 use @samp{sh -e -c} instead, and the @option{-e} option causes the
16122 subshell to exit immediately if a subsidiary simple-command fails.  For
16123 example, the command @samp{touch T; rm -f U} always attempts to
16124 remove @file{U} with Posix make, but incompatible
16125 @command{make} implementations skip the @command{rm} if the
16126 @command{touch} fails.  One way to work around this is to reword the
16127 affected simple-commands so that they always succeed, e.g., @samp{touch
16128 T || :; rm -f U}.
16129 However, even this approach can run into common bugs in @acronym{BSD}
16130 implementations of the @option{-e} option of @command{sh} and
16131 @command{set} (@pxref{Limitations of Builtins}), so if you are worried
16132 about porting to buggy @acronym{BSD} shells it may be simpler to migrate
16133 complicated @command{make} actions into separate scripts.
16135 @node Special Chars in Names
16136 @section Special Characters in Make Macro Names
16138 Posix limits macro names to nonempty strings containing only
16139 @acronym{ASCII} letters and digits, @samp{.}, and @samp{_}.  Many
16140 @command{make} implementations allow a wider variety of characters, but
16141 portable makefiles should avoid them.  It is portable to start a name
16142 with a special character, e.g., @samp{$(.FOO)}.
16144 Some ancient @command{make} implementations don't support leading
16145 underscores in macro names.  An example is @acronym{NEWS-OS} 4.2R.
16147 @example
16148 $ @kbd{cat Makefile}
16149 _am_include = #
16150 _am_quote =
16151 all:; @@echo this is test
16152 $ @kbd{make}
16153 Make: Must be a separator on rules line 2.  Stop.
16154 $ @kbd{cat Makefile2}
16155 am_include = #
16156 am_quote =
16157 all:; @@echo this is test
16158 $ @kbd{make -f Makefile2}
16159 this is test
16160 @end example
16162 @noindent
16163 However, this problem is no longer of practical concern.
16165 @node Backslash-Newline-Newline
16166 @section Backslash-Newline-Newline in Make Macro Values
16168 @c  This has been seen on ia64 hpux 11.20, and on one hppa hpux 10.20,
16169 @c  but another hppa hpux 10.20 didn't have it.  Bob Proulx
16170 @c  <bob@proulx.com> thinks it was in hpux 8.0 too.
16171 On some versions of @acronym{HP-UX}, @command{make} reads multiple newlines
16172 following a backslash, continuing to the next non-empty line.  For
16173 example,
16175 @example
16176 FOO = one \
16178 BAR = two
16180 test:
16181         : FOO is "$(FOO)"
16182         : BAR is "$(BAR)"
16183 @end example
16185 @noindent
16186 shows @code{FOO} equal to @code{one BAR = two}.  Other implementations
16187 sensibly let a backslash continue only to the immediately following
16188 line.
16190 @node Backslash-Newline Comments
16191 @section Backslash-Newline in Make Comments
16193 According to Posix, Make comments start with @code{#}
16194 and continue until an unescaped newline is reached.
16196 @example
16197 $ @kbd{cat Makefile}
16198 # A = foo \
16199       bar \
16200       baz
16202 all:
16203         @@echo ok
16204 $ @kbd{make}   # GNU make
16206 @end example
16208 @noindent
16209 However this is not always the case.  Some implementations
16210 discard everything from @code{#} through the end of the line, ignoring any
16211 trailing backslash.
16213 @example
16214 $ @kbd{pmake}  # BSD make
16215 "Makefile", line 3: Need an operator
16216 Fatal errors encountered -- cannot continue
16217 @end example
16219 @noindent
16220 Therefore, if you want to comment out a multi-line definition, prefix each
16221 line with @code{#}, not only the first.
16223 @example
16224 # A = foo \
16225 #     bar \
16226 #     baz
16227 @end example
16229 @node Long Lines in Makefiles
16230 @section Long Lines in Makefiles
16232 Tru64 5.1's @command{make} has been reported to crash when given a
16233 makefile with lines longer than around 20 kB.  Earlier versions are
16234 reported to exit with @code{Line too long} diagnostics.
16236 @node Macros and Submakes
16237 @section @code{make macro=value} and Submakes
16239 A command-line variable definition such as @code{foo=bar} overrides any
16240 definition of @code{foo} in a makefile.  Some @command{make}
16241 implementations (such as @acronym{GNU} @command{make}) propagate this
16242 override to subsidiary invocations of @command{make}.  Some other
16243 implementations do not pass the substitution along to submakes.
16245 @example
16246 $ @kbd{cat Makefile}
16247 foo = foo
16248 one:
16249         @@echo $(foo)
16250         $(MAKE) two
16251 two:
16252         @@echo $(foo)
16253 $ @kbd{make foo=bar}            # GNU make 3.79.1
16255 make two
16256 make[1]: Entering directory `/home/adl'
16258 make[1]: Leaving directory `/home/adl'
16259 $ @kbd{pmake foo=bar}           # BSD make
16261 pmake two
16263 @end example
16265 You have a few possibilities if you do want the @code{foo=bar} override
16266 to propagate to submakes.  One is to use the @option{-e}
16267 option, which causes all environment variables to have precedence over
16268 the makefile macro definitions, and declare foo as an environment
16269 variable:
16271 @example
16272 $ @kbd{env foo=bar make -e}
16273 @end example
16275 The @option{-e} option is propagated to submakes automatically,
16276 and since the environment is inherited between @command{make}
16277 invocations, the @code{foo} macro is overridden in
16278 submakes as expected.
16280 This syntax (@code{foo=bar make -e}) is portable only when used
16281 outside of a makefile, for instance from a script or from the
16282 command line.  When run inside a @command{make} rule, @acronym{GNU}
16283 @command{make} 3.80 and prior versions forget to propagate the
16284 @option{-e} option to submakes.
16286 Moreover, using @option{-e} could have unexpected side effects if your
16287 environment contains some other macros usually defined by the
16288 makefile.  (See also the note about @code{make -e} and @code{SHELL}
16289 below.)
16291 Another way to propagate overrides to submakes is to do it
16292 manually, from your makefile:
16294 @example
16295 foo = foo
16296 one:
16297         @@echo $(foo)
16298         $(MAKE) foo=$(foo) two
16299 two:
16300         @@echo $(foo)
16301 @end example
16303 You need to foresee all macros that a user might want to override if
16304 you do that.
16306 @node The Make Macro MAKEFLAGS
16307 @section The Make Macro MAKEFLAGS
16308 @cindex @code{MAKEFLAGS} and @command{make}
16309 @cindex @command{make} and @code{MAKEFLAGS}
16311 Posix requires @command{make} to use @code{MAKEFLAGS} to affect the
16312 current and recursive invocations of make, but allows implementations
16313 several formats for the variable.  It is tricky to parse
16314 @code{$MAKEFLAGS} to determine whether @option{-s} for silent execution
16315 or @option{-k} for continued execution are in effect.  For example, you
16316 cannot assume that the first space-separated word in @code{$MAKEFLAGS}
16317 contains single-letter options, since in the Cygwin version of
16318 @acronym{GNU} @command{make} it is either @option{--unix} or
16319 @option{--win32} with the second word containing single-letter options.
16321 @example
16322 $ @kbd{cat Makefile}
16323 all:
16324         @@echo MAKEFLAGS = $(MAKEFLAGS)
16325 $ @kbd{make}
16326 MAKEFLAGS = --unix
16327 $ @kbd{make -k}
16328 MAKEFLAGS = --unix -k
16329 @end example
16331 @node The Make Macro SHELL
16332 @section The Make Macro @code{SHELL}
16333 @cindex @code{SHELL} and @command{make}
16334 @cindex @command{make} and @code{SHELL}
16336 Posix-compliant @command{make} internally uses the @code{$(SHELL)}
16337 macro to spawn shell processes and execute Make rules.  This
16338 is a builtin macro supplied by @command{make}, but it can be modified
16339 by a makefile or by a command-line argument.
16341 Not all @command{make} implementations define this @code{SHELL} macro.
16342 Tru64
16343 @command{make} is an example; this implementation always uses
16344 @code{/bin/sh}.  So it's a good idea to always define @code{SHELL} in
16345 your makefiles.  If you use Autoconf, do
16347 @example
16348 SHELL = @@SHELL@@
16349 @end example
16351 @noindent
16352 If you use Automake, this is done for you.
16354 Do not force @code{SHELL = /bin/sh} because that is not correct
16355 everywhere.  Remember, @file{/bin/sh} is not Posix compliant on many
16356 systems, such as FreeBSD 4, NetBSD 3, AIX 3, Solaris 10, or Tru64.
16357 Additionally, @acronym{DJGPP} lacks @code{/bin/sh}, and when its
16358 @acronym{GNU} @command{make} port sees such a setting it enters a
16359 special emulation mode where features like pipes and redirections are
16360 emulated on top of DOS's @command{command.com}.  Unfortunately this
16361 emulation is incomplete; for instance it does not handle command
16362 substitutions.  Using @code{@@SHELL@@} means that your makefile will
16363 benefit from the same improved shell, such as @command{bash} or
16364 @command{ksh}, that was discovered during @command{configure}, so that
16365 you aren't fighting two different sets of shell bugs between the two
16366 contexts.
16368 Posix-compliant @command{make} should never acquire the value of
16369 $(SHELL) from the environment, even when @code{make -e} is used
16370 (otherwise, think about what would happen to your rules if
16371 @code{SHELL=/bin/tcsh}).
16373 However not all @command{make} implementations have this exception.
16374 For instance it's not surprising that Tru64 @command{make} doesn't
16375 protect @code{SHELL}, since it doesn't use it.
16377 @example
16378 $ @kbd{cat Makefile}
16379 SHELL = /bin/sh
16380 FOO = foo
16381 all:
16382         @@echo $(SHELL)
16383         @@echo $(FOO)
16384 $ @kbd{env SHELL=/bin/tcsh FOO=bar make -e}   # Tru64 Make
16385 /bin/tcsh
16387 $ @kbd{env SHELL=/bin/tcsh FOO=bar gmake -e}  # GNU make
16388 /bin/sh
16390 @end example
16392 Conversely, @command{make} is not supposed to export any changes to the
16393 macro @code{SHELL} to child processes.  Again, many implementations
16394 break this rule:
16396 @example
16397 $ @kbd{cat Makefile}
16398 all:
16399         @@echo $(SHELL)
16400         @@printenv SHELL
16401 $ @kbd{env SHELL=sh make -e SHELL=/bin/ksh}   # BSD Make, GNU make 3.80
16402 /bin/ksh
16403 /bin/ksh
16404 $ @kbd{env SHELL=sh gmake -e SHELL=/bin/ksh}  # GNU make 3.81
16405 /bin/ksh
16407 @end example
16409 @node Comments in Make Rules
16410 @section Comments in Make Rules
16411 @cindex Comments in @file{Makefile} rules
16412 @cindex @file{Makefile} rules and comments
16414 Never put comments in a rule.
16416 Some @command{make} treat anything starting with a tab as a command for
16417 the current rule, even if the tab is immediately followed by a @code{#}.
16418 The @command{make} from Tru64 Unix V5.1 is one of them.  The following
16419 makefile runs @code{# foo} through the shell.
16421 @example
16422 all:
16423         # foo
16424 @end example
16426 @node obj/ and Make
16427 @section The @file{obj/} Subdirectory and Make
16428 @cindex @file{obj/}, subdirectory
16429 @cindex @acronym{BSD} @command{make} and @file{obj/}
16431 Never name one of your subdirectories @file{obj/} if you don't like
16432 surprises.
16434 If an @file{obj/} directory exists, @acronym{BSD} @command{make} enters it
16435 before reading the makefile.  Hence the makefile in the
16436 current directory is not read.
16438 @example
16439 $ @kbd{cat Makefile}
16440 all:
16441         echo Hello
16442 $ @kbd{cat obj/Makefile}
16443 all:
16444         echo World
16445 $ @kbd{make}      # GNU make
16446 echo Hello
16447 Hello
16448 $ @kbd{pmake}     # BSD make
16449 echo World
16450 World
16451 @end example
16453 @node make -k Status
16454 @section Exit Status of @code{make -k}
16455 @cindex @code{make -k}
16457 Do not rely on the exit status of @code{make -k}.  Some implementations
16458 reflect whether they encountered an error in their exit status; other
16459 implementations always succeed.
16461 @example
16462 $ @kbd{cat Makefile}
16463 all:
16464         false
16465 $ @kbd{make -k; echo exit status: $?}    # GNU make
16466 false
16467 make: *** [all] Error 1
16468 exit status: 2
16469 $ @kbd{pmake -k; echo exit status: $?}   # BSD make
16470 false
16471 *** Error code 1 (continuing)
16472 exit status: 0
16473 @end example
16475 @node VPATH and Make
16476 @section @code{VPATH} and Make
16477 @cindex @code{VPATH}
16479 Posix does not specify the semantics of @code{VPATH}.  Typically,
16480 @command{make} supports @code{VPATH}, but its implementation is not
16481 consistent.
16483 Autoconf and Automake support makefiles whose usages of @code{VPATH} are
16484 portable to recent-enough popular implementations of @command{make}, but
16485 to keep the resulting makefiles portable, a package's makefile
16486 prototypes must take the following issues into account.  These issues
16487 are complicated and are often poorly understood, and installers who use
16488 @code{VPATH} should expect to find many bugs in this area.  If you use
16489 @code{VPATH}, the simplest way to avoid these portability bugs is to
16490 stick with @acronym{GNU} @command{make}, since it is the most
16491 commonly-used @command{make} among Autoconf users.
16493 Here are some known issues with some @code{VPATH}
16494 implementations.
16496 @menu
16497 * VPATH and Double-colon::      Problems with @samp{::} on ancient hosts
16498 * $< in Explicit Rules::        @code{$<} does not work in ordinary rules
16499 * Automatic Rule Rewriting::    @code{VPATH} goes wild on Solaris
16500 * Tru64 Directory Magic::       @command{mkdir} goes wild on Tru64
16501 * Make Target Lookup::          More details about @code{VPATH} lookup
16502 @end menu
16504 @node VPATH and Double-colon
16505 @subsection @code{VPATH} and Double-colon Rules
16506 @cindex @code{VPATH} and double-colon rules
16507 @cindex double-colon rules and @code{VPATH}
16509 With ancient versions of Sun @command{make},
16510 any assignment to @code{VPATH} causes @command{make} to execute only
16511 the first set of double-colon rules.
16512 However, this problem is no longer of practical concern.
16514 @node $< in Explicit Rules
16515 @subsection @code{$<} Not Supported in Explicit Rules
16516 @cindex explicit rules, @code{$<}, and @code{VPATH}
16517 @cindex @code{$<}, explicit rules, and @code{VPATH}
16518 @cindex @code{VPATH}, explicit rules, and @code{$<}
16520 Using @code{$<} in explicit rules is not portable.
16521 The prerequisite file must be named explicitly in the rule.  If you want
16522 to find the prerequisite via a @code{VPATH} search, you have to code the
16523 whole thing manually.  @xref{Build Directories}.
16525 @node Automatic Rule Rewriting
16526 @subsection Automatic Rule Rewriting
16527 @cindex @code{VPATH} and automatic rule rewriting
16528 @cindex automatic rule rewriting and @code{VPATH}
16530 Some @command{make} implementations, such as Solaris and Tru64,
16531 search for prerequisites in @code{VPATH} and
16532 then rewrite each occurrence as a plain word in the rule.
16533 For instance:
16535 @example
16536 # This isn't portable to GNU make.
16537 VPATH = ../pkg/src
16538 f.c: if.c
16539         cp if.c f.c
16540 @end example
16542 @noindent
16543 executes @code{cp ../pkg/src/if.c f.c} if @file{if.c} is
16544 found in @file{../pkg/src}.
16546 However, this rule leads to real problems in practice.  For example, if
16547 the source directory contains an ordinary file named @file{test} that is
16548 used in a dependency, Solaris @command{make} rewrites commands like
16549 @samp{if test -r foo; @dots{}} to @samp{if ../pkg/src/test -r foo;
16550 @dots{}}, which is typically undesirable.  To avoid this problem,
16551 portable makefiles should never mention a source file whose name is that
16552 of a shell keyword like @file{until} or a shell command like
16553 @command{cat} or @command{gcc} or @command{test}.
16555 Because of these problems @acronym{GNU} @command{make} and many other
16556 @command{make} implementations do not rewrite commands, so portable
16557 makefiles should
16558 search @code{VPATH} manually.  It is tempting to write this:
16560 @smallexample
16561 # This isn't portable to Solaris make.
16562 VPATH = ../pkg/src
16563 f.c: if.c
16564         cp `test -f if.c || echo $(VPATH)/`if.c f.c
16565 @end smallexample
16567 @noindent
16568 However, the ``prerequisite rewriting'' still applies here.  So if
16569 @file{if.c} is in @file{../pkg/src}, Solaris and Tru64 @command{make}
16570 execute
16572 @smallexample
16573 cp `test -f ../pkg/src/if.c || echo ../pkg/src/`if.c f.c
16574 @end smallexample
16576 @noindent
16577 which reduces to
16579 @example
16580 cp if.c f.c
16581 @end example
16583 @noindent
16584 and thus fails.  Oops.
16586 A simple workaround, and good practice anyway, is to use @samp{$?} and
16587 @samp{$@@} when possible:
16589 @smallexample
16590 VPATH = ../pkg/src
16591 f.c: if.c
16592         cp $? $@@
16593 @end smallexample
16595 @noindent
16596 but this does not generalize well to commands with multiple
16597 prerequisites.  A more general workaround is to rewrite the rule so that
16598 the prerequisite @file{if.c} never appears as a plain word.  For
16599 example, these three rules would be safe, assuming @file{if.c} is in
16600 @file{../pkg/src} and the other files are in the working directory:
16602 @smallexample
16603 VPATH = ../pkg/src
16604 f.c: if.c f1.c
16605         cat `test -f ./if.c || echo $(VPATH)/`if.c f1.c >$@@
16606 g.c: if.c g1.c
16607         cat `test -f 'if.c' || echo $(VPATH)/`if.c g1.c >$@@
16608 h.c: if.c h1.c
16609         cat `test -f "if.c" || echo $(VPATH)/`if.c h1.c >$@@
16610 @end smallexample
16612 Things get worse when your prerequisites are in a macro.
16614 @example
16615 VPATH = ../pkg/src
16616 HEADERS = f.h g.h h.h
16617 install-HEADERS: $(HEADERS)
16618         for i in $(HEADERS); do \
16619           $(INSTALL) -m 644 \
16620             `test -f $$i || echo $(VPATH)/`$$i \
16621             $(DESTDIR)$(includedir)/$$i; \
16622         done
16623 @end example
16625 The above @code{install-HEADERS} rule is not Solaris-proof because @code{for
16626 i in $(HEADERS);} is expanded to @code{for i in f.h g.h h.h;}
16627 where @code{f.h} and @code{g.h} are plain words and are hence
16628 subject to @code{VPATH} adjustments.
16630 If the three files are in @file{../pkg/src}, the rule is run as:
16632 @example
16633 for i in ../pkg/src/f.h ../pkg/src/g.h h.h; do \
16634   install -m 644 \
16635      `test -f $i || echo ../pkg/src/`$i \
16636      /usr/local/include/$i; \
16637 done
16638 @end example
16640 where the two first @command{install} calls fail.  For instance,
16641 consider the @code{f.h} installation:
16643 @example
16644 install -m 644 \
16645   `test -f ../pkg/src/f.h || \
16646     echo ../pkg/src/ \
16647   `../pkg/src/f.h \
16648   /usr/local/include/../pkg/src/f.h;
16649 @end example
16651 @noindent
16652 It reduces to:
16654 @example
16655 install -m 644 \
16656   ../pkg/src/f.h \
16657   /usr/local/include/../pkg/src/f.h;
16658 @end example
16660 Note that the manual @code{VPATH} search did not cause any problems here;
16661 however this command installs @file{f.h} in an incorrect directory.
16663 Trying to quote @code{$(HEADERS)} in some way, as we did for
16664 @code{foo.c} a few makefiles ago, does not help:
16666 @example
16667 install-HEADERS: $(HEADERS)
16668         headers='$(HEADERS)'; \
16669         for i in $$headers; do \
16670           $(INSTALL) -m 644 \
16671             `test -f $$i || echo $(VPATH)/`$$i \
16672             $(DESTDIR)$(includedir)/$$i; \
16673         done
16674 @end example
16676 Now, @code{headers='$(HEADERS)'} macro-expands to:
16678 @example
16679 headers='f.h g.h h.h'
16680 @end example
16682 @noindent
16683 but @code{g.h} is still a plain word.  (As an aside, the idiom
16684 @code{headers='$(HEADERS)'; for i in $$headers;} is a good
16685 idea if @code{$(HEADERS)} can be empty, because some shells diagnose a
16686 syntax error on @code{for i in;}.)
16688 One workaround is to strip this unwanted @file{../pkg/src/} prefix manually:
16690 @example
16691 VPATH = ../pkg/src
16692 HEADERS = f.h g.h h.h
16693 install-HEADERS: $(HEADERS)
16694         headers='$(HEADERS)'; \
16695         for i in $$headers; do \
16696           i=`expr "$$i" : '$(VPATH)/\(.*\)'`;
16697           $(INSTALL) -m 644 \
16698             `test -f $$i || echo $(VPATH)/`$$i \
16699             $(DESTDIR)$(includedir)/$$i; \
16700         done
16701 @end example
16703 Automake does something similar.  However the above hack works only if
16704 the files listed in @code{HEADERS} are in the current directory or a
16705 subdirectory; they should not be in an enclosing directory.  If we had
16706 @code{HEADERS = ../f.h}, the above fragment would fail in a VPATH
16707 build with Tru64 @command{make}.  The reason is that not only does
16708 Tru64 @command{make} rewrite dependencies, but it also simplifies
16709 them.  Hence @code{../f.h} becomes @code{../pkg/f.h} instead of
16710 @code{../pkg/src/../f.h}.  This obviously defeats any attempt to strip
16711 a leading @file{../pkg/src/} component.
16713 The following example makes the behavior of Tru64 @command{make}
16714 more apparent.
16716 @example
16717 $ @kbd{cat Makefile}
16718 VPATH = sub
16719 all: ../foo
16720         echo ../foo
16721 $ @kbd{ls}
16722 Makefile foo
16723 $ @kbd{make}
16724 echo foo
16726 @end example
16728 @noindent
16729 Dependency @file{../foo} was found in @file{sub/../foo}, but Tru64
16730 @command{make} simplified it as @file{foo}.  (Note that the @file{sub/}
16731 directory does not even exist, this just means that the simplification
16732 occurred before the file was checked for.)
16734 For the record here is how SunOS 4 @command{make} behaves on this
16735 example.
16737 @smallexample
16738 $ @kbd{make}
16739 make: Fatal error: Don't know how to make target `../foo'
16740 $ @kbd{mkdir sub}
16741 $ @kbd{make}
16742 echo sub/../foo
16743 sub/../foo
16744 @end smallexample
16747 @node Tru64 Directory Magic
16748 @subsection Tru64 @command{make} Creates Prerequisite Directories Magically
16749 @cindex @code{VPATH} and prerequisite directories
16750 @cindex prerequisite directories and @code{VPATH}
16752 When a prerequisite is a subdirectory of @code{VPATH}, Tru64
16753 @command{make} creates it in the current directory.
16755 @example
16756 $ @kbd{mkdir -p foo/bar build}
16757 $ @kbd{cd build}
16758 $ @kbd{cat >Makefile <<END
16759 VPATH = ..
16760 all: foo/bar
16761 END}
16762 $ @kbd{make}
16763 mkdir foo
16764 mkdir foo/bar
16765 @end example
16767 This can yield unexpected results if a rule uses a manual @code{VPATH}
16768 search as presented before.
16770 @example
16771 VPATH = ..
16772 all : foo/bar
16773         command `test -d foo/bar || echo ../`foo/bar
16774 @end example
16776 The above @command{command} is run on the empty @file{foo/bar}
16777 directory that was created in the current directory.
16779 @node Make Target Lookup
16780 @subsection Make Target Lookup
16781 @cindex @code{VPATH}, resolving target pathnames
16783 @acronym{GNU} @command{make} uses a complex algorithm to decide when it
16784 should use files found via a @code{VPATH} search.  @xref{Search
16785 Algorithm, , How Directory Searches are Performed, make, The @acronym{GNU} Make
16786 Manual}.
16788 If a target needs to be rebuilt, @acronym{GNU} @command{make} discards the
16789 file name found during the @code{VPATH} search for this target, and
16790 builds the file locally using the file name given in the makefile.
16791 If a target does not need to be rebuilt, @acronym{GNU} @command{make} uses the
16792 file name found during the @code{VPATH} search.
16794 Other @command{make} implementations, like Net@acronym{BSD} @command{make}, are
16795 easier to describe: the file name found during the @code{VPATH} search
16796 is used whether the target needs to be rebuilt or not.  Therefore
16797 new files are created locally, but existing files are updated at their
16798 @code{VPATH} location.
16800 Open@acronym{BSD} and Free@acronym{BSD} @command{make}, however,
16801 never perform a
16802 @code{VPATH} search for a dependency that has an explicit rule.
16803 This is extremely annoying.
16805 When attempting a @code{VPATH} build for an autoconfiscated package
16806 (e.g., @code{mkdir build && cd build && ../configure}), this means
16807 @acronym{GNU}
16808 @command{make} builds everything locally in the @file{build}
16809 directory, while @acronym{BSD} @command{make} builds new files locally and
16810 updates existing files in the source directory.
16812 @example
16813 $ @kbd{cat Makefile}
16814 VPATH = ..
16815 all: foo.x bar.x
16816 foo.x bar.x: newer.x
16817         @@echo Building $@@
16818 $ @kbd{touch ../bar.x}
16819 $ @kbd{touch ../newer.x}
16820 $ @kbd{make}        # GNU make
16821 Building foo.x
16822 Building bar.x
16823 $ @kbd{pmake}       # NetBSD make
16824 Building foo.x
16825 Building ../bar.x
16826 $ @kbd{fmake}       # FreeBSD make, OpenBSD make
16827 Building foo.x
16828 Building bar.x
16829 $ @kbd{tmake}       # Tru64 make
16830 Building foo.x
16831 Building bar.x
16832 $ @kbd{touch ../bar.x}
16833 $ @kbd{make}        # GNU make
16834 Building foo.x
16835 $ @kbd{pmake}       # NetBSD make
16836 Building foo.x
16837 $ @kbd{fmake}       # FreeBSD make, OpenBSD make
16838 Building foo.x
16839 Building bar.x
16840 $ @kbd{tmake}       # Tru64 make
16841 Building foo.x
16842 Building bar.x
16843 @end example
16845 Note how Net@acronym{BSD} @command{make} updates @file{../bar.x} in its
16846 VPATH location, and how Free@acronym{BSD}, Open@acronym{BSD}, and Tru64
16847 @command{make} always
16848 update @file{bar.x}, even when @file{../bar.x} is up to date.
16850 Another point worth mentioning is that once @acronym{GNU} @command{make} has
16851 decided to ignore a @code{VPATH} file name (e.g., it ignored
16852 @file{../bar.x} in the above example) it continues to ignore it when
16853 the target occurs as a prerequisite of another rule.
16855 The following example shows that @acronym{GNU} @command{make} does not look up
16856 @file{bar.x} in @code{VPATH} before performing the @code{.x.y} rule,
16857 because it ignored the @code{VPATH} result of @file{bar.x} while running
16858 the @code{bar.x: newer.x} rule.
16860 @example
16861 $ @kbd{cat Makefile}
16862 VPATH = ..
16863 all: bar.y
16864 bar.x: newer.x
16865         @@echo Building $@@
16866 .SUFFIXES: .x .y
16867 .x.y:
16868         cp $< $@@
16869 $ @kbd{touch ../bar.x}
16870 $ @kbd{touch ../newer.x}
16871 $ @kbd{make}        # GNU make
16872 Building bar.x
16873 cp bar.x bar.y
16874 cp: cannot stat `bar.x': No such file or directory
16875 make: *** [bar.y] Error 1
16876 $ @kbd{pmake}       # NetBSD make
16877 Building ../bar.x
16878 cp ../bar.x bar.y
16879 $ @kbd{rm bar.y}
16880 $ @kbd{fmake}       # FreeBSD make, OpenBSD make
16881 echo Building bar.x
16882 cp bar.x bar.y
16883 cp: cannot stat `bar.x': No such file or directory
16884 *** Error code 1
16885 $ @kbd{tmake}       # Tru64 make
16886 Building bar.x
16887 cp: bar.x: No such file or directory
16888 *** Exit 1
16889 @end example
16891 Note that if you drop away the command from the @code{bar.x: newer.x}
16892 rule, @acronym{GNU} @command{make} magically starts to work: it
16893 knows that @code{bar.x} hasn't been updated, therefore it doesn't
16894 discard the result from @code{VPATH} (@file{../bar.x}) in succeeding
16895 uses.  Tru64 also works, but Free@acronym{BSD} and Open@acronym{BSD}
16896 still don't.
16898 @example
16899 $ @kbd{cat Makefile}
16900 VPATH = ..
16901 all: bar.y
16902 bar.x: newer.x
16903 .SUFFIXES: .x .y
16904 .x.y:
16905         cp $< $@@
16906 $ @kbd{touch ../bar.x}
16907 $ @kbd{touch ../newer.x}
16908 $ @kbd{make}        # GNU make
16909 cp ../bar.x bar.y
16910 $ @kbd{rm bar.y}
16911 $ @kbd{pmake}       # NetBSD make
16912 cp ../bar.x bar.y
16913 $ @kbd{rm bar.y}
16914 $ @kbd{fmake}       # FreeBSD make, OpenBSD make
16915 cp bar.x bar.y
16916 cp: cannot stat `bar.x': No such file or directory
16917 *** Error code 1
16918 $ @kbd{tmake}       # Tru64 make
16919 cp ../bar.x bar.y
16920 @end example
16922 It seems the sole solution that would please every @command{make}
16923 implementation is to never rely on @code{VPATH} searches for targets.
16924 In other words, @code{VPATH} should be reserved to unbuilt sources.
16927 @node Single Suffix Rules
16928 @section Single Suffix Rules and Separated Dependencies
16929 @cindex Single Suffix Inference Rule
16930 @cindex Rule, Single Suffix Inference
16931 A @dfn{Single Suffix Rule} is basically a usual suffix (inference) rule
16932 (@samp{.from.to:}), but which @emph{destination} suffix is empty
16933 (@samp{.from:}).
16935 @cindex Separated Dependencies
16936 @dfn{Separated dependencies} simply refers to listing the prerequisite
16937 of a target, without defining a rule.  Usually one can list on the one
16938 hand side, the rules, and on the other hand side, the dependencies.
16940 Solaris @command{make} does not support separated dependencies for
16941 targets defined by single suffix rules:
16943 @example
16944 $ @kbd{cat Makefile}
16945 .SUFFIXES: .in
16946 foo: foo.in
16947 .in:
16948         cp $< $@@
16949 $ @kbd{touch foo.in}
16950 $ @kbd{make}
16951 $ @kbd{ls}
16952 Makefile  foo.in
16953 @end example
16955 @noindent
16956 while @acronym{GNU} Make does:
16958 @example
16959 $ @kbd{gmake}
16960 cp foo.in foo
16961 $ @kbd{ls}
16962 Makefile  foo       foo.in
16963 @end example
16965 Note it works without the @samp{foo: foo.in} dependency.
16967 @example
16968 $ @kbd{cat Makefile}
16969 .SUFFIXES: .in
16970 .in:
16971         cp $< $@@
16972 $ @kbd{make foo}
16973 cp foo.in foo
16974 @end example
16976 @noindent
16977 and it works with double suffix inference rules:
16979 @example
16980 $ @kbd{cat Makefile}
16981 foo.out: foo.in
16982 .SUFFIXES: .in .out
16983 .in.out:
16984         cp $< $@@
16985 $ @kbd{make}
16986 cp foo.in foo.out
16987 @end example
16989 As a result, in such a case, you have to write target rules.
16991 @node Timestamps and Make
16992 @section Timestamp Resolution and Make
16993 @cindex timestamp resolution
16994 Traditionally, file timestamps had 1-second resolution, and
16995 @command{make} used those timestamps to determine whether one file was
16996 newer than the other.  However, many modern file systems have
16997 timestamps with 1-nanosecond resolution.  Some @command{make}
16998 implementations look at the entire timestamp; others ignore the
16999 fractional part, which can lead to incorrect results.  Normally this
17000 is not a problem, but in some extreme cases you may need to use tricks
17001 like @samp{sleep 1} to work around timestamp truncation bugs.
17003 Commands like @samp{cp -p} and @samp{touch -r} typically do not copy
17004 file timestamps to their full resolutions (@pxref{Limitations of Usual
17005 Tools}).  Hence you should be wary of rules like this:
17007 @example
17008 dest: src
17009         cp -p src dest
17010 @end example
17012 as @file{dest} often appears to be older than @file{src} after the
17013 timestamp is truncated, and this can cause @command{make} to do
17014 needless rework the next time it is invoked.  To work around this
17015 problem, you can use a timestamp file, e.g.:
17017 @example
17018 dest-stamp: src
17019         cp -p src dest
17020         date >dest-stamp
17021 @end example
17026 @c ======================================== Portable C and C++ Programming
17028 @node Portable C and C++
17029 @chapter Portable C and C++ Programming
17030 @cindex Portable C and C++ programming
17032 C and C++ programs often use low-level features of the underlying
17033 system, and therefore are often more difficult to make portable to other
17034 platforms.
17036 Several standards have been developed to help make your programs more
17037 portable.  If you write programs with these standards in mind, you can
17038 have greater confidence that your programs work on a wide variety
17039 of systems.  @xref{Standards, , Language Standards Supported by
17040 @acronym{GCC}, gcc, Using the @acronym{GNU} Compiler Collection
17041 (@acronym{GCC})}, for a list of C-related
17042 standards.  Many programs also assume the
17043 @uref{http://www.opengroup.org/susv3, Posix standard}.
17045 Some old code is written to be portable to K&R C, which predates any C
17046 standard.  K&R C compilers are no longer of practical interest, though,
17047 and the rest of section assumes at least C89, the first C standard.
17049 Program portability is a huge topic, and this section can only briefly
17050 introduce common pitfalls.  @xref{System Portability, , Portability
17051 between System Types, standards, @acronym{GNU} Coding Standards}, for
17052 more information.
17054 @menu
17055 * Varieties of Unportability::  How to make your programs unportable
17056 * Integer Overflow::            When integers get too large
17057 * Preprocessor Arithmetic::     @code{#if} expression problems
17058 * Null Pointers::               Properties of null pointers
17059 * Buffer Overruns::             Subscript errors and the like
17060 * Volatile Objects::            @code{volatile} and signals
17061 * Floating Point Portability::  Portable floating-point arithmetic
17062 * Exiting Portably::            Exiting and the exit status
17063 @end menu
17065 @node Varieties of Unportability
17066 @section Varieties of Unportability
17067 @cindex portability
17069 Autoconf tests and ordinary programs often need to test what is allowed
17070 on a system, and therefore they may need to deliberately exceed the
17071 boundaries of what the standards allow, if only to see whether an
17072 optional feature is present.  When you write such a program, you should
17073 keep in mind the difference between constraints, unspecified behavior,
17074 and undefined behavior.
17076 In C, a @dfn{constraint} is a rule that the compiler must enforce.  An
17077 example constraint is that C programs must not declare a bit-field with
17078 negative width.  Tests can therefore reliably assume that programs with
17079 negative-width bit-fields are rejected by a compiler that conforms
17080 to the standard.
17082 @dfn{Unspecified behavior} is valid behavior, where the standard allows
17083 multiple possibilities.  For example, the order of evaluation of
17084 function arguments is unspecified.  Some unspecified behavior is
17085 @dfn{implementation-defined}, i.e., documented by the implementation,
17086 but since Autoconf tests cannot read the documentation they cannot
17087 distinguish between implementation-defined and other unspecified
17088 behavior.  It is common for Autoconf tests to probe implementations to
17089 determine otherwise-unspecified behavior.
17091 @dfn{Undefined behavior} is invalid behavior, where the standard allows
17092 the implementation to do anything it pleases.  For example,
17093 dereferencing a null pointer leads to undefined behavior.  If possible,
17094 test programs should avoid undefined behavior, since a program with
17095 undefined behavior might succeed on a test that should fail.
17097 The above rules apply to programs that are intended to conform to the
17098 standard.  However, strictly-conforming programs are quite rare, since
17099 the standards are so limiting.  A major goal of Autoconf is to support
17100 programs that use implementation features not described by the standard,
17101 and it is fairly common for test programs to violate the above rules, if
17102 the programs work well enough in practice.
17104 @node Integer Overflow
17105 @section Integer Overflow
17106 @cindex integer overflow
17107 @cindex overflow, signed integer
17108 @cindex signed integer overflow
17109 @cindex wraparound arithmetic
17111 In practice many portable C programs assume that signed integer overflow wraps
17112 around reliably using two's complement arithmetic.  Yet the C standard
17113 says that program behavior is undefined on overflow, and in a few cases
17114 C programs do not work on some modern implementations because their
17115 overflows do not wrap around as their authors expected.  Conversely, in
17116 signed integer remainder, the C standard requires overflow
17117 behavior that is commonly not implemented.
17119 @menu
17120 * Integer Overflow Basics::      Why integer overflow is a problem
17121 * Signed Overflow Examples::     Examples of code assuming wraparound
17122 * Optimization and Wraparound::  Optimizations that break uses of wraparound
17123 * Signed Overflow Advice::       Practical advice for signed overflow issues
17124 * Signed Integer Division::      @code{INT_MIN / -1} and @code{INT_MIN % -1}
17125 @end menu
17127 @node Integer Overflow Basics
17128 @subsection Basics of Integer Overflow
17129 @cindex integer overflow
17130 @cindex overflow, signed integer
17131 @cindex signed integer overflow
17132 @cindex wraparound arithmetic
17134 In languages like C, unsigned integer overflow reliably wraps around;
17135 e.g., @code{UINT_MAX + 1} yields zero.
17136 This is guaranteed by the C standard and is
17137 portable in practice, unless you specify aggressive,
17138 nonstandard optimization options
17139 suitable only for special applications.
17141 In contrast, the C standard says that signed integer overflow leads to
17142 undefined behavior where a program can do anything, including dumping
17143 core or overrunning a buffer.  The misbehavior can even precede the
17144 overflow.  Such an overflow can occur during addition, subtraction,
17145 multiplication, division, and left shift.
17147 Despite this requirement of the standard, many C programs and Autoconf
17148 tests assume that signed integer overflow silently wraps around modulo a
17149 power of two, using two's complement arithmetic, so long as you cast the
17150 resulting value to a signed integer type or store it into a signed
17151 integer variable.  If you use conservative optimization flags, such
17152 programs are generally portable to the vast majority of modern
17153 platforms, with a few exceptions discussed later.
17155 For historical reasons the C standard also allows implementations with
17156 ones' complement or signed magnitude arithmetic, but it is safe to
17157 assume two's complement nowadays.
17159 Also, overflow can occur when converting an out-of-range value to a
17160 signed integer type.  Here a standard implementation must define what
17161 happens, but this might include raising an exception.  In practice all
17162 known implementations support silent wraparound in this case, so you need
17163 not worry about other possibilities.
17165 @node Signed Overflow Examples
17166 @subsection Examples of Code Assuming Wraparound Overflow
17167 @cindex integer overflow
17168 @cindex overflow, signed integer
17169 @cindex signed integer overflow
17170 @cindex wraparound arithmetic
17172 There has long been a tension between what the C standard requires for
17173 signed integer overflow, and what C programs commonly assume.  The
17174 standard allows aggressive optimizations based on assumptions that
17175 overflow never occurs, but many practical C programs rely on overflow
17176 wrapping around.  These programs do not conform to the standard, but
17177 they commonly work in practice because compiler writers are
17178 understandably reluctant to implement optimizations that would break
17179 many programs, unless perhaps a user specifies aggressive optimization.
17181 The C Standard says that if a program has signed integer overflow its
17182 behavior is undefined, and the undefined behavior can even precede the
17183 overflow.  To take an extreme example:
17185 @c Inspired by Robert Dewar's example in
17186 @c <http://gcc.gnu.org/ml/gcc/2007-01/msg00038.html> (2007-01-01).
17187 @example
17188 if (password == expected_password)
17189   allow_superuser_privileges ();
17190 else if (counter++ == INT_MAX)
17191   abort ();
17192 else
17193   printf ("%d password mismatches\n", counter);
17194 @end example
17196 @noindent
17197 If the @code{int} variable @code{counter} equals @code{INT_MAX},
17198 @code{counter++} must overflow and the behavior is undefined, so the C
17199 standard allows the compiler to optimize away the test against
17200 @code{INT_MAX} and the @code{abort} call.
17201 Worse, if an earlier bug in the program lets the compiler deduce that
17202 @code{counter == INT_MAX} or that @code{counter} previously overflowed,
17203 the C standard allows the compiler to optimize away the password test
17204 and generate code that allows superuser privileges unconditionally.
17206 Despite this requirement by the standard, it has long been common for C
17207 code to assume wraparound arithmetic after signed overflow, and all
17208 known practical C implementations support some C idioms that assume
17209 wraparound signed arithmetic, even if the idioms do not conform
17210 strictly to the standard.  If your code looks like the following
17211 examples it will almost surely work with real-world compilers.
17213 Here is an example derived from the 7th Edition Unix implementation of
17214 @code{atoi} (1979-01-10):
17216 @example
17217 char *p;
17218 int f, n;
17219 @dots{}
17220 while (*p >= '0' && *p <= '9')
17221   n = n * 10 + *p++ - '0';
17222 return (f ? -n : n);
17223 @end example
17225 @noindent
17226 Even if the input string is in range, on most modern machines this has
17227 signed overflow when computing the most negative integer (the @code{-n}
17228 overflows) or a value near an extreme integer (the first @code{+}
17229 overflows).
17231 Here is another example, derived from the 7th Edition implementation of
17232 @code{rand} (1979-01-10).  Here the programmer expects both
17233 multiplication and addition to wrap on overflow:
17235 @example
17236 static long int randx = 1;
17237 @dots{}
17238 randx = randx * 1103515245 + 12345;
17239 return (randx >> 16) & 077777;
17240 @end example
17242 In the following example, derived from the @acronym{GNU} C Library 2.5
17243 implementation of @code{mktime} (2006-09-09), the code assumes
17244 wraparound arithmetic in @code{+} to detect signed overflow:
17246 @example
17247 time_t t, t1, t2;
17248 int sec_requested, sec_adjustment;
17249 @dots{}
17250 t1 = t + sec_requested;
17251 t2 = t1 + sec_adjustment;
17252 if (((t1 < t) != (sec_requested < 0))
17253     | ((t2 < t1) != (sec_adjustment < 0)))
17254   return -1;
17255 @end example
17257 If your code looks like these examples, it is probably safe even though
17258 it does not strictly conform to the C standard.  This might lead one to
17259 believe that one can generally assume wraparound on overflow, but that
17260 is not always true, as can be seen in the next section.
17262 @node Optimization and Wraparound
17263 @subsection Optimizations That Break Wraparound Arithmetic
17264 @cindex loop induction
17266 Compilers sometimes generate code that is incompatible with wraparound
17267 integer arithmetic.  A simple example is an algebraic simplification: a
17268 compiler might translate @code{(i * 2000) / 1000} to @code{i * 2}
17269 because it assumes that @code{i * 2000} does not overflow.  The
17270 translation is not equivalent to the original when overflow occurs:
17271 e.g., in the typical case of 32-bit signed two's complement wraparound
17272 @code{int}, if @code{i} has type @code{int} and value @code{1073742},
17273 the original expression returns @minus{}2147483 but the optimized
17274 version returns the mathematically correct value 2147484.
17276 More subtly, loop induction optimizations often exploit the undefined
17277 behavior of signed overflow.  Consider the following contrived function
17278 @code{sumc}:
17280 @example
17282 sumc (int lo, int hi)
17284   int sum = 0;
17285   int i;
17286   for (i = lo; i <= hi; i++)
17287     sum ^= i * 53;
17288   return sum;
17290 @end example
17292 @noindent
17293 To avoid multiplying by 53 each time through the loop, an optimizing
17294 compiler might internally transform @code{sumc} to the equivalent of the
17295 following:
17297 @example
17299 transformed_sumc (int lo, int hi)
17301   int sum = 0;
17302   int hic = hi * 53;
17303   int ic;
17304   for (ic = lo * 53; ic <= hic; ic += 53)
17305     sum ^= ic;
17306   return sum;
17308 @end example
17310 @noindent
17311 This transformation is allowed by the C standard, but it is invalid for
17312 wraparound arithmetic when @code{INT_MAX / 53 < hi}, because then the
17313 overflow in computing expressions like @code{hi * 53} can cause the
17314 expression @code{i <= hi} to yield a different value from the
17315 transformed expression @code{ic <= hic}.
17317 For this reason, compilers that use loop induction and similar
17318 techniques often do not support reliable wraparound arithmetic when a
17319 loop induction variable like @code{ic} is involved.  Since loop
17320 induction variables are generated by the compiler, and are not visible
17321 in the source code, it is not always trivial to say whether the problem
17322 affects your code.
17324 Hardly any code actually depends on wraparound arithmetic in cases like
17325 these, so in practice these loop induction optimizations are almost
17326 always useful.  However, edge cases in this area can cause problems.
17327 For example:
17329 @example
17330 int j;
17331 for (j = 1; 0 < j; j *= 2)
17332   test (j);
17333 @end example
17335 @noindent
17336 Here, the loop attempts to iterate through all powers of 2 that
17337 @code{int} can represent, but the C standard allows a compiler to
17338 optimize away the comparison and generate an infinite loop,
17339 under the argument that behavior is undefined on overflow.  As of this
17340 writing this optimization is not done by any production version of
17341 @acronym{GCC} with @option{-O2}, but it might be performed by other
17342 compilers, or by more aggressive @acronym{GCC} optimization options,
17343 and the @acronym{GCC} developers have not decided whether it will
17344 continue to work with @acronym{GCC} and @option{-O2}.
17346 @node Signed Overflow Advice
17347 @subsection Practical Advice for Signed Overflow Issues
17348 @cindex integer overflow
17349 @cindex overflow, signed integer
17350 @cindex signed integer overflow
17351 @cindex wraparound arithmetic
17353 Ideally the safest approach is to avoid signed integer overflow
17354 entirely.  For example, instead of multiplying two signed integers, you
17355 can convert them to unsigned integers, multiply the unsigned values,
17356 then test whether the result is in signed range.
17358 Rewriting code in this way will be inconvenient, though, particularly if
17359 the signed values might be negative.  Also, it may hurt
17360 performance.  Using unsigned arithmetic to check for overflow is
17361 particularly painful to do portably and efficiently when dealing with an
17362 integer type like @code{uid_t} whose width and signedness vary from
17363 platform to platform.
17365 Furthermore, many C applications pervasively assume wraparound behavior
17366 and typically it is not easy to find and remove all these assumptions.
17367 Hence it is often useful to maintain nonstandard code that assumes
17368 wraparound on overflow, instead of rewriting the code.  The rest of this
17369 section attempts to give practical advice for this situation.
17371 If your code wants to detect signed integer overflow in @code{sum = a +
17372 b}, it is generally safe to use an expression like @code{(sum < a) != (b
17373 < 0)}.
17375 If your code uses a signed loop index, make sure that the index cannot
17376 overflow, along with all signed expressions derived from the index.
17377 Here is a contrived example of problematic code with two instances of
17378 overflow.
17380 @example
17381 for (i = INT_MAX - 10; i <= INT_MAX; i++)
17382   if (i + 1 < 0)
17383     @{
17384       report_overflow ();
17385       break;
17386     @}
17387 @end example
17389 @noindent
17390 Because of the two overflows, a compiler might optimize away or
17391 transform the two comparisons in a way that is incompatible with the
17392 wraparound assumption.
17394 If your code uses an expression like @code{(i * 2000) / 1000} and you
17395 actually want the multiplication to wrap around on overflow, use
17396 unsigned arithmetic
17397 to do it, e.g., @code{((int) (i * 2000u)) / 1000}.
17399 If your code assumes wraparound behavior and you want to insulate it
17400 against any @acronym{GCC} optimizations that would fail to support that
17401 behavior, you should use @acronym{GCC}'s @option{-fwrapv} option, which
17402 causes signed overflow to wrap around reliably (except for division and
17403 remainder, as discussed in the next section).
17405 If you need to port to platforms where signed integer overflow does not
17406 reliably wrap around (e.g., due to hardware overflow checking, or to
17407 highly aggressive optimizations), you should consider debugging with
17408 @acronym{GCC}'s @option{-ftrapv} option, which causes signed overflow to
17409 raise an exception.
17411 @node Signed Integer Division
17412 @subsection Signed Integer Division and Integer Overflow
17413 @cindex division, integer
17415 Overflow in signed
17416 integer division is not always harmless: for example, on CPUs of the
17417 i386 family, dividing @code{INT_MIN} by @code{-1} yields a SIGFPE signal
17418 which by default terminates the program.  Worse, taking the remainder
17419 of these two values typically yields the same signal on these CPUs,
17420 even though the C standard requires @code{INT_MIN % -1} to yield zero
17421 because the expression does not overflow.
17423 @node Preprocessor Arithmetic
17424 @section Preprocessor Arithmetic
17425 @cindex preprocessor arithmetic
17427 In C99, preprocessor arithmetic, used for @code{#if} expressions, must
17428 be evaluated as if all signed values are of type @code{intmax_t} and all
17429 unsigned values of type @code{uintmax_t}.  Many compilers are buggy in
17430 this area, though.  For example, as of 2007, Sun C mishandles @code{#if
17431 LLONG_MIN < 0} on a platform with 32-bit @code{long int} and 64-bit
17432 @code{long long int}.  Also, some older preprocessors mishandle
17433 constants ending in @code{LL}.  To work around these problems, you can
17434 compute the value of expressions like @code{LONG_MAX < LLONG_MAX} at
17435 @code{configure}-time rather than at @code{#if}-time.
17437 @node Null Pointers
17438 @section Properties of Null Pointers
17439 @cindex null pointers
17441 Most modern hosts reliably fail when you attempt to dereference a null
17442 pointer.
17444 On almost all modern hosts, null pointers use an all-bits-zero internal
17445 representation, so you can reliably use @code{memset} with 0 to set all
17446 the pointers in an array to null values.
17448 If @code{p} is a null pointer to an object type, the C expression
17449 @code{p + 0} always evaluates to @code{p} on modern hosts, even though
17450 the standard says that it has undefined behavior.
17452 @node Buffer Overruns
17453 @section Buffer Overruns and Subscript Errors
17454 @cindex buffer overruns
17456 Buffer overruns and subscript errors are the most common dangerous
17457 errors in C programs.  They result in undefined behavior because storing
17458 outside an array typically modifies storage that is used by some other
17459 object, and most modern systems lack runtime checks to catch these
17460 errors.  Programs should not rely on buffer overruns being caught.
17462 There is one exception to the usual rule that a portable program cannot
17463 address outside an array.  In C, it is valid to compute the address just
17464 past an object, e.g., @code{&a[N]} where @code{a} has @code{N} elements,
17465 so long as you do not dereference the resulting pointer.  But it is not
17466 valid to compute the address just before an object, e.g., @code{&a[-1]};
17467 nor is it valid to compute two past the end, e.g., @code{&a[N+1]}.  On
17468 most platforms @code{&a[-1] < &a[0] && &a[N] < &a[N+1]}, but this is not
17469 reliable in general, and it is usually easy enough to avoid the
17470 potential portability problem, e.g., by allocating an extra unused array
17471 element at the start or end.
17473 @uref{http://valgrind.org/, Valgrind} can catch many overruns.
17474 @acronym{GCC}
17475 users might also consider using the @option{-fmudflap} option to catch
17476 overruns.
17478 Buffer overruns are usually caused by off-by-one errors, but there are
17479 more subtle ways to get them.
17481 Using @code{int} values to index into an array or compute array sizes
17482 causes problems on typical 64-bit hosts where an array index might
17483 be @math{2^31} or larger.  Index values of type @code{size_t} avoid this
17484 problem, but cannot be negative.  Index values of type @code{ptrdiff_t}
17485 are signed, and are wide enough in practice.
17487 If you add or multiply two numbers to calculate an array size, e.g.,
17488 @code{malloc (x * sizeof y + z)}, havoc ensues if the addition or
17489 multiplication overflows.
17491 Many implementations of the @code{alloca} function silently misbehave
17492 and can generate buffer overflows if given sizes that are too large.
17493 The size limits are implementation dependent, but are at least 4000
17494 bytes on all platforms that we know about.
17496 The standard functions @code{asctime}, @code{asctime_r}, @code{ctime},
17497 @code{ctime_r}, and @code{gets} are prone to buffer overflows, and
17498 portable code should not use them unless the inputs are known to be
17499 within certain limits.  The time-related functions can overflow their
17500 buffers if given timestamps out of range (e.g., a year less than -999
17501 or greater than 9999).  Time-related buffer overflows cannot happen with
17502 recent-enough versions of the @acronym{GNU} C library, but are possible
17503 with other
17504 implementations.  The @code{gets} function is the worst, since it almost
17505 invariably overflows its buffer when presented with an input line larger
17506 than the buffer.
17508 @node Volatile Objects
17509 @section Volatile Objects
17510 @cindex volatile objects
17512 The keyword @code{volatile} is often misunderstood in portable code.
17513 Its use inhibits some memory-access optimizations, but programmers often
17514 wish that it had a different meaning than it actually does.
17516 @code{volatile} was designed for code that accesses special objects like
17517 memory-mapped device registers whose contents spontaneously change.
17518 Such code is inherently low-level, and it is difficult to specify
17519 portably what @code{volatile} means in these cases.  The C standard
17520 says, ``What constitutes an access to an object that has
17521 volatile-qualified type is implementation-defined,'' so in theory each
17522 implementation is supposed to fill in the gap by documenting what
17523 @code{volatile} means for that implementation.  In practice, though,
17524 this documentation is usually absent or incomplete.
17526 One area of confusion is the distinction between objects defined with
17527 volatile types, and volatile lvalues.  From the C standard's point of
17528 view, an object defined with a volatile type has externally visible
17529 behavior.  You can think of such objects as having little oscilloscope
17530 probes attached to them, so that the user can observe some properties of
17531 accesses to them, just as the user can observe data written to output
17532 files.  However, the standard does not make it clear whether users can
17533 observe accesses by volatile lvalues to ordinary objects.  For example:
17535 @example
17536 /* Declare and access a volatile object.
17537    Accesses to X are "visible" to users.  */
17538 static int volatile x;
17539 x = 1;
17541 /* Access two ordinary objects via a volatile lvalue.
17542    It's not clear whether accesses to *P are "visible".  */
17543 int y;
17544 int *z = malloc (sizeof (int));
17545 int volatile *p;
17546 p = &y;
17547 *p = 1;
17548 p = z;
17549 *p = 1;
17550 @end example
17552 Programmers often wish that @code{volatile} meant ``Perform the memory
17553 access here and now, without merging several memory accesses, without
17554 changing the memory word size, and without reordering.''  But the C
17555 standard does not require this.  For objects defined with a volatile
17556 type, accesses must be done before the next sequence point; but
17557 otherwise merging, reordering, and word-size change is allowed.  Worse,
17558 it is not clear from the standard whether volatile lvalues provide more
17559 guarantees in general than nonvolatile lvalues, if the underlying
17560 objects are ordinary.
17562 Even when accessing objects defined with a volatile type,
17563 the C standard allows only
17564 extremely limited signal handlers: the behavior is undefined if a signal
17565 handler reads any nonlocal object, or writes to any nonlocal object
17566 whose type is not @code{sig_atomic_t volatile}, or calls any standard
17567 library function other than @code{abort}, @code{signal}, and (if C99)
17568 @code{_Exit}.  Hence C compilers need not worry about a signal handler
17569 disturbing ordinary computation, unless the computation accesses a
17570 @code{sig_atomic_t volatile} lvalue that is not a local variable.
17571 (There is an obscure exception for accesses via a pointer to a volatile
17572 character, since it may point into part of a @code{sig_atomic_t
17573 volatile} object.)  Posix
17574 adds to the list of library functions callable from a portable signal
17575 handler, but otherwise is like the C standard in this area.
17577 Some C implementations allow memory-access optimizations within each
17578 translation unit, such that actual behavior agrees with the behavior
17579 required by the standard only when calling a function in some other
17580 translation unit, and a signal handler acts like it was called from a
17581 different translation unit.  The C standard hints that in these
17582 implementations, objects referred to by signal handlers ``would require
17583 explicit specification of @code{volatile} storage, as well as other
17584 implementation-defined restrictions.''  But unfortunately even for this
17585 special case these other restrictions are often not documented well.
17586 @xref{Volatiles, , When is a Volatile Object Accessed?, gcc, Using the
17587 @acronym{GNU} Compiler Collection (@acronym{GCC})}, for some
17588 restrictions imposed by @acronym{GCC}.  @xref{Defining Handlers, ,
17589 Defining Signal Handlers, libc, The @acronym{GNU} C Library}, for some
17590 restrictions imposed by the @acronym{GNU} C library.  Restrictions
17591 differ on other platforms.
17593 If possible, it is best to use a signal handler that fits within the
17594 limits imposed by the C and Posix standards.
17596 If this is not practical, you can try the following rules of thumb.  A
17597 signal handler should access only volatile lvalues, preferably lvalues
17598 that refer to objects defined with a volatile type, and should not
17599 assume that the accessed objects have an internally consistent state
17600 if they are larger than a machine word.  Furthermore, installers
17601 should employ compilers and compiler options that are commonly used
17602 for building operating system kernels, because kernels often need more
17603 from @code{volatile} than the C Standard requires, and installers who
17604 compile an application in a similar environment can sometimes benefit
17605 from the extra constraints imposed by kernels on compilers.
17606 Admittedly we are handwaving somewhat here, as there are few
17607 guarantees in this area; the rules of thumb may help to fix some bugs
17608 but there is a good chance that they will not fix them all.
17610 For @code{volatile}, C++ has the same problems that C does.
17611 Multithreaded applications have even more problems with @code{volatile},
17612 but they are beyond the scope of this section.
17614 The bottom line is that using @code{volatile} typically hurts
17615 performance but should not hurt correctness.  In some cases its use
17616 does help correctness, but these cases are often so poorly understood
17617 that all too often adding @code{volatile} to a data structure merely
17618 alleviates some symptoms of a bug while not fixing the bug in general.
17620 @node Floating Point Portability
17621 @section Floating Point Portability
17622 @cindex floating point
17624 Almost all modern systems use IEEE-754 floating point, and it is safe to
17625 assume IEEE-754 in most portable code these days.  For more information,
17626 please see David Goldberg's classic paper
17627 @uref{http://www.validlab.com/goldberg/paper.pdf, What Every Computer
17628 Scientist Should Know About Floating-Point Arithmetic}.
17630 @node Exiting Portably
17631 @section Exiting Portably
17632 @cindex exiting portably
17634 A C or C++ program can exit with status @var{N} by returning
17635 @var{N} from the @code{main} function.  Portable programs are supposed
17636 to exit either with status 0 or @code{EXIT_SUCCESS} to succeed, or with
17637 status @code{EXIT_FAILURE} to fail, but in practice it is portable to
17638 fail by exiting with status 1, and test programs that assume Posix can
17639 fail by exiting with status values from 1 through 255.  Programs on
17640 SunOS 2.0 (1985) through 3.5.2 (1988) incorrectly exited with zero
17641 status when @code{main} returned nonzero, but ancient systems like these
17642 are no longer of practical concern.
17644 A program can also exit with status @var{N} by passing @var{N} to the
17645 @code{exit} function, and a program can fail by calling the @code{abort}
17646 function.  If a program is specialized to just some platforms, it can fail
17647 by calling functions specific to those platforms, e.g., @code{_exit}
17648 (Posix) and @code{_Exit} (C99).  However, like other functions, an exit
17649 function should be declared, typically by including a header.  For
17650 example, if a C program calls @code{exit}, it should include @file{stdlib.h}
17651 either directly or via the default includes (@pxref{Default Includes}).
17653 A program can fail due to undefined behavior such as dereferencing a null
17654 pointer, but this is not recommended as undefined behavior allows an
17655 implementation to do whatever it pleases and this includes exiting
17656 successfully.
17659 @c ================================================== Manual Configuration
17661 @node Manual Configuration
17662 @chapter Manual Configuration
17664 A few kinds of features can't be guessed automatically by running test
17665 programs.  For example, the details of the object-file format, or
17666 special options that need to be passed to the compiler or linker.  You
17667 can check for such features using ad-hoc means, such as having
17668 @command{configure} check the output of the @code{uname} program, or
17669 looking for libraries that are unique to particular systems.  However,
17670 Autoconf provides a uniform method for handling unguessable features.
17672 @menu
17673 * Specifying Names::            Specifying the system type
17674 * Canonicalizing::              Getting the canonical system type
17675 * Using System Type::           What to do with the system type
17676 @end menu
17678 @node Specifying Names
17679 @section Specifying the System Type
17680 @cindex System type
17682 Autoconf-generated
17683 @command{configure} scripts can make decisions based on a canonical name
17684 for the system type, which has the form:
17685 @samp{@var{cpu}-@var{vendor}-@var{os}}, where @var{os} can be
17686 @samp{@var{system}} or @samp{@var{kernel}-@var{system}}
17688 @command{configure} can usually guess the canonical name for the type of
17689 system it's running on.  To do so it runs a script called
17690 @command{config.guess}, which infers the name using the @code{uname}
17691 command or symbols predefined by the C preprocessor.
17693 Alternately, the user can specify the system type with command line
17694 arguments to @command{configure}.  Doing so is necessary when
17695 cross-compiling.  In the most complex case of cross-compiling, three
17696 system types are involved.  The options to specify them are:
17698 @table @option
17699 @item --build=@var{build-type}
17700 the type of system on which the package is being configured and
17701 compiled.  It defaults to the result of running @command{config.guess}.
17703 @item --host=@var{host-type}
17704 the type of system on which the package runs.  By default it is the
17705 same as the build machine.  Specifying it enables the cross-compilation
17706 mode.
17708 @item --target=@var{target-type}
17709 the type of system for which any compiler tools in the package
17710 produce code (rarely needed).  By default, it is the same as host.
17711 @end table
17713 If you mean to override the result of @command{config.guess}, use
17714 @option{--build}, not @option{--host}, since the latter enables
17715 cross-compilation.  For historical reasons,
17716 whenever you specify @option{--host},
17717 be sure to specify @option{--build} too; this will be fixed in the
17718 future.  So, to enter cross-compilation mode, use a command like this
17720 @example
17721 ./configure --build=i686-pc-linux-gnu --host=m68k-coff
17722 @end example
17724 @noindent
17725 Note that if you do not specify @option{--host}, @command{configure}
17726 fails if it can't run the code generated by the specified compiler.  For
17727 example, configuring as follows fails:
17729 @example
17730 ./configure CC=m68k-coff-gcc
17731 @end example
17733 In the future, when cross-compiling Autoconf will @emph{not}
17734 accept tools (compilers, linkers, assemblers) whose name is not
17735 prefixed with the host type.  The only case when this may be
17736 useful is when you really are not cross-compiling, but only
17737 building for a least-common-denominator architecture: an example
17738 is building for @code{i386-pc-linux-gnu} while running on an
17739 @code{i686-pc-linux-gnu} architecture.  In this case, some particular
17740 pairs might be similar enough to let you get away with the system
17741 compilers, but in general the compiler might make bogus assumptions
17742 on the host: if you know what you are doing, please create symbolic
17743 links from the host compiler to the build compiler.
17745 @cindex @command{config.sub}
17746 @command{configure} recognizes short aliases for many system types; for
17747 example, @samp{decstation} can be used instead of
17748 @samp{mips-dec-ultrix4.2}.  @command{configure} runs a script called
17749 @command{config.sub} to canonicalize system type aliases.
17751 This section deliberately omits the description of the obsolete
17752 interface; see @ref{Hosts and Cross-Compilation}.
17755 @node Canonicalizing
17756 @section Getting the Canonical System Type
17757 @cindex System type
17758 @cindex Canonical system type
17760 The following macros make the system type available to @command{configure}
17761 scripts.
17763 @ovindex build_alias
17764 @ovindex host_alias
17765 @ovindex target_alias
17767 The variables @samp{build_alias}, @samp{host_alias}, and
17768 @samp{target_alias} are always exactly the arguments of @option{--build},
17769 @option{--host}, and @option{--target}; in particular, they are left empty
17770 if the user did not use them, even if the corresponding
17771 @code{AC_CANONICAL} macro was run.  Any configure script may use these
17772 variables anywhere.  These are the variables that should be used when in
17773 interaction with the user.
17775 If you need to recognize some special environments based on their system
17776 type, run the following macros to get canonical system names.  These
17777 variables are not set before the macro call.
17779 If you use these macros, you must distribute @command{config.guess} and
17780 @command{config.sub} along with your source code.  @xref{Output}, for
17781 information about the @code{AC_CONFIG_AUX_DIR} macro which you can use
17782 to control in which directory @command{configure} looks for those scripts.
17785 @defmac AC_CANONICAL_BUILD
17786 @acindex{CANONICAL_BUILD}
17787 @ovindex build
17788 @ovindex build_cpu
17789 @ovindex build_vendor
17790 @ovindex build_os
17791 Compute the canonical build-system type variable, @code{build}, and its
17792 three individual parts @code{build_cpu}, @code{build_vendor}, and
17793 @code{build_os}.
17795 If @option{--build} was specified, then @code{build} is the
17796 canonicalization of @code{build_alias} by @command{config.sub},
17797 otherwise it is determined by the shell script @command{config.guess}.
17798 @end defmac
17800 @defmac AC_CANONICAL_HOST
17801 @acindex{CANONICAL_HOST}
17802 @ovindex host
17803 @ovindex host_cpu
17804 @ovindex host_vendor
17805 @ovindex host_os
17806 Compute the canonical host-system type variable, @code{host}, and its
17807 three individual parts @code{host_cpu}, @code{host_vendor}, and
17808 @code{host_os}.
17810 If @option{--host} was specified, then @code{host} is the
17811 canonicalization of @code{host_alias} by @command{config.sub},
17812 otherwise it defaults to @code{build}.
17813 @end defmac
17815 @defmac AC_CANONICAL_TARGET
17816 @acindex{CANONICAL_TARGET}
17817 @ovindex target
17818 @ovindex target_cpu
17819 @ovindex target_vendor
17820 @ovindex target_os
17821 Compute the canonical target-system type variable, @code{target}, and its
17822 three individual parts @code{target_cpu}, @code{target_vendor}, and
17823 @code{target_os}.
17825 If @option{--target} was specified, then @code{target} is the
17826 canonicalization of @code{target_alias} by @command{config.sub},
17827 otherwise it defaults to @code{host}.
17828 @end defmac
17830 Note that there can be artifacts due to the backward compatibility
17831 code.  See @xref{Hosts and Cross-Compilation}, for more.
17833 @node Using System Type
17834 @section Using the System Type
17836 In @file{configure.ac} the system type is generally used by one or more
17837 @code{case} statements to select system-specifics.  Shell wildcards can
17838 be used to match a group of system types.
17840 For example, an extra assembler code object file could be chosen, giving
17841 access to a CPU cycle counter register.  @code{$(CYCLE_OBJ)} in the
17842 following would be used in a makefile to add the object to a
17843 program or library.
17845 @example
17846 case $host in
17847   alpha*-*-*) CYCLE_OBJ=rpcc.o ;;
17848   i?86-*-*)   CYCLE_OBJ=rdtsc.o ;;
17849   *)          CYCLE_OBJ= ;;
17850 esac
17851 AC_SUBST([CYCLE_OBJ])
17852 @end example
17854 @code{AC_CONFIG_LINKS} (@pxref{Configuration Links}) is another good way
17855 to select variant source files, for example optimized code for some
17856 CPUs.  The configured CPU type doesn't always indicate exact CPU types,
17857 so some runtime capability checks may be necessary too.
17859 @example
17860 case $host in
17861   alpha*-*-*)   AC_CONFIG_LINKS([dither.c:alpha/dither.c]) ;;
17862   powerpc*-*-*) AC_CONFIG_LINKS([dither.c:powerpc/dither.c]) ;;
17863   *-*-*)        AC_CONFIG_LINKS([dither.c:generic/dither.c]) ;;
17864 esac
17865 @end example
17867 The host system type can also be used to find cross-compilation tools
17868 with @code{AC_CHECK_TOOL} (@pxref{Generic Programs}).
17870 The above examples all show @samp{$host}, since this is where the code
17871 is going to run.  Only rarely is it necessary to test @samp{$build}
17872 (which is where the build is being done).
17874 Whenever you're tempted to use @samp{$host} it's worth considering
17875 whether some sort of probe would be better.  New system types come along
17876 periodically or previously missing features are added.  Well-written
17877 probes can adapt themselves to such things, but hard-coded lists of
17878 names can't.  Here are some guidelines,
17880 @itemize @bullet
17881 @item
17882 Availability of libraries and library functions should always be checked
17883 by probing.
17884 @item
17885 Variant behavior of system calls is best identified with runtime tests
17886 if possible, but bug workarounds or obscure difficulties might have to
17887 be driven from @samp{$host}.
17888 @item
17889 Assembler code is inevitably highly CPU-specific and is best selected
17890 according to @samp{$host_cpu}.
17891 @item
17892 Assembler variations like underscore prefix on globals or ELF versus
17893 COFF type directives are however best determined by probing, perhaps
17894 even examining the compiler output.
17895 @end itemize
17897 @samp{$target} is for use by a package creating a compiler or similar.
17898 For ordinary packages it's meaningless and should not be used.  It
17899 indicates what the created compiler should generate code for, if it can
17900 cross-compile.  @samp{$target} generally selects various hard-coded CPU
17901 and system conventions, since usually the compiler or tools under
17902 construction themselves determine how the target works.
17905 @c ===================================================== Site Configuration.
17907 @node Site Configuration
17908 @chapter Site Configuration
17910 @command{configure} scripts support several kinds of local configuration
17911 decisions.  There are ways for users to specify where external software
17912 packages are, include or exclude optional features, install programs
17913 under modified names, and set default values for @command{configure}
17914 options.
17916 @menu
17917 * Help Formatting::             Customizing @samp{configure --help}
17918 * External Software::           Working with other optional software
17919 * Package Options::             Selecting optional features
17920 * Pretty Help Strings::         Formatting help string
17921 * Option Checking::             Controlling checking of @command{configure} options
17922 * Site Details::                Configuring site details
17923 * Transforming Names::          Changing program names when installing
17924 * Site Defaults::               Giving @command{configure} local defaults
17925 @end menu
17927 @node Help Formatting
17928 @section Controlling Help Output
17930 Users consult @samp{configure --help} to learn of configuration
17931 decisions specific to your package.  By default, @command{configure}
17932 breaks this output into sections for each type of option; within each
17933 section, help strings appear in the order @file{configure.ac} defines
17934 them:
17936 @example
17937 Optional Features:
17938   @dots{}
17939   --enable-bar            include bar
17941 Optional Packages:
17942   @dots{}
17943   --with-foo              use foo
17944 @end example
17946 @defmac AC_PRESERVE_HELP_ORDER
17947 @acindex{PRESERVE_HELP_ORDER}
17949 Request an alternate @option{--help} format, in which options of all
17950 types appear together, in the order defined.  Call this macro before any
17951 @code{AC_ARG_ENABLE} or @code{AC_ARG_WITH}.
17953 @example
17954 Optional Features and Packages:
17955   @dots{}
17956   --enable-bar            include bar
17957   --with-foo              use foo
17958 @end example
17960 @end defmac
17962 @node External Software
17963 @section Working With External Software
17964 @cindex External software
17966 Some packages require, or can optionally use, other software packages
17967 that are already installed.  The user can give @command{configure}
17968 command line options to specify which such external software to use.
17969 The options have one of these forms:
17971 @c FIXME: Can't use @ovar here, Texinfo 4.0 goes lunatic and emits something
17972 @c awful.
17973 @example
17974 --with-@var{package}[=@var{arg}]
17975 --without-@var{package}
17976 @end example
17978 For example, @option{--with-gnu-ld} means work with the @acronym{GNU} linker
17979 instead of some other linker.  @option{--with-x} means work with The X
17980 Window System.
17982 The user can give an argument by following the package name with
17983 @samp{=} and the argument.  Giving an argument of @samp{no} is for
17984 packages that are used by default; it says to @emph{not} use the
17985 package.  An argument that is neither @samp{yes} nor @samp{no} could
17986 include a name or number of a version of the other package, to specify
17987 more precisely which other package this program is supposed to work
17988 with.  If no argument is given, it defaults to @samp{yes}.
17989 @option{--without-@var{package}} is equivalent to
17990 @option{--with-@var{package}=no}.
17992 Normally @command{configure} scripts complain about
17993 @option{--with-@var{package}} options that they do not support.
17994 @xref{Option Checking}, for details, and for how to override the
17995 defaults.
17997 For each external software package that may be used, @file{configure.ac}
17998 should call @code{AC_ARG_WITH} to detect whether the @command{configure}
17999 user asked to use it.  Whether each package is used or not by default,
18000 and which arguments are valid, is up to you.
18002 @anchor{AC_ARG_WITH}
18003 @defmac AC_ARG_WITH (@var{package}, @var{help-string}, @
18004   @ovar{action-if-given}, @ovar{action-if-not-given})
18005 @acindex{ARG_WITH}
18006 If the user gave @command{configure} the option @option{--with-@var{package}}
18007 or @option{--without-@var{package}}, run shell commands
18008 @var{action-if-given}.  If neither option was given, run shell commands
18009 @var{action-if-not-given}.  The name @var{package} indicates another
18010 software package that this program should work with.  It should consist
18011 only of alphanumeric characters, dashes, and dots.
18013 The option's argument is available to the shell commands
18014 @var{action-if-given} in the shell variable @code{withval}, which is
18015 actually just the value of the shell variable named
18016 @code{with_@var{package}}, with any non-alphanumeric characters in
18017 @var{package} changed into @samp{_}.  You may use that variable instead,
18018 if you wish.
18020 The argument @var{help-string} is a description of the option that
18021 looks like this:
18022 @example
18023   --with-readline         support fancy command line editing
18024 @end example
18026 @noindent
18027 @var{help-string} may be more than one line long, if more detail is
18028 needed.  Just make sure the columns line up in @samp{configure
18029 --help}.  Avoid tabs in the help string.  You'll need to enclose the
18030 help string in @samp{[} and @samp{]} in order to produce the leading
18031 blanks.
18033 You should format your @var{help-string} with the macro
18034 @code{AS_HELP_STRING} (@pxref{Pretty Help Strings}).
18036 The following example shows how to use the @code{AC_ARG_WITH} macro in
18037 a common situation.  You want to let the user decide whether to enable
18038 support for an external library (e.g., the readline library); if the user
18039 specified neither @option{--with-readline} nor @option{--without-readline},
18040 you want to enable support for readline only if the library is available
18041 on the system.
18043 @c FIXME: Remove AS_IF when the problem of AC_REQUIRE within `if' is solved.
18044 @example
18045 AC_ARG_WITH([readline],
18046   [AS_HELP_STRING([--with-readline],
18047     [support fancy command line editing @@<:@@default=check@@:>@@])],
18048   [],
18049   [with_readline=check])
18051 LIBREADLINE=
18052 AS_IF([test "x$with_readline" != xno],
18053   [AC_CHECK_LIB([readline], [main],
18054     [AC_SUBST([LIBREADLINE], ["-lreadline -lncurses"])
18055      AC_DEFINE([HAVE_LIBREADLINE], [1],
18056                [Define if you have libreadline])
18057     ],
18058     [if test "x$with_readline" != xcheck; then
18059        AC_MSG_FAILURE(
18060          [--with-readline was given, but test for readline failed])
18061      fi
18062     ], -lncurses)])
18063 @end example
18065 The next example shows how to use @code{AC_ARG_WITH} to give the user the
18066 possibility to enable support for the readline library, in case it is still
18067 experimental and not well tested, and is therefore disabled by default.
18069 @c FIXME: Remove AS_IF when the problem of AC_REQUIRE within `if' is solved.
18070 @example
18071 AC_ARG_WITH([readline],
18072   [AS_HELP_STRING([--with-readline],
18073     [enable experimental support for readline])],
18074   [],
18075   [with_readline=no])
18077 LIBREADLINE=
18078 AS_IF([test "x$with_readline" != xno],
18079   [AC_CHECK_LIB([readline], [main],
18080     [AC_SUBST([LIBREADLINE], ["-lreadline -lncurses"])
18081      AC_DEFINE([HAVE_LIBREADLINE], [1],
18082                [Define if you have libreadline])
18083     ],
18084     [AC_MSG_FAILURE(
18085        [--with-readline was given, but test for readline failed])],
18086     [-lncurses])])
18087 @end example
18089 The last example shows how to use @code{AC_ARG_WITH} to give the user the
18090 possibility to disable support for the readline library, given that it is
18091 an important feature and that it should be enabled by default.
18093 @c FIXME: Remove AS_IF when the problem of AC_REQUIRE within `if' is solved.
18094 @example
18095 AC_ARG_WITH([readline],
18096   [AS_HELP_STRING([--without-readline],
18097     [disable support for readline])],
18098   [],
18099   [with_readline=yes])
18101 LIBREADLINE=
18102 AS_IF([test "x$with_readline" != xno],
18103   [AC_CHECK_LIB([readline], [main],
18104     [AC_SUBST([LIBREADLINE], ["-lreadline -lncurses"])
18105      AC_DEFINE([HAVE_LIBREADLINE], [1],
18106                [Define if you have libreadline])
18107     ],
18108     [AC_MSG_FAILURE(
18109        [readline test failed (--without-readline to disable)])],
18110     [-lncurses])])
18111 @end example
18113 These three examples can be easily adapted to the case where
18114 @code{AC_ARG_ENABLE} should be preferred to @code{AC_ARG_WITH} (see
18115 @ref{Package Options}).
18116 @end defmac
18118 @node Package Options
18119 @section Choosing Package Options
18120 @cindex Package options
18121 @cindex Options, package
18123 If a software package has optional compile-time features, the user can
18124 give @command{configure} command line options to specify whether to
18125 compile them.  The options have one of these forms:
18127 @c FIXME: Can't use @ovar here, Texinfo 4.0 goes lunatic and emits something
18128 @c awful.
18129 @example
18130 --enable-@var{feature}[=@var{arg}]
18131 --disable-@var{feature}
18132 @end example
18134 These options allow users to choose which optional features to build and
18135 install.  @option{--enable-@var{feature}} options should never make a
18136 feature behave differently or cause one feature to replace another.
18137 They should only cause parts of the program to be built rather than left
18138 out.
18140 The user can give an argument by following the feature name with
18141 @samp{=} and the argument.  Giving an argument of @samp{no} requests
18142 that the feature @emph{not} be made available.  A feature with an
18143 argument looks like @option{--enable-debug=stabs}.  If no argument is
18144 given, it defaults to @samp{yes}.  @option{--disable-@var{feature}} is
18145 equivalent to @option{--enable-@var{feature}=no}.
18147 Normally @command{configure} scripts complain about
18148 @option{--enable-@var{package}} options that they do not support.
18149 @xref{Option Checking}, for details, and for how to override the
18150 defaults.
18152 For each optional feature, @file{configure.ac} should call
18153 @code{AC_ARG_ENABLE} to detect whether the @command{configure} user asked
18154 to include it.  Whether each feature is included or not by default, and
18155 which arguments are valid, is up to you.
18157 @anchor{AC_ARG_ENABLE}
18158 @defmac AC_ARG_ENABLE (@var{feature}, @var{help-string}, @
18159   @ovar{action-if-given}, @ovar{action-if-not-given})
18160 @acindex{ARG_ENABLE}
18161 If the user gave @command{configure} the option
18162 @option{--enable-@var{feature}} or @option{--disable-@var{feature}}, run
18163 shell commands @var{action-if-given}.  If neither option was given, run
18164 shell commands @var{action-if-not-given}.  The name @var{feature}
18165 indicates an optional user-level facility.  It should consist only of
18166 alphanumeric characters, dashes, and dots.
18168 The option's argument is available to the shell commands
18169 @var{action-if-given} in the shell variable @code{enableval}, which is
18170 actually just the value of the shell variable named
18171 @code{enable_@var{feature}}, with any non-alphanumeric characters in
18172 @var{feature} changed into @samp{_}.  You may use that variable instead,
18173 if you wish.  The @var{help-string} argument is like that of
18174 @code{AC_ARG_WITH} (@pxref{External Software}).
18176 You should format your @var{help-string} with the macro
18177 @code{AS_HELP_STRING} (@pxref{Pretty Help Strings}).
18179 See the examples suggested with the definition of @code{AC_ARG_WITH}
18180 (@pxref{External Software}) to get an idea of possible applications of
18181 @code{AC_ARG_ENABLE}.
18182 @end defmac
18184 @node Pretty Help Strings
18185 @section Making Your Help Strings Look Pretty
18186 @cindex Help strings
18188 Properly formatting the @samp{help strings} which are used in
18189 @code{AC_ARG_WITH} (@pxref{External Software}) and @code{AC_ARG_ENABLE}
18190 (@pxref{Package Options}) can be challenging.  Specifically, you want
18191 your own @samp{help strings} to line up in the appropriate columns of
18192 @samp{configure --help} just like the standard Autoconf @samp{help
18193 strings} do.  This is the purpose of the @code{AS_HELP_STRING} macro.
18195 @anchor{AS_HELP_STRING}
18196 @defmac AS_HELP_STRING (@var{left-hand-side}, @var{right-hand-side} @
18197   @dvar{indent-column, 26}, @dvar{wrap-column, 79})
18198 @asindex{HELP_STRING}
18200 Expands into an help string that looks pretty when the user executes
18201 @samp{configure --help}.  It is typically used in @code{AC_ARG_WITH}
18202 (@pxref{External Software}) or @code{AC_ARG_ENABLE} (@pxref{Package
18203 Options}).  The following example makes this clearer.
18205 @example
18206 AC_ARG_WITH([foo],
18207   [AS_HELP_STRING([--with-foo],
18208      [use foo (default is no)])],
18209   [use_foo=$withval],
18210   [use_foo=no])
18211 @end example
18213 Then the last few lines of @samp{configure --help} appear like
18214 this:
18216 @example
18217 --enable and --with options recognized:
18218   --with-foo              use foo (default is no)
18219 @end example
18221 Macro expansion is performed on the first argument.  However, the second
18222 argument of @code{AS_HELP_STRING} is treated as a whitespace separated
18223 list of text to be reformatted, and is not subject to macro expansion.
18224 Since it is not expanded, it should not be double quoted.
18225 @xref{Autoconf Language}, for a more detailed explanation.
18227 The @code{AS_HELP_STRING} macro is particularly helpful when the
18228 @var{left-hand-side} and/or @var{right-hand-side} are composed of macro
18229 arguments, as shown in the following example.  Be aware that
18230 @var{left-hand-side} may not expand to unbalanced quotes,
18231 although quadrigraphs can be used.
18233 @example
18234 AC_DEFUN([MY_ARG_WITH],
18235   [AC_ARG_WITH(m4_translit([[$1]], [_], [-]),
18236      [AS_HELP_STRING([--with-m4_translit([$1], [_], [-])],
18237                      [use $1 (default is $2)])],
18238      [use_[]$1=$withval],
18239      [use_[]$1=$2])])
18240 MY_ARG_WITH([a_b], [no])
18241 @end example
18242 @noindent
18243 Here, the last few lines of @samp{configure --help} will include:
18245 @example
18246 --enable and --with options recognized:
18247   --with-a-b              use a_b (default is no)
18248 @end example
18250 The parameters @var{indent-column} and @var{wrap-column} were introduced
18251 in Autoconf 2.62.  Generally, they should not be specified; they exist
18252 for fine-tuning of the wrapping.
18253 @example
18254 AS_HELP_STRING([--option], [description of option])
18255 @result{}  --option                description of option
18256 AS_HELP_STRING([--option], [description of option], [15], [30])
18257 @result{}  --option     description of
18258 @result{}               option
18259 @end example
18260 @end defmac
18263 @node Option Checking
18264 @section Controlling Checking of @command{configure} Options
18265 @cindex Options, Package
18267 The @command{configure} script checks its command-line options against a
18268 list of known options, like @option{--help} or @option{--config-cache}.
18269 An unknown option ordinarily indicates a mistake by the user and
18270 @command{configure} halts with an error.  However, by default unknown
18271 @option{--with-@var{package}} and @option{--enable-@var{feature}}
18272 options elicit only a warning, to support configuring entire source
18273 trees.
18275 Source trees often contain multiple packages with a top-level
18276 @command{configure} script that uses the @code{AC_CONFIG_SUBDIRS} macro
18277 (@pxref{Subdirectories}).  Because the packages generally support
18278 different @option{--with-@var{package}} and
18279 @option{--enable-@var{feature}} options, the @acronym{GNU} Coding
18280 Standards say they must accept unrecognized options without halting.
18281 Even a warning message is undesirable here, so @code{AC_CONFIG_SUBDIRS}
18282 automatically disables the warnings.
18284 This default behavior may be modified in two ways.  First, the installer
18285 can invoke @code{configure --disable-option-checking} to disable
18286 these warnings, or invoke @code{configure --enable-option-checking=fatal}
18287 options to turn them into fatal errors, respectively.  Second, the
18288 maintainer can use @code{AC_DISABLE_OPTION_CHECKING}.
18290 @defmac AC_DISABLE_OPTION_CHECKING
18291 @acindex{DISABLE_OPTION_CHECKING}
18293 By default, disable warnings related to any unrecognized
18294 @option{--with-@var{package}} or @option{--enable-@var{feature}}
18295 options.  This is implied by @code{AC_CONFIG_SUBDIRS}.
18297 The installer can override this behavior by passing
18298 @option{--enable-option-checking} (enable warnings) or
18299 @option{--enable-option-checking=fatal} (enable errors) to
18300 @command{configure}.
18301 @end defmac
18304 @node Site Details
18305 @section Configuring Site Details
18306 @cindex Site details
18308 Some software packages require complex site-specific information.  Some
18309 examples are host names to use for certain services, company names, and
18310 email addresses to contact.  Since some configuration scripts generated
18311 by Metaconfig ask for such information interactively, people sometimes
18312 wonder how to get that information in Autoconf-generated configuration
18313 scripts, which aren't interactive.
18315 Such site configuration information should be put in a file that is
18316 edited @emph{only by users}, not by programs.  The location of the file
18317 can either be based on the @code{prefix} variable, or be a standard
18318 location such as the user's home directory.  It could even be specified
18319 by an environment variable.  The programs should examine that file at
18320 runtime, rather than at compile time.  Runtime configuration is more
18321 convenient for users and makes the configuration process simpler than
18322 getting the information while configuring.  @xref{Directory Variables, ,
18323 Variables for Installation Directories, standards, @acronym{GNU} Coding
18324 Standards}, for more information on where to put data files.
18326 @node Transforming Names
18327 @section Transforming Program Names When Installing
18328 @cindex Transforming program names
18329 @cindex Program names, transforming
18331 Autoconf supports changing the names of programs when installing them.
18332 In order to use these transformations, @file{configure.ac} must call the
18333 macro @code{AC_ARG_PROGRAM}.
18335 @defmac AC_ARG_PROGRAM
18336 @acindex{ARG_PROGRAM}
18337 @ovindex program_transform_name
18338 Place in output variable @code{program_transform_name} a sequence of
18339 @code{sed} commands for changing the names of installed programs.
18341 If any of the options described below are given to @command{configure},
18342 program names are transformed accordingly.  Otherwise, if
18343 @code{AC_CANONICAL_TARGET} has been called and a @option{--target} value
18344 is given, the target type followed by a dash is used as a prefix.
18345 Otherwise, no program name transformation is done.
18346 @end defmac
18348 @menu
18349 * Transformation Options::      @command{configure} options to transform names
18350 * Transformation Examples::     Sample uses of transforming names
18351 * Transformation Rules::        Makefile uses of transforming names
18352 @end menu
18354 @node Transformation Options
18355 @subsection Transformation Options
18357 You can specify name transformations by giving @command{configure} these
18358 command line options:
18360 @table @option
18361 @item --program-prefix=@var{prefix}
18362 prepend @var{prefix} to the names;
18364 @item --program-suffix=@var{suffix}
18365 append @var{suffix} to the names;
18367 @item --program-transform-name=@var{expression}
18368 perform @code{sed} substitution @var{expression} on the names.
18369 @end table
18371 @node Transformation Examples
18372 @subsection Transformation Examples
18374 These transformations are useful with programs that can be part of a
18375 cross-compilation development environment.  For example, a
18376 cross-assembler running on a Sun 4 configured with
18377 @option{--target=i960-vxworks} is normally installed as
18378 @file{i960-vxworks-as}, rather than @file{as}, which could be confused
18379 with a native Sun 4 assembler.
18381 You can force a program name to begin with @file{g}, if you don't want
18382 @acronym{GNU} programs installed on your system to shadow other programs with
18383 the same name.  For example, if you configure @acronym{GNU} @code{diff} with
18384 @option{--program-prefix=g}, then when you run @samp{make install} it is
18385 installed as @file{/usr/local/bin/gdiff}.
18387 As a more sophisticated example, you could use
18389 @example
18390 --program-transform-name='s/^/g/; s/^gg/g/; s/^gless/less/'
18391 @end example
18392 @noindent
18394 to prepend @samp{g} to most of the program names in a source tree,
18395 excepting those like @code{gdb} that already have one and those like
18396 @code{less} and @code{lesskey} that aren't @acronym{GNU} programs.  (That is
18397 assuming that you have a source tree containing those programs that is
18398 set up to use this feature.)
18400 One way to install multiple versions of some programs simultaneously is
18401 to append a version number to the name of one or both.  For example, if
18402 you want to keep Autoconf version 1 around for awhile, you can configure
18403 Autoconf version 2 using @option{--program-suffix=2} to install the
18404 programs as @file{/usr/local/bin/autoconf2},
18405 @file{/usr/local/bin/autoheader2}, etc.  Nevertheless, pay attention
18406 that only the binaries are renamed, therefore you'd have problems with
18407 the library files which might overlap.
18409 @node Transformation Rules
18410 @subsection Transformation Rules
18412 Here is how to use the variable @code{program_transform_name} in a
18413 @file{Makefile.in}:
18415 @example
18416 PROGRAMS = cp ls rm
18417 transform = @@program_transform_name@@
18418 install:
18419         for p in $(PROGRAMS); do \
18420           $(INSTALL_PROGRAM) $$p $(DESTDIR)$(bindir)/`echo $$p | \
18421                                               sed '$(transform)'`; \
18422         done
18424 uninstall:
18425         for p in $(PROGRAMS); do \
18426           rm -f $(DESTDIR)$(bindir)/`echo $$p | sed '$(transform)'`; \
18427         done
18428 @end example
18430 It is guaranteed that @code{program_transform_name} is never empty, and
18431 that there are no useless separators.  Therefore you may safely embed
18432 @code{program_transform_name} within a sed program using @samp{;}:
18434 @example
18435 transform = @@program_transform_name@@
18436 transform_exe = s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/
18437 @end example
18439 Whether to do the transformations on documentation files (Texinfo or
18440 @code{man}) is a tricky question; there seems to be no perfect answer,
18441 due to the several reasons for name transforming.  Documentation is not
18442 usually particular to a specific architecture, and Texinfo files do not
18443 conflict with system documentation.  But they might conflict with
18444 earlier versions of the same files, and @code{man} pages sometimes do
18445 conflict with system documentation.  As a compromise, it is probably
18446 best to do name transformations on @code{man} pages but not on Texinfo
18447 manuals.
18449 @node Site Defaults
18450 @section Setting Site Defaults
18451 @cindex Site defaults
18453 Autoconf-generated @command{configure} scripts allow your site to provide
18454 default values for some configuration values.  You do this by creating
18455 site- and system-wide initialization files.
18457 @evindex CONFIG_SITE
18458 If the environment variable @code{CONFIG_SITE} is set, @command{configure}
18459 uses its value as the name of a shell script to read.  Otherwise, it
18460 reads the shell script @file{@var{prefix}/share/config.site} if it exists,
18461 then @file{@var{prefix}/etc/config.site} if it exists.  Thus,
18462 settings in machine-specific files override those in machine-independent
18463 ones in case of conflict.
18465 Site files can be arbitrary shell scripts, but only certain kinds of
18466 code are really appropriate to be in them.  Because @command{configure}
18467 reads any cache file after it has read any site files, a site file can
18468 define a default cache file to be shared between all Autoconf-generated
18469 @command{configure} scripts run on that system (@pxref{Cache Files}).  If
18470 you set a default cache file in a site file, it is a good idea to also
18471 set the output variable @code{CC} in that site file, because the cache
18472 file is only valid for a particular compiler, but many systems have
18473 several available.
18475 You can examine or override the value set by a command line option to
18476 @command{configure} in a site file; options set shell variables that have
18477 the same names as the options, with any dashes turned into underscores.
18478 The exceptions are that @option{--without-} and @option{--disable-} options
18479 are like giving the corresponding @option{--with-} or @option{--enable-}
18480 option and the value @samp{no}.  Thus, @option{--cache-file=localcache}
18481 sets the variable @code{cache_file} to the value @samp{localcache};
18482 @option{--enable-warnings=no} or @option{--disable-warnings} sets the variable
18483 @code{enable_warnings} to the value @samp{no}; @option{--prefix=/usr} sets the
18484 variable @code{prefix} to the value @samp{/usr}; etc.
18486 Site files are also good places to set default values for other output
18487 variables, such as @code{CFLAGS}, if you need to give them non-default
18488 values: anything you would normally do, repetitively, on the command
18489 line.  If you use non-default values for @var{prefix} or
18490 @var{exec_prefix} (wherever you locate the site file), you can set them
18491 in the site file if you specify it with the @code{CONFIG_SITE}
18492 environment variable.
18494 You can set some cache values in the site file itself.  Doing this is
18495 useful if you are cross-compiling, where it is impossible to check features
18496 that require running a test program.  You could ``prime the cache'' by
18497 setting those values correctly for that system in
18498 @file{@var{prefix}/etc/config.site}.  To find out the names of the cache
18499 variables you need to set, look for shell variables with @samp{_cv_} in
18500 their names in the affected @command{configure} scripts, or in the Autoconf
18501 M4 source code for those macros.
18503 The cache file is careful to not override any variables set in the site
18504 files.  Similarly, you should not override command-line options in the
18505 site files.  Your code should check that variables such as @code{prefix}
18506 and @code{cache_file} have their default values (as set near the top of
18507 @command{configure}) before changing them.
18509 Here is a sample file @file{/usr/share/local/gnu/share/config.site}.  The
18510 command @samp{configure --prefix=/usr/share/local/gnu} would read this
18511 file (if @code{CONFIG_SITE} is not set to a different file).
18513 @example
18514 # config.site for configure
18516 # Change some defaults.
18517 test "$prefix" = NONE && prefix=/usr/share/local/gnu
18518 test "$exec_prefix" = NONE && exec_prefix=/usr/local/gnu
18519 test "$sharedstatedir" = '$@{prefix@}/com' && sharedstatedir=/var
18520 test "$localstatedir" = '$@{prefix@}/var' && localstatedir=/var
18522 # Give Autoconf 2.x generated configure scripts a shared default
18523 # cache file for feature test results, architecture-specific.
18524 if test "$cache_file" = /dev/null; then
18525   cache_file="$prefix/var/config.cache"
18526   # A cache file is only valid for one C compiler.
18527   CC=gcc
18529 @end example
18531 @cindex Filesystem Hierarchy Standard
18532 @cindex FHS
18534 Another use of @file{config.site} is for priming the directory variables
18535 in a manner consistent with the Filesystem Hierarchy Standard
18536 (@acronym{FHS}).  Once the following file is installed at
18537 @file{/usr/share/config.site}, a user can execute simply
18538 @code{./configure --prefix=/usr} to get all the directories chosen in
18539 the locations recommended by @acronym{FHS}.
18541 @example
18542 # /usr/local/config.site for FHS defaults when installing below /usr,
18543 # and the respective settings were not changed on the command line.
18544 if test "$prefix" = /usr; then
18545   test "$sysconfdir" = '$@{prefix@}/etc' && sysconfdir=/etc
18546   test "$sharedstatedir" = '$@{prefix@}/com' && sharedstatedir=/var
18547   test "$localstatedir" = '$@{prefix@}/var' && localstatedir=/var
18549 @end example
18552 @c ============================================== Running configure Scripts.
18554 @node Running configure Scripts
18555 @chapter Running @command{configure} Scripts
18556 @cindex @command{configure}
18558 Below are instructions on how to configure a package that uses a
18559 @command{configure} script, suitable for inclusion as an @file{INSTALL}
18560 file in the package.  A plain-text version of @file{INSTALL} which you
18561 may use comes with Autoconf.
18563 @menu
18564 * Basic Installation::          Instructions for typical cases
18565 * Compilers and Options::       Selecting compilers and optimization
18566 * Multiple Architectures::      Compiling for multiple architectures at once
18567 * Installation Names::          Installing in different directories
18568 * Optional Features::           Selecting optional features
18569 * Particular Systems::          Particular systems
18570 * System Type::                 Specifying the system type
18571 * Sharing Defaults::            Setting site-wide defaults for @command{configure}
18572 * Defining Variables::          Specifying the compiler etc.
18573 * configure Invocation::        Changing how @command{configure} runs
18574 @end menu
18576 @set autoconf
18577 @include install.texi
18580 @c ============================================== config.status Invocation
18582 @node config.status Invocation
18583 @chapter config.status Invocation
18584 @cindex @command{config.status}
18586 The @command{configure} script creates a file named @file{config.status},
18587 which actually configures, @dfn{instantiates}, the template files.  It
18588 also records the configuration options that were specified when the
18589 package was last configured in case reconfiguring is needed.
18591 Synopsis:
18592 @example
18593 ./config.status @var{option}@dots{} [@var{file}@dots{}]
18594 @end example
18596 It configures the @var{files}; if none are specified, all the templates
18597 are instantiated.  The files must be specified without their
18598 dependencies, as in
18600 @example
18601 ./config.status foobar
18602 @end example
18604 @noindent
18607 @example
18608 ./config.status foobar:foo.in:bar.in
18609 @end example
18611 The supported options are:
18613 @table @option
18614 @item --help
18615 @itemx -h
18616 Print a summary of the command line options, the list of the template
18617 files, and exit.
18619 @item --version
18620 @itemx -V
18621 Print the version number of Autoconf and the configuration settings,
18622 and exit.
18624 @item --silent
18625 @itemx --quiet
18626 @itemx -q
18627 Do not print progress messages.
18629 @item --debug
18630 @itemx -d
18631 Don't remove the temporary files.
18633 @item --file=@var{file}[:@var{template}]
18634 Require that @var{file} be instantiated as if
18635 @samp{AC_CONFIG_FILES(@var{file}:@var{template})} was used.  Both
18636 @var{file} and @var{template} may be @samp{-} in which case the standard
18637 output and/or standard input, respectively, is used.  If a
18638 @var{template} file name is relative, it is first looked for in the build
18639 tree, and then in the source tree.  @xref{Configuration Actions}, for
18640 more details.
18642 This option and the following ones provide one way for separately
18643 distributed packages to share the values computed by @command{configure}.
18644 Doing so can be useful if some of the packages need a superset of the
18645 features that one of them, perhaps a common library, does.  These
18646 options allow a @file{config.status} file to create files other than the
18647 ones that its @file{configure.ac} specifies, so it can be used for a
18648 different package.
18650 @item --header=@var{file}[:@var{template}]
18651 Same as @option{--file} above, but with @samp{AC_CONFIG_HEADERS}.
18653 @item --recheck
18654 Ask @file{config.status} to update itself and exit (no instantiation).
18655 This option is useful if you change @command{configure}, so that the
18656 results of some tests might be different from the previous run.  The
18657 @option{--recheck} option reruns @command{configure} with the same arguments
18658 you used before, plus the @option{--no-create} option, which prevents
18659 @command{configure} from running @file{config.status} and creating
18660 @file{Makefile} and other files, and the @option{--no-recursion} option,
18661 which prevents @command{configure} from running other @command{configure}
18662 scripts in subdirectories.  (This is so other Make rules can
18663 run @file{config.status} when it changes; @pxref{Automatic Remaking},
18664 for an example).
18665 @end table
18667 @file{config.status} checks several optional environment variables that
18668 can alter its behavior:
18670 @defvar CONFIG_SHELL
18671 @evindex CONFIG_SHELL
18672 The shell with which to run @command{configure} for the @option{--recheck}
18673 option.  It must be Bourne-compatible.  The default is a shell that
18674 supports @code{LINENO} if available, and @file{/bin/sh} otherwise.
18675 Invoking @command{configure} by hand bypasses this setting, so you may
18676 need to use a command like @samp{CONFIG_SHELL=/bin/bash /bin/bash ./configure}
18677 to insure that the same shell is used everywhere.  The absolute name of the
18678 shell should be passed.
18679 @end defvar
18681 @defvar CONFIG_STATUS
18682 @evindex CONFIG_STATUS
18683 The file name to use for the shell script that records the
18684 configuration.  The default is @file{./config.status}.  This variable is
18685 useful when one package uses parts of another and the @command{configure}
18686 scripts shouldn't be merged because they are maintained separately.
18687 @end defvar
18689 You can use @file{./config.status} in your makefiles.  For example, in
18690 the dependencies given above (@pxref{Automatic Remaking}),
18691 @file{config.status} is run twice when @file{configure.ac} has changed.
18692 If that bothers you, you can make each run only regenerate the files for
18693 that rule:
18694 @example
18695 @group
18696 config.h: stamp-h
18697 stamp-h: config.h.in config.status
18698         ./config.status config.h
18699         echo > stamp-h
18701 Makefile: Makefile.in config.status
18702         ./config.status Makefile
18703 @end group
18704 @end example
18706 The calling convention of @file{config.status} has changed; see
18707 @ref{Obsolete config.status Use}, for details.
18710 @c =================================================== Obsolete Constructs
18712 @node Obsolete Constructs
18713 @chapter Obsolete Constructs
18714 @cindex Obsolete constructs
18716 Autoconf changes, and throughout the years some constructs have been
18717 obsoleted.  Most of the changes involve the macros, but in some cases
18718 the tools themselves, or even some concepts, are now considered
18719 obsolete.
18721 You may completely skip this chapter if you are new to Autoconf.  Its
18722 intention is mainly to help maintainers updating their packages by
18723 understanding how to move to more modern constructs.
18725 @menu
18726 * Obsolete config.status Use::  Obsolete convention for @command{config.status}
18727 * acconfig Header::             Additional entries in @file{config.h.in}
18728 * autoupdate Invocation::       Automatic update of @file{configure.ac}
18729 * Obsolete Macros::             Backward compatibility macros
18730 * Autoconf 1::                  Tips for upgrading your files
18731 * Autoconf 2.13::               Some fresher tips
18732 @end menu
18734 @node Obsolete config.status Use
18735 @section Obsolete @file{config.status} Invocation
18737 @file{config.status} now supports arguments to specify the files to
18738 instantiate; see @ref{config.status Invocation}, for more details.
18739 Before, environment variables had to be used.
18741 @defvar CONFIG_COMMANDS
18742 @evindex CONFIG_COMMANDS
18743 The tags of the commands to execute.  The default is the arguments given
18744 to @code{AC_OUTPUT} and @code{AC_CONFIG_COMMANDS} in
18745 @file{configure.ac}.
18746 @end defvar
18748 @defvar CONFIG_FILES
18749 @evindex CONFIG_FILES
18750 The files in which to perform @samp{@@@var{variable}@@} substitutions.
18751 The default is the arguments given to @code{AC_OUTPUT} and
18752 @code{AC_CONFIG_FILES} in @file{configure.ac}.
18753 @end defvar
18755 @defvar CONFIG_HEADERS
18756 @evindex CONFIG_HEADERS
18757 The files in which to substitute C @code{#define} statements.  The
18758 default is the arguments given to @code{AC_CONFIG_HEADERS}; if that
18759 macro was not called, @file{config.status} ignores this variable.
18760 @end defvar
18762 @defvar CONFIG_LINKS
18763 @evindex CONFIG_LINKS
18764 The symbolic links to establish.  The default is the arguments given to
18765 @code{AC_CONFIG_LINKS}; if that macro was not called,
18766 @file{config.status} ignores this variable.
18767 @end defvar
18769 In @ref{config.status Invocation}, using this old interface, the example
18770 would be:
18772 @example
18773 @group
18774 config.h: stamp-h
18775 stamp-h: config.h.in config.status
18776         CONFIG_COMMANDS= CONFIG_LINKS= CONFIG_FILES= \
18777           CONFIG_HEADERS=config.h ./config.status
18778         echo > stamp-h
18780 Makefile: Makefile.in config.status
18781         CONFIG_COMMANDS= CONFIG_LINKS= CONFIG_HEADERS= \
18782           CONFIG_FILES=Makefile ./config.status
18783 @end group
18784 @end example
18786 @noindent
18787 (If @file{configure.ac} does not call @code{AC_CONFIG_HEADERS}, there is
18788 no need to set @code{CONFIG_HEADERS} in the @command{make} rules.  Equally
18789 for @code{CONFIG_COMMANDS}, etc.)
18792 @node acconfig Header
18793 @section @file{acconfig.h}
18795 @cindex @file{acconfig.h}
18796 @cindex @file{config.h.top}
18797 @cindex @file{config.h.bot}
18799 In order to produce @file{config.h.in}, @command{autoheader} needs to
18800 build or to find templates for each symbol.  Modern releases of Autoconf
18801 use @code{AH_VERBATIM} and @code{AH_TEMPLATE} (@pxref{Autoheader
18802 Macros}), but in older releases a file, @file{acconfig.h}, contained the
18803 list of needed templates.  @command{autoheader} copied comments and
18804 @code{#define} and @code{#undef} statements from @file{acconfig.h} in
18805 the current directory, if present.  This file used to be mandatory if
18806 you @code{AC_DEFINE} any additional symbols.
18808 Modern releases of Autoconf also provide @code{AH_TOP} and
18809 @code{AH_BOTTOM} if you need to prepend/append some information to
18810 @file{config.h.in}.  Ancient versions of Autoconf had a similar feature:
18811 if @file{./acconfig.h} contains the string @samp{@@TOP@@},
18812 @command{autoheader} copies the lines before the line containing
18813 @samp{@@TOP@@} into the top of the file that it generates.  Similarly,
18814 if @file{./acconfig.h} contains the string @samp{@@BOTTOM@@},
18815 @command{autoheader} copies the lines after that line to the end of the
18816 file it generates.  Either or both of those strings may be omitted.  An
18817 even older alternate way to produce the same effect in ancient versions
18818 of Autoconf is to create the files @file{@var{file}.top} (typically
18819 @file{config.h.top}) and/or @file{@var{file}.bot} in the current
18820 directory.  If they exist, @command{autoheader} copies them to the
18821 beginning and end, respectively, of its output.
18823 In former versions of Autoconf, the files used in preparing a software
18824 package for distribution were:
18825 @example
18826 @group
18827 configure.ac --.   .------> autoconf* -----> configure
18828                +---+
18829 [aclocal.m4] --+   `---.
18830 [acsite.m4] ---'       |
18831                        +--> [autoheader*] -> [config.h.in]
18832 [acconfig.h] ----.     |
18833                  +-----'
18834 [config.h.top] --+
18835 [config.h.bot] --'
18836 @end group
18837 @end example
18839 Using only the @code{AH_} macros, @file{configure.ac} should be
18840 self-contained, and should not depend upon @file{acconfig.h} etc.
18843 @node autoupdate Invocation
18844 @section Using @command{autoupdate} to Modernize @file{configure.ac}
18845 @cindex @command{autoupdate}
18847 The @command{autoupdate} program updates a @file{configure.ac} file that
18848 calls Autoconf macros by their old names to use the current macro names.
18849 In version 2 of Autoconf, most of the macros were renamed to use a more
18850 uniform and descriptive naming scheme.  @xref{Macro Names}, for a
18851 description of the new scheme.  Although the old names still work
18852 (@pxref{Obsolete Macros}, for a list of the old macros and the corresponding
18853 new names), you can make your @file{configure.ac} files more readable
18854 and make it easier to use the current Autoconf documentation if you
18855 update them to use the new macro names.
18857 @evindex SIMPLE_BACKUP_SUFFIX
18858 If given no arguments, @command{autoupdate} updates @file{configure.ac},
18859 backing up the original version with the suffix @file{~} (or the value
18860 of the environment variable @code{SIMPLE_BACKUP_SUFFIX}, if that is
18861 set).  If you give @command{autoupdate} an argument, it reads that file
18862 instead of @file{configure.ac} and writes the updated file to the
18863 standard output.
18865 @noindent
18866 @command{autoupdate} accepts the following options:
18868 @table @option
18869 @item --help
18870 @itemx -h
18871 Print a summary of the command line options and exit.
18873 @item --version
18874 @itemx -V
18875 Print the version number of Autoconf and exit.
18877 @item --verbose
18878 @itemx -v
18879 Report processing steps.
18881 @item --debug
18882 @itemx -d
18883 Don't remove the temporary files.
18885 @item --force
18886 @itemx -f
18887 Force the update even if the file has not changed.  Disregard the cache.
18889 @item --include=@var{dir}
18890 @itemx -I @var{dir}
18891 Also look for input files in @var{dir}.  Multiple invocations accumulate.
18892 Directories are browsed from last to first.
18894 @item --prepend-include=@var{dir}
18895 @itemx -B @var{dir}
18896 Prepend directory @var{dir} to the search path.  This is used to include
18897 the language-specific files before any third-party macros.
18898 @end table
18900 @node Obsolete Macros
18901 @section Obsolete Macros
18903 Several macros are obsoleted in Autoconf, for various reasons (typically
18904 they failed to quote properly, couldn't be extended for more recent
18905 issues, etc.).  They are still supported, but deprecated: their use
18906 should be avoided.
18908 During the jump from Autoconf version 1 to version 2, most of the
18909 macros were renamed to use a more uniform and descriptive naming scheme,
18910 but their signature did not change.  @xref{Macro Names}, for a
18911 description of the new naming scheme.  Below, if there is just the mapping
18912 from old names to new names for these macros, the reader is invited to
18913 refer to the definition of the new macro for the signature and the
18914 description.
18916 @defmac AC_AIX
18917 @acindex{AIX}
18918 @cvindex _ALL_SOURCE
18919 This macro is a platform-specific subset of
18920 @code{AC_USE_SYSTEM_EXTENSIONS} (@pxref{AC_USE_SYSTEM_EXTENSIONS}).
18921 @end defmac
18923 @defmac AC_ALLOCA
18924 @acindex{ALLOCA}
18925 Replaced by @code{AC_FUNC_ALLOCA} (@pxref{AC_FUNC_ALLOCA}).
18926 @end defmac
18928 @defmac AC_ARG_ARRAY
18929 @acindex{ARG_ARRAY}
18930 Removed because of limited usefulness.
18931 @end defmac
18933 @defmac AC_C_CROSS
18934 @acindex{C_CROSS}
18935 This macro is obsolete; it does nothing.
18936 @end defmac
18938 @defmac AC_C_LONG_DOUBLE
18939 @acindex{C_LONG_DOUBLE}
18940 @cvindex HAVE_LONG_DOUBLE
18941 If the C compiler supports a working @code{long double} type with more
18942 range or precision than the @code{double} type, define
18943 @code{HAVE_LONG_DOUBLE}.
18945 You should use @code{AC_TYPE_LONG_DOUBLE} or
18946 @code{AC_TYPE_LONG_DOUBLE_WIDER} instead.  @xref{Particular Types}.
18947 @end defmac
18949 @defmac AC_CANONICAL_SYSTEM
18950 @acindex{CANONICAL_SYSTEM}
18951 Determine the system type and set output variables to the names of the
18952 canonical system types.  @xref{Canonicalizing}, for details about the
18953 variables this macro sets.
18955 The user is encouraged to use either @code{AC_CANONICAL_BUILD}, or
18956 @code{AC_CANONICAL_HOST}, or @code{AC_CANONICAL_TARGET}, depending on
18957 the needs.  Using @code{AC_CANONICAL_TARGET} is enough to run the two
18958 other macros (@pxref{Canonicalizing}).
18959 @end defmac
18961 @defmac AC_CHAR_UNSIGNED
18962 @acindex{CHAR_UNSIGNED}
18963 Replaced by @code{AC_C_CHAR_UNSIGNED} (@pxref{AC_C_CHAR_UNSIGNED}).
18964 @end defmac
18966 @defmac AC_CHECK_TYPE (@var{type}, @var{default})
18967 @acindex{CHECK_TYPE}
18968 Autoconf, up to 2.13, used to provide this version of
18969 @code{AC_CHECK_TYPE}, deprecated because of its flaws.  First, although
18970 it is a member of the @code{CHECK} clan, it does
18971 more than just checking.  Secondly, missing types are defined
18972 using @code{#define}, not @code{typedef}, and this can lead to
18973 problems in the case of pointer types.
18975 This use of @code{AC_CHECK_TYPE} is obsolete and discouraged; see
18976 @ref{Generic Types}, for the description of the current macro.
18978 If the type @var{type} is not defined, define it to be the C (or C++)
18979 builtin type @var{default}, e.g., @samp{short int} or @samp{unsigned int}.
18981 This macro is equivalent to:
18983 @example
18984 AC_CHECK_TYPE([@var{type}], [],
18985   [AC_DEFINE_UNQUOTED([@var{type}], [@var{default}],
18986      [Define to `@var{default}'
18987       if <sys/types.h> does not define.])])
18988 @end example
18990 In order to keep backward compatibility, the two versions of
18991 @code{AC_CHECK_TYPE} are implemented, selected using these heuristics:
18993 @enumerate
18994 @item
18995 If there are three or four arguments, the modern version is used.
18997 @item
18998 If the second argument appears to be a C or C++ type, then the
18999 obsolete version is used.  This happens if the argument is a C or C++
19000 @emph{builtin} type or a C identifier ending in @samp{_t}, optionally
19001 followed by one of @samp{[(* } and then by a string of zero or more
19002 characters taken from the set @samp{[]()* _a-zA-Z0-9}.
19004 @item
19005 If the second argument is spelled with the alphabet of valid C and C++
19006 types, the user is warned and the modern version is used.
19008 @item
19009 Otherwise, the modern version is used.
19010 @end enumerate
19012 @noindent
19013 You are encouraged either to use a valid builtin type, or to use the
19014 equivalent modern code (see above), or better yet, to use
19015 @code{AC_CHECK_TYPES} together with
19017 @example
19018 #ifndef HAVE_LOFF_T
19019 typedef loff_t off_t;
19020 #endif
19021 @end example
19022 @end defmac
19023 @c end of AC_CHECK_TYPE
19025 @defmac AC_CHECKING (@var{feature-description})
19026 @acindex{CHECKING}
19027 Same as
19029 @example
19030 AC_MSG_NOTICE([checking @var{feature-description}@dots{}]
19031 @end example
19033 @noindent
19034 @xref{AC_MSG_NOTICE}.
19035 @end defmac
19037 @defmac AC_COMPILE_CHECK (@var{echo-text}, @var{includes}, @
19038   @var{function-body}, @var{action-if-true}, @ovar{action-if-false})
19039 @acindex{COMPILE_CHECK}
19040 This is an obsolete version of @code{AC_TRY_COMPILE} itself replaced by
19041 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}), with the
19042 addition that it prints @samp{checking for @var{echo-text}} to the
19043 standard output first, if @var{echo-text} is non-empty.  Use
19044 @code{AC_MSG_CHECKING} and @code{AC_MSG_RESULT} instead to print
19045 messages (@pxref{Printing Messages}).
19046 @end defmac
19048 @defmac AC_CONST
19049 @acindex{CONST}
19050 Replaced by @code{AC_C_CONST} (@pxref{AC_C_CONST}).
19051 @end defmac
19053 @defmac AC_CROSS_CHECK
19054 @acindex{CROSS_CHECK}
19055 Same as @code{AC_C_CROSS}, which is obsolete too, and does nothing
19056 @code{:-)}.
19057 @end defmac
19059 @defmac AC_CYGWIN
19060 @acindex{CYGWIN}
19061 @evindex CYGWIN
19062 Check for the Cygwin environment in which case the shell variable
19063 @code{CYGWIN} is set to @samp{yes}.  Don't use this macro, the dignified
19064 means to check the nature of the host is using @code{AC_CANONICAL_HOST}
19065 (@pxref{Canonicalizing}).  As a matter of fact this macro is defined as:
19067 @example
19068 AC_REQUIRE([AC_CANONICAL_HOST])[]dnl
19069 case $host_os in
19070   *cygwin* ) CYGWIN=yes;;
19071          * ) CYGWIN=no;;
19072 esac
19073 @end example
19075 Beware that the variable @env{CYGWIN} has a special meaning when
19076 running Cygwin, and should not be changed.  That's yet another reason
19077 not to use this macro.
19078 @end defmac
19080 @defmac AC_DECL_SYS_SIGLIST
19081 @acindex{DECL_SYS_SIGLIST}
19082 @cvindex SYS_SIGLIST_DECLARED
19083 Same as:
19085 @example
19086 AC_CHECK_DECLS([sys_siglist], [], [],
19087 [#include <signal.h>
19088 /* NetBSD declares sys_siglist in unistd.h.  */
19089 #ifdef HAVE_UNISTD_H
19090 # include <unistd.h>
19091 #endif
19093 @end example
19095 @noindent
19096 @xref{AC_CHECK_DECLS}.
19097 @end defmac
19099 @defmac AC_DECL_YYTEXT
19100 @acindex{DECL_YYTEXT}
19101 Does nothing, now integrated in @code{AC_PROG_LEX} (@pxref{AC_PROG_LEX}).
19102 @end defmac
19104 @defmac AC_DIR_HEADER
19105 @acindex{DIR_HEADER}
19106 @cvindex DIRENT
19107 @cvindex SYSNDIR
19108 @cvindex SYSDIR
19109 @cvindex NDIR
19110 Like calling @code{AC_FUNC_CLOSEDIR_VOID}
19111 (@pxref{AC_FUNC_CLOSEDIR_VOID}) and @code{AC_HEADER_DIRENT}
19112 (@pxref{AC_HEADER_DIRENT}),
19113 but defines a different set of C preprocessor macros to indicate which
19114 header file is found:
19116 @multitable {@file{sys/ndir.h}} {Old Symbol} {@code{HAVE_SYS_NDIR_H}}
19117 @item Header            @tab Old Symbol     @tab New Symbol
19118 @item @file{dirent.h}   @tab @code{DIRENT}  @tab @code{HAVE_DIRENT_H}
19119 @item @file{sys/ndir.h} @tab @code{SYSNDIR} @tab @code{HAVE_SYS_NDIR_H}
19120 @item @file{sys/dir.h}  @tab @code{SYSDIR}  @tab @code{HAVE_SYS_DIR_H}
19121 @item @file{ndir.h}     @tab @code{NDIR}    @tab @code{HAVE_NDIR_H}
19122 @end multitable
19123 @end defmac
19125 @defmac AC_DYNIX_SEQ
19126 @acindex{DYNIX_SEQ}
19127 If on DYNIX/ptx, add @option{-lseq} to output variable
19128 @code{LIBS}.  This macro used to be defined as
19130 @example
19131 AC_CHECK_LIB([seq], [getmntent], [LIBS="-lseq $LIBS"])
19132 @end example
19134 @noindent
19135 now it is just @code{AC_FUNC_GETMNTENT} (@pxref{AC_FUNC_GETMNTENT}).
19136 @end defmac
19138 @defmac AC_EXEEXT
19139 @acindex{EXEEXT}
19140 @ovindex EXEEXT
19141 Defined the output variable @code{EXEEXT} based on the output of the
19142 compiler, which is now done automatically.  Typically set to empty
19143 string if Posix and @samp{.exe} if a @acronym{DOS} variant.
19144 @end defmac
19146 @defmac AC_EMXOS2
19147 @acindex{EMXOS2}
19148 Similar to @code{AC_CYGWIN} but checks for the EMX environment on OS/2
19149 and sets @code{EMXOS2}.  Don't use this macro, the dignified means to
19150 check the nature of the host is using @code{AC_CANONICAL_HOST}
19151 (@pxref{Canonicalizing}).
19152 @end defmac
19154 @defmac AC_ENABLE (@var{feature}, @var{action-if-given}, @
19155   @ovar{action-if-not-given})
19156 @acindex{ENABLE}
19157 This is an obsolete version of @code{AC_ARG_ENABLE} that does not
19158 support providing a help string (@pxref{AC_ARG_ENABLE}).
19159 @end defmac
19161 @defmac AC_ERROR
19162 @acindex{ERROR}
19163 Replaced by @code{AC_MSG_ERROR} (@pxref{AC_MSG_ERROR}).
19164 @end defmac
19166 @defmac AC_FIND_X
19167 @acindex{FIND_X}
19168 Replaced by @code{AC_PATH_X} (@pxref{AC_PATH_X}).
19169 @end defmac
19171 @defmac AC_FIND_XTRA
19172 @acindex{FIND_XTRA}
19173 Replaced by @code{AC_PATH_XTRA} (@pxref{AC_PATH_XTRA}).
19174 @end defmac
19176 @defmac AC_FOREACH
19177 @acindex{FOREACH}
19178 Replaced by @code{m4_foreach_w} (@pxref{m4_foreach_w}).
19179 @end defmac
19181 @defmac AC_FUNC_CHECK
19182 @acindex{FUNC_CHECK}
19183 Replaced by @code{AC_CHECK_FUNC} (@pxref{AC_CHECK_FUNC}).
19184 @end defmac
19186 @anchor{AC_FUNC_SETVBUF_REVERSED}
19187 @defmac AC_FUNC_SETVBUF_REVERSED
19188 @acindex{FUNC_SETVBUF_REVERSED}
19189 @cvindex SETVBUF_REVERSED
19190 @c @fuindex setvbuf
19191 @prindex @code{setvbuf}
19192 Do nothing.  Formerly, this macro checked whether @code{setvbuf} takes
19193 the buffering type as its second argument and the buffer pointer as the
19194 third, instead of the other way around, and defined
19195 @code{SETVBUF_REVERSED}.  However, the last systems to have the problem
19196 were those based on SVR2, which became obsolete in 1987, and the macro
19197 is no longer needed.
19198 @end defmac
19200 @defmac AC_FUNC_WAIT3
19201 @acindex{FUNC_WAIT3}
19202 @cvindex HAVE_WAIT3
19203 If @code{wait3} is found and fills in the contents of its third argument
19204 (a @samp{struct rusage *}), which @acronym{HP-UX} does not do, define
19205 @code{HAVE_WAIT3}.
19207 These days portable programs should use @code{waitpid}, not
19208 @code{wait3}, as @code{wait3} has been removed from Posix.
19209 @end defmac
19211 @defmac AC_GCC_TRADITIONAL
19212 @acindex{GCC_TRADITIONAL}
19213 Replaced by @code{AC_PROG_GCC_TRADITIONAL} (@pxref{AC_PROG_GCC_TRADITIONAL}).
19214 @end defmac
19216 @defmac AC_GETGROUPS_T
19217 @acindex{GETGROUPS_T}
19218 Replaced by @code{AC_TYPE_GETGROUPS} (@pxref{AC_TYPE_GETGROUPS}).
19219 @end defmac
19221 @defmac AC_GETLOADAVG
19222 @acindex{GETLOADAVG}
19223 Replaced by @code{AC_FUNC_GETLOADAVG} (@pxref{AC_FUNC_GETLOADAVG}).
19224 @end defmac
19226 @defmac AC_GNU_SOURCE
19227 @acindex{GNU_SOURCE}
19228 @cvindex _GNU_SOURCE
19229 This macro is a platform-specific subset of
19230 @code{AC_USE_SYSTEM_EXTENSIONS} (@pxref{AC_USE_SYSTEM_EXTENSIONS}).
19231 @end defmac
19233 @defmac AC_HAVE_FUNCS
19234 @acindex{HAVE_FUNCS}
19235 Replaced by @code{AC_CHECK_FUNCS} (@pxref{AC_CHECK_FUNCS}).
19236 @end defmac
19238 @defmac AC_HAVE_HEADERS
19239 @acindex{HAVE_HEADERS}
19240 Replaced by @code{AC_CHECK_HEADERS} (@pxref{AC_CHECK_HEADERS}).
19241 @end defmac
19243 @defmac AC_HAVE_LIBRARY (@var{library}, @ovar{action-if-found}, @
19244   @ovar{action-if-not-found}, @ovar{other-libraries})
19245 @acindex{HAVE_LIBRARY}
19246 This macro is equivalent to calling @code{AC_CHECK_LIB} with a
19247 @var{function} argument of @code{main}.  In addition, @var{library} can
19248 be written as any of @samp{foo}, @option{-lfoo}, or @samp{libfoo.a}.  In
19249 all of those cases, the compiler is passed @option{-lfoo}.  However,
19250 @var{library} cannot be a shell variable; it must be a literal name.
19251 @xref{AC_CHECK_LIB}.
19252 @end defmac
19254 @defmac AC_HAVE_POUNDBANG
19255 @acindex{HAVE_POUNDBANG}
19256 Replaced by @code{AC_SYS_INTERPRETER} (@pxref{AC_SYS_INTERPRETER}).
19257 @end defmac
19259 @defmac AC_HEADER_CHECK
19260 @acindex{HEADER_CHECK}
19261 Replaced by @code{AC_CHECK_HEADER} (@pxref{AC_CHECK_HEADER}).
19262 @end defmac
19264 @defmac AC_HEADER_EGREP
19265 @acindex{HEADER_EGREP}
19266 Replaced by @code{AC_EGREP_HEADER} (@pxref{AC_EGREP_HEADER}).
19267 @end defmac
19269 @defmac AC_HELP_STRING
19270 @acindex{HELP_STRING}
19271 Replaced by @code{AS_HELP_STRING} (@pxref{AS_HELP_STRING}).
19272 @end defmac
19274 @defmac AC_INIT (@var{unique-file-in-source-dir})
19275 @acindex{INIT}
19276 Formerly @code{AC_INIT} used to have a single argument, and was
19277 equivalent to:
19279 @example
19280 AC_INIT
19281 AC_CONFIG_SRCDIR(@var{unique-file-in-source-dir})
19282 @end example
19283 See @ref{AC_INIT} and @ref{AC_CONFIG_SRCDIR}.
19284 @end defmac
19286 @defmac AC_INLINE
19287 @acindex{INLINE}
19288 Replaced by @code{AC_C_INLINE} (@pxref{AC_C_INLINE}).
19289 @end defmac
19291 @defmac AC_INT_16_BITS
19292 @acindex{INT_16_BITS}
19293 @cvindex INT_16_BITS
19294 If the C type @code{int} is 16 bits wide, define @code{INT_16_BITS}.
19295 Use @samp{AC_CHECK_SIZEOF(int)} instead (@pxref{AC_CHECK_SIZEOF}).
19296 @end defmac
19298 @defmac AC_IRIX_SUN
19299 @acindex{IRIX_SUN}
19300 If on @sc{irix} (Silicon Graphics Unix), add @option{-lsun} to output
19301 @code{LIBS}.  If you were using it to get @code{getmntent}, use
19302 @code{AC_FUNC_GETMNTENT} instead.  If you used it for the NIS versions
19303 of the password and group functions, use @samp{AC_CHECK_LIB(sun,
19304 getpwnam)}.  Up to Autoconf 2.13, it used to be
19306 @example
19307 AC_CHECK_LIB([sun], [getmntent], [LIBS="-lsun $LIBS"])
19308 @end example
19310 @noindent
19311 now it is defined as
19313 @example
19314 AC_FUNC_GETMNTENT
19315 AC_CHECK_LIB([sun], [getpwnam])
19316 @end example
19318 @noindent
19319 See @ref{AC_FUNC_GETMNTENT} and @ref{AC_CHECK_LIB}.
19320 @end defmac
19322 @defmac AC_ISC_POSIX
19323 @acindex{ISC_POSIX}
19324 @ovindex LIBS
19325 This macro adds @option{-lcposix} to output variable @code{LIBS} if
19326 necessary for Posix facilities.  Sun dropped support for the obsolete
19327 @sc{interactive} Systems Corporation Unix on 2006-07-23.  New programs
19328 need not use this macro.  It is implemented as
19329 @code{AC_SEARCH_LIBS([strerror], [cposix])} (@pxref{AC_SEARCH_LIBS}).
19330 @end defmac
19332 @defmac AC_LANG_C
19333 @acindex{LANG_C}
19334 Same as @samp{AC_LANG([C])} (@pxref{AC_LANG}).
19335 @end defmac
19337 @defmac AC_LANG_CPLUSPLUS
19338 @acindex{LANG_CPLUSPLUS}
19339 Same as @samp{AC_LANG([C++])} (@pxref{AC_LANG}).
19340 @end defmac
19342 @defmac AC_LANG_FORTRAN77
19343 @acindex{LANG_FORTRAN77}
19344 Same as @samp{AC_LANG([Fortran 77])} (@pxref{AC_LANG}).
19345 @end defmac
19347 @defmac AC_LANG_RESTORE
19348 @acindex{LANG_RESTORE}
19349 Select the @var{language} that is saved on the top of the stack, as set
19350 by @code{AC_LANG_SAVE}, remove it from the stack, and call
19351 @code{AC_LANG(@var{language})}.  @xref{Language Choice}, for the
19352 preferred way to change languages.
19353 @end defmac
19355 @defmac AC_LANG_SAVE
19356 @acindex{LANG_SAVE}
19357 Remember the current language (as set by @code{AC_LANG}) on a stack.
19358 The current language does not change.  @code{AC_LANG_PUSH} is preferred
19359 (@pxref{AC_LANG_PUSH}).
19360 @end defmac
19362 @defmac AC_LINK_FILES (@var{source}@dots{}, @var{dest}@dots{})
19363 @acindex{LINK_FILES}
19364 This is an obsolete version of @code{AC_CONFIG_LINKS}
19365 (@pxref{AC_CONFIG_LINKS}.  An updated version of:
19367 @example
19368 AC_LINK_FILES(config/$machine.h config/$obj_format.h,
19369               host.h            object.h)
19370 @end example
19372 @noindent
19375 @example
19376 AC_CONFIG_LINKS([host.h:config/$machine.h
19377                 object.h:config/$obj_format.h])
19378 @end example
19379 @end defmac
19381 @defmac AC_LN_S
19382 @acindex{LN_S}
19383 Replaced by @code{AC_PROG_LN_S} (@pxref{AC_PROG_LN_S}).
19384 @end defmac
19386 @defmac AC_LONG_64_BITS
19387 @acindex{LONG_64_BITS}
19388 @cvindex LONG_64_BITS
19389 Define @code{LONG_64_BITS} if the C type @code{long int} is 64 bits wide.
19390 Use the generic macro @samp{AC_CHECK_SIZEOF([long int])} instead
19391 (@pxref{AC_CHECK_SIZEOF}).
19392 @end defmac
19394 @defmac AC_LONG_DOUBLE
19395 @acindex{LONG_DOUBLE}
19396 If the C compiler supports a working @code{long double} type with more
19397 range or precision than the @code{double} type, define
19398 @code{HAVE_LONG_DOUBLE}.
19400 You should use @code{AC_TYPE_LONG_DOUBLE} or
19401 @code{AC_TYPE_LONG_DOUBLE_WIDER} instead.  @xref{Particular Types}.
19402 @end defmac
19404 @defmac AC_LONG_FILE_NAMES
19405 @acindex{LONG_FILE_NAMES}
19406 Replaced by
19407 @example
19408 AC_SYS_LONG_FILE_NAMES
19409 @end example
19410 @noindent
19411 @xref{AC_SYS_LONG_FILE_NAMES}.
19412 @end defmac
19414 @defmac AC_MAJOR_HEADER
19415 @acindex{MAJOR_HEADER}
19416 Replaced by @code{AC_HEADER_MAJOR} (@pxref{AC_HEADER_MAJOR}).
19417 @end defmac
19419 @defmac AC_MEMORY_H
19420 @acindex{MEMORY_H}
19421 @cvindex NEED_MEMORY_H
19422 Used to define @code{NEED_MEMORY_H} if the @code{mem} functions were
19423 defined in @file{memory.h}.  Today it is equivalent to
19424 @samp{AC_CHECK_HEADERS([memory.h])} (@pxref{AC_CHECK_HEADERS}).  Adjust
19425 your code to depend upon
19426 @code{HAVE_MEMORY_H}, not @code{NEED_MEMORY_H}; see @ref{Standard
19427 Symbols}.
19428 @end defmac
19430 @defmac AC_MINGW32
19431 @acindex{MINGW32}
19432 Similar to @code{AC_CYGWIN} but checks for the MinGW compiler
19433 environment and sets @code{MINGW32}.  Don't use this macro, the
19434 dignified means to check the nature of the host is using
19435 @code{AC_CANONICAL_HOST} (@pxref{Canonicalizing}).
19436 @end defmac
19438 @defmac AC_MINIX
19439 @acindex{MINIX}
19440 @cvindex _MINIX
19441 @cvindex _POSIX_SOURCE
19442 @cvindex _POSIX_1_SOURCE
19443 This macro is a platform-specific subset of
19444 @code{AC_USE_SYSTEM_EXTENSIONS} (@pxref{AC_USE_SYSTEM_EXTENSIONS}).
19445 @end defmac
19447 @defmac AC_MINUS_C_MINUS_O
19448 @acindex{MINUS_C_MINUS_O}
19449 Replaced by @code{AC_PROG_CC_C_O} (@pxref{AC_PROG_CC_C_O}).
19450 @end defmac
19452 @defmac AC_MMAP
19453 @acindex{MMAP}
19454 Replaced by @code{AC_FUNC_MMAP} (@pxref{AC_FUNC_MMAP}).
19455 @end defmac
19457 @defmac AC_MODE_T
19458 @acindex{MODE_T}
19459 Replaced by @code{AC_TYPE_MODE_T} (@pxref{AC_TYPE_MODE_T}).
19460 @end defmac
19462 @defmac AC_OBJEXT
19463 @acindex{OBJEXT}
19464 @ovindex OBJEXT
19465 Defined the output variable @code{OBJEXT} based on the output of the
19466 compiler, after .c files have been excluded.  Typically set to @samp{o}
19467 if Posix, @samp{obj} if a @acronym{DOS} variant.
19468 Now the compiler checking macros handle
19469 this automatically.
19470 @end defmac
19472 @defmac AC_OBSOLETE (@var{this-macro-name}, @ovar{suggestion})
19473 @acindex{OBSOLETE}
19474 Make M4 print a message to the standard error output warning that
19475 @var{this-macro-name} is obsolete, and giving the file and line number
19476 where it was called.  @var{this-macro-name} should be the name of the
19477 macro that is calling @code{AC_OBSOLETE}.  If @var{suggestion} is given,
19478 it is printed at the end of the warning message; for example, it can be
19479 a suggestion for what to use instead of @var{this-macro-name}.
19481 For instance
19483 @example
19484 AC_OBSOLETE([$0], [; use AC_CHECK_HEADERS(unistd.h) instead])dnl
19485 @end example
19487 @noindent
19488 You are encouraged to use @code{AU_DEFUN} instead, since it gives better
19489 services to the user (@pxref{AU_DEFUN}).
19490 @end defmac
19492 @defmac AC_OFF_T
19493 @acindex{OFF_T}
19494 Replaced by @code{AC_TYPE_OFF_T} (@pxref{AC_TYPE_OFF_T}).
19495 @end defmac
19497 @defmac AC_OUTPUT (@ovar{file}@dots{}, @ovar{extra-cmds}, @ovar{init-cmds})
19498 @acindex{OUTPUT}
19499 The use of @code{AC_OUTPUT} with arguments is deprecated.  This obsoleted
19500 interface is equivalent to:
19502 @example
19503 @group
19504 AC_CONFIG_FILES(@var{file}@dots{})
19505 AC_CONFIG_COMMANDS([default],
19506                    @var{extra-cmds}, @var{init-cmds})
19507 AC_OUTPUT
19508 @end group
19509 @end example
19511 @noindent
19512 See @ref{AC_CONFIG_FILES}, @ref{AC_CONFIG_COMMANDS}, and @ref{AC_OUTPUT}.
19513 @end defmac
19515 @defmac AC_OUTPUT_COMMANDS (@var{extra-cmds}, @ovar{init-cmds})
19516 @acindex{OUTPUT_COMMANDS}
19517 Specify additional shell commands to run at the end of
19518 @file{config.status}, and shell commands to initialize any variables
19519 from @command{configure}.  This macro may be called multiple times.  It is
19520 obsolete, replaced by @code{AC_CONFIG_COMMANDS} (@pxref{AC_CONFIG_COMMANDS}).
19522 Here is an unrealistic example:
19524 @example
19525 fubar=27
19526 AC_OUTPUT_COMMANDS([echo this is extra $fubar, and so on.],
19527                    [fubar=$fubar])
19528 AC_OUTPUT_COMMANDS([echo this is another, extra, bit],
19529                    [echo init bit])
19530 @end example
19532 Aside from the fact that @code{AC_CONFIG_COMMANDS} requires an
19533 additional key, an important difference is that
19534 @code{AC_OUTPUT_COMMANDS} is quoting its arguments twice, unlike
19535 @code{AC_CONFIG_COMMANDS}.  This means that @code{AC_CONFIG_COMMANDS}
19536 can safely be given macro calls as arguments:
19538 @example
19539 AC_CONFIG_COMMANDS(foo, [my_FOO()])
19540 @end example
19542 @noindent
19543 Conversely, where one level of quoting was enough for literal strings
19544 with @code{AC_OUTPUT_COMMANDS}, you need two with
19545 @code{AC_CONFIG_COMMANDS}.  The following lines are equivalent:
19547 @example
19548 @group
19549 AC_OUTPUT_COMMANDS([echo "Square brackets: []"])
19550 AC_CONFIG_COMMANDS([default], [[echo "Square brackets: []"]])
19551 @end group
19552 @end example
19553 @end defmac
19555 @defmac AC_PID_T
19556 @acindex{PID_T}
19557 Replaced by @code{AC_TYPE_PID_T} (@pxref{AC_TYPE_PID_T}).
19558 @end defmac
19560 @defmac AC_PREFIX
19561 @acindex{PREFIX}
19562 Replaced by @code{AC_PREFIX_PROGRAM} (@pxref{AC_PREFIX_PROGRAM}).
19563 @end defmac
19565 @defmac AC_PROGRAMS_CHECK
19566 @acindex{PROGRAMS_CHECK}
19567 Replaced by @code{AC_CHECK_PROGS} (@pxref{AC_CHECK_PROGS}).
19568 @end defmac
19570 @defmac AC_PROGRAMS_PATH
19571 @acindex{PROGRAMS_PATH}
19572 Replaced by @code{AC_PATH_PROGS} (@pxref{AC_PATH_PROGS}).
19573 @end defmac
19575 @defmac AC_PROGRAM_CHECK
19576 @acindex{PROGRAM_CHECK}
19577 Replaced by @code{AC_CHECK_PROG} (@pxref{AC_CHECK_PROG}).
19578 @end defmac
19580 @defmac AC_PROGRAM_EGREP
19581 @acindex{PROGRAM_EGREP}
19582 Replaced by @code{AC_EGREP_CPP} (@pxref{AC_EGREP_CPP}).
19583 @end defmac
19585 @defmac AC_PROGRAM_PATH
19586 @acindex{PROGRAM_PATH}
19587 Replaced by @code{AC_PATH_PROG} (@pxref{AC_PATH_PROG}).
19588 @end defmac
19590 @defmac AC_REMOTE_TAPE
19591 @acindex{REMOTE_TAPE}
19592 Removed because of limited usefulness.
19593 @end defmac
19595 @defmac AC_RESTARTABLE_SYSCALLS
19596 @acindex{RESTARTABLE_SYSCALLS}
19597 This macro was renamed @code{AC_SYS_RESTARTABLE_SYSCALLS}.  However,
19598 these days portable programs should use @code{sigaction} with
19599 @code{SA_RESTART} if they want restartable system calls.  They should
19600 not rely on @code{HAVE_RESTARTABLE_SYSCALLS}, since nowadays whether a
19601 system call is restartable is a dynamic issue, not a configuration-time
19602 issue.
19603 @end defmac
19605 @defmac AC_RETSIGTYPE
19606 @acindex{RETSIGTYPE}
19607 Replaced by @code{AC_TYPE_SIGNAL} (@pxref{AC_TYPE_SIGNAL}), which itself
19608 is obsolete when assuming C89 or better.
19609 @end defmac
19611 @defmac AC_RSH
19612 @acindex{RSH}
19613 Removed because of limited usefulness.
19614 @end defmac
19616 @defmac AC_SCO_INTL
19617 @acindex{SCO_INTL}
19618 @ovindex LIBS
19619 If on SCO Unix, add @option{-lintl} to output variable @code{LIBS}.  This
19620 macro used to do this:
19622 @example
19623 AC_CHECK_LIB([intl], [strftime], [LIBS="-lintl $LIBS"])
19624 @end example
19626 @noindent
19627 Now it just calls @code{AC_FUNC_STRFTIME} instead (@pxref{AC_FUNC_STRFTIME}).
19628 @end defmac
19630 @defmac AC_SETVBUF_REVERSED
19631 @acindex{SETVBUF_REVERSED}
19632 Replaced by
19633 @example
19634 AC_FUNC_SETVBUF_REVERSED
19635 @end example
19636 @noindent
19637 @xref{AC_FUNC_SETVBUF_REVERSED}.
19638 @end defmac
19640 @defmac AC_SET_MAKE
19641 @acindex{SET_MAKE}
19642 Replaced by @code{AC_PROG_MAKE_SET} (@pxref{AC_PROG_MAKE_SET}).
19643 @end defmac
19645 @defmac AC_SIZEOF_TYPE
19646 @acindex{SIZEOF_TYPE}
19647 Replaced by @code{AC_CHECK_SIZEOF} (@pxref{AC_CHECK_SIZEOF}).
19648 @end defmac
19650 @defmac AC_SIZE_T
19651 @acindex{SIZE_T}
19652 Replaced by @code{AC_TYPE_SIZE_T} (@pxref{AC_TYPE_SIZE_T}).
19653 @end defmac
19655 @defmac AC_STAT_MACROS_BROKEN
19656 @acindex{STAT_MACROS_BROKEN}
19657 Replaced by @code{AC_HEADER_STAT} (@pxref{AC_HEADER_STAT}).
19658 @end defmac
19660 @defmac AC_STDC_HEADERS
19661 @acindex{STDC_HEADERS}
19662 Replaced by @code{AC_HEADER_STDC} (@pxref{AC_HEADER_STDC}).
19663 @end defmac
19665 @defmac AC_STRCOLL
19666 @acindex{STRCOLL}
19667 Replaced by @code{AC_FUNC_STRCOLL} (@pxref{AC_FUNC_STRCOLL}).
19668 @end defmac
19670 @defmac AC_STRUCT_ST_BLKSIZE
19671 @acindex{STRUCT_ST_BLKSIZE}
19672 @cvindex HAVE_STRUCT_STAT_ST_BLKSIZE
19673 @cvindex HAVE_ST_BLKSIZE
19674 If @code{struct stat} contains an @code{st_blksize} member, define
19675 @code{HAVE_STRUCT_STAT_ST_BLKSIZE}.  The former name,
19676 @code{HAVE_ST_BLKSIZE} is to be avoided, as its support will cease in
19677 the future.  This macro is obsoleted, and should be replaced by
19679 @example
19680 AC_CHECK_MEMBERS([struct stat.st_blksize])
19681 @end example
19682 @noindent
19683 @xref{AC_CHECK_MEMBERS}.
19684 @end defmac
19686 @defmac AC_STRUCT_ST_RDEV
19687 @acindex{STRUCT_ST_RDEV}
19688 @cvindex HAVE_ST_RDEV
19689 @cvindex HAVE_STRUCT_STAT_ST_RDEV
19690 If @code{struct stat} contains an @code{st_rdev} member, define
19691 @code{HAVE_STRUCT_STAT_ST_RDEV}.  The former name for this macro,
19692 @code{HAVE_ST_RDEV}, is to be avoided as it will cease to be supported
19693 in the future.  Actually, even the new macro is obsolete and should be
19694 replaced by:
19695 @example
19696 AC_CHECK_MEMBERS([struct stat.st_rdev])
19697 @end example
19698 @noindent
19699 @xref{AC_CHECK_MEMBERS}.
19700 @end defmac
19702 @defmac AC_ST_BLKSIZE
19703 @acindex{ST_BLKSIZE}
19704 Replaced by @code{AC_CHECK_MEMBERS} (@pxref{AC_CHECK_MEMBERS}).
19705 @end defmac
19707 @defmac AC_ST_BLOCKS
19708 @acindex{ST_BLOCKS}
19709 Replaced by @code{AC_STRUCT_ST_BLOCKS} (@pxref{AC_STRUCT_ST_BLOCKS}).
19710 @end defmac
19712 @defmac AC_ST_RDEV
19713 @acindex{ST_RDEV}
19714 Replaced by @code{AC_CHECK_MEMBERS} (@pxref{AC_CHECK_MEMBERS}).
19715 @end defmac
19717 @defmac AC_SYS_RESTARTABLE_SYSCALLS
19718 @acindex{SYS_RESTARTABLE_SYSCALLS}
19719 @cvindex HAVE_RESTARTABLE_SYSCALLS
19720 If the system automatically restarts a system call that is interrupted
19721 by a signal, define @code{HAVE_RESTARTABLE_SYSCALLS}.  This macro does
19722 not check whether system calls are restarted in general---it checks whether a
19723 signal handler installed with @code{signal} (but not @code{sigaction})
19724 causes system calls to be restarted.  It does not check whether system calls
19725 can be restarted when interrupted by signals that have no handler.
19727 These days portable programs should use @code{sigaction} with
19728 @code{SA_RESTART} if they want restartable system calls.  They should
19729 not rely on @code{HAVE_RESTARTABLE_SYSCALLS}, since nowadays whether a
19730 system call is restartable is a dynamic issue, not a configuration-time
19731 issue.
19732 @end defmac
19734 @defmac AC_SYS_SIGLIST_DECLARED
19735 @acindex{SYS_SIGLIST_DECLARED}
19736 This macro was renamed @code{AC_DECL_SYS_SIGLIST}.  However, even that
19737 name is obsolete, as the same functionality is now acheived via
19738 @code{AC_CHECK_DECLS} (@pxref{AC_CHECK_DECLS}).
19739 @end defmac
19741 @defmac AC_TEST_CPP
19742 @acindex{TEST_CPP}
19743 This macro was renamed @code{AC_TRY_CPP}, which in turn was replaced by
19744 @code{AC_PREPROC_IFELSE} (@pxref{AC_PREPROC_IFELSE}).
19745 @end defmac
19747 @defmac AC_TEST_PROGRAM
19748 @acindex{TEST_PROGRAM}
19749 This macro was renamed @code{AC_TRY_RUN}, which in turn was replaced by
19750 @code{AC_RUN_IFELSE} (@pxref{AC_RUN_IFELSE}).
19751 @end defmac
19753 @defmac AC_TIMEZONE
19754 @acindex{TIMEZONE}
19755 Replaced by @code{AC_STRUCT_TIMEZONE} (@pxref{AC_STRUCT_TIMEZONE}).
19756 @end defmac
19758 @defmac AC_TIME_WITH_SYS_TIME
19759 @acindex{TIME_WITH_SYS_TIME}
19760 Replaced by @code{AC_HEADER_TIME} (@pxref{AC_HEADER_TIME}).
19761 @end defmac
19763 @defmac AC_TRY_COMPILE (@var{includes}, @var{function-body}, @
19764   @ovar{action-if-true}, @ovar{action-if-false})
19765 @acindex{TRY_COMPILE}
19766 Same as:
19768 @example
19769 AC_COMPILE_IFELSE(
19770   [AC_LANG_PROGRAM([[@var{includes}]],
19771      [[@var{function-body}]])],
19772   [@var{action-if-true}],
19773   [@var{action-if-false}])
19774 @end example
19776 @noindent
19777 @xref{Running the Compiler}.
19779 This macro double quotes both @var{includes} and @var{function-body}.
19781 For C and C++, @var{includes} is any @code{#include} statements needed
19782 by the code in @var{function-body} (@var{includes} is ignored if
19783 the currently selected language is Fortran or Fortran 77).  The compiler
19784 and compilation flags are determined by the current language
19785 (@pxref{Language Choice}).
19786 @end defmac
19788 @defmac AC_TRY_CPP (@var{input}, @ovar{action-if-true}, @ovar{action-if-false})
19789 @acindex{TRY_CPP}
19790 Same as:
19792 @example
19793 AC_PREPROC_IFELSE(
19794   [AC_LANG_SOURCE([[@var{input}]])],
19795   [@var{action-if-true}],
19796   [@var{action-if-false}])
19797 @end example
19799 @noindent
19800 @xref{Running the Preprocessor}.
19802 This macro double quotes the @var{input}.
19803 @end defmac
19805 @defmac AC_TRY_LINK (@var{includes}, @var{function-body}, @
19806   @ovar{action-if-true}, @ovar{action-if-false})
19807 @acindex{TRY_LINK}
19808 Same as:
19810 @example
19811 AC_LINK_IFELSE(
19812   [AC_LANG_PROGRAM([[@var{includes}]],
19813      [[@var{function-body}]])],
19814   [@var{action-if-true}],
19815   [@var{action-if-false}])
19816 @end example
19818 @noindent
19819 @xref{Running the Compiler}.
19821 This macro double quotes both @var{includes} and @var{function-body}.
19823 Depending on the current language (@pxref{Language Choice}), create a
19824 test program to see whether a function whose body consists of
19825 @var{function-body} can be compiled and linked.  If the file compiles
19826 and links successfully, run shell commands @var{action-if-found},
19827 otherwise run @var{action-if-not-found}.
19829 This macro double quotes both @var{includes} and @var{function-body}.
19831 For C and C++, @var{includes} is any @code{#include} statements needed
19832 by the code in @var{function-body} (@var{includes} is ignored if
19833 the currently selected language is Fortran or Fortran 77).  The compiler
19834 and compilation flags are determined by the current language
19835 (@pxref{Language Choice}), and in addition @code{LDFLAGS} and
19836 @code{LIBS} are used for linking.
19837 @end defmac
19839 @defmac AC_TRY_LINK_FUNC (@var{function}, @ovar{action-if-found}, @
19840   @ovar{action-if-not-found})
19841 @acindex{TRY_LINK_FUNC}
19842 This macro is equivalent to
19843 @example
19844 AC_LINK_IFELSE([AC_LANG_CALL([], [@var{function}])],
19845   [@var{action-if-found}], [@var{action-if-not-found}])
19846 @end example
19847 @noindent
19848 @xref{AC_LINK_IFELSE}.
19849 @end defmac
19851 @defmac AC_TRY_RUN (@var{program}, @ovar{action-if-true}, @
19852   @ovar{action-if-false}, @ovar{action-if-cross-compiling})
19853 @acindex{TRY_RUN}
19854 Same as:
19856 @example
19857 AC_RUN_IFELSE(
19858   [AC_LANG_SOURCE([[@var{program}]])],
19859   [@var{action-if-true}],
19860   [@var{action-if-false}],
19861   [@var{action-if-cross-compiling}])
19862 @end example
19864 @noindent
19865 @xref{Runtime}.
19866 @end defmac
19868 @anchor{AC_TYPE_SIGNAL}
19869 @defmac AC_TYPE_SIGNAL
19870 @acindex{TYPE_SIGNAL}
19871 @cvindex RETSIGTYPE
19872 @hdrindex{signal.h}
19873 If @file{signal.h} declares @code{signal} as returning a pointer to a
19874 function returning @code{void}, define @code{RETSIGTYPE} to be
19875 @code{void}; otherwise, define it to be @code{int}.  These days, it is
19876 portable to assume C89, and that signal handlers return @code{void},
19877 without needing to use this macro or @code{RETSIGTYPE}.
19879 When targetting older K&R C, it is possible to define signal handlers as
19880 returning type @code{RETSIGTYPE}, and omit a return statement:
19882 @example
19883 @group
19884 RETSIGTYPE
19885 hup_handler ()
19887 @dots{}
19889 @end group
19890 @end example
19891 @end defmac
19893 @defmac AC_UID_T
19894 @acindex{UID_T}
19895 Replaced by @code{AC_TYPE_UID_T} (@pxref{AC_TYPE_UID_T}).
19896 @end defmac
19898 @defmac AC_UNISTD_H
19899 @acindex{UNISTD_H}
19900 Same as @samp{AC_CHECK_HEADERS([unistd.h])} (@pxref{AC_CHECK_HEADERS}).
19901 @end defmac
19903 @defmac AC_USG
19904 @acindex{USG}
19905 @cvindex USG
19906 Define @code{USG} if the @acronym{BSD} string functions are defined in
19907 @file{strings.h}.  You should no longer depend upon @code{USG}, but on
19908 @code{HAVE_STRING_H}; see @ref{Standard Symbols}.
19909 @end defmac
19911 @defmac AC_UTIME_NULL
19912 @acindex{UTIME_NULL}
19913 Replaced by @code{AC_FUNC_UTIME_NULL} (@pxref{AC_FUNC_UTIME_NULL}).
19914 @end defmac
19916 @defmac AC_VALIDATE_CACHED_SYSTEM_TUPLE (@ovar{cmd})
19917 @acindex{VALIDATE_CACHED_SYSTEM_TUPLE}
19918 If the cache file is inconsistent with the current host, target and
19919 build system types, it used to execute @var{cmd} or print a default
19920 error message.  This is now handled by default.
19921 @end defmac
19923 @defmac AC_VERBOSE (@var{result-description})
19924 @acindex{VERBOSE}
19925 Replaced by @code{AC_MSG_RESULT} (@pxref{AC_MSG_RESULT}).
19926 @end defmac
19928 @defmac AC_VFORK
19929 @acindex{VFORK}
19930 Replaced by @code{AC_FUNC_FORK} (@pxref{AC_FUNC_FORK}).
19931 @end defmac
19933 @defmac AC_VPRINTF
19934 @acindex{VPRINTF}
19935 Replaced by @code{AC_FUNC_VPRINTF} (@pxref{AC_FUNC_VPRINTF}).
19936 @end defmac
19938 @defmac AC_WAIT3
19939 @acindex{WAIT3}
19940 This macro was renamed @code{AC_FUNC_WAIT3}.  However, these days
19941 portable programs should use @code{waitpid}, not @code{wait3}, as
19942 @code{wait3} has been removed from Posix.
19943 @end defmac
19945 @defmac AC_WARN
19946 @acindex{WARN}
19947 Replaced by @code{AC_MSG_WARN} (@pxref{AC_MSG_WARN}).
19948 @end defmac
19950 @defmac AC_WITH (@var{package}, @var{action-if-given}, @
19951   @ovar{action-if-not-given})
19952 @acindex{WITH}
19953 This is an obsolete version of @code{AC_ARG_WITH} that does not
19954 support providing a help string (@pxref{AC_ARG_WITH}).
19955 @end defmac
19957 @defmac AC_WORDS_BIGENDIAN
19958 @acindex{WORDS_BIGENDIAN}
19959 Replaced by @code{AC_C_BIGENDIAN} (@pxref{AC_C_BIGENDIAN}).
19960 @end defmac
19962 @defmac AC_XENIX_DIR
19963 @acindex{XENIX_DIR}
19964 @ovindex LIBS
19965 This macro used to add @option{-lx} to output variable @code{LIBS} if on
19966 Xenix.  Also, if @file{dirent.h} is being checked for, added
19967 @option{-ldir} to @code{LIBS}.  Now it is merely an alias of
19968 @code{AC_HEADER_DIRENT} instead, plus some code to detect whether
19969 running @sc{xenix} on which you should not depend:
19971 @example
19972 AC_MSG_CHECKING([for Xenix])
19973 AC_EGREP_CPP([yes],
19974 [#if defined M_XENIX && !defined M_UNIX
19975   yes
19976 #endif],
19977              [AC_MSG_RESULT([yes]); XENIX=yes],
19978              [AC_MSG_RESULT([no]); XENIX=])
19979 @end example
19980 @noindent
19981 Don't use this macro, the dignified means to check the nature of the
19982 host is using @code{AC_CANONICAL_HOST} (@pxref{Canonicalizing}).
19983 @end defmac
19985 @defmac AC_YYTEXT_POINTER
19986 @acindex{YYTEXT_POINTER}
19987 This macro was renamed @code{AC_DECL_YYTEXT}, which in turn was
19988 integrated into @code{AC_PROG_LEX} (@pxref{AC_PROG_LEX}).
19989 @end defmac
19991 @node Autoconf 1
19992 @section Upgrading From Version 1
19993 @cindex Upgrading autoconf
19994 @cindex Autoconf upgrading
19996 Autoconf version 2 is mostly backward compatible with version 1.
19997 However, it introduces better ways to do some things, and doesn't
19998 support some of the ugly things in version 1.  So, depending on how
19999 sophisticated your @file{configure.ac} files are, you might have to do
20000 some manual work in order to upgrade to version 2.  This chapter points
20001 out some problems to watch for when upgrading.  Also, perhaps your
20002 @command{configure} scripts could benefit from some of the new features in
20003 version 2; the changes are summarized in the file @file{NEWS} in the
20004 Autoconf distribution.
20006 @menu
20007 * Changed File Names::          Files you might rename
20008 * Changed Makefiles::           New things to put in @file{Makefile.in}
20009 * Changed Macros::              Macro calls you might replace
20010 * Changed Results::             Changes in how to check test results
20011 * Changed Macro Writing::       Better ways to write your own macros
20012 @end menu
20014 @node Changed File Names
20015 @subsection Changed File Names
20017 If you have an @file{aclocal.m4} installed with Autoconf (as opposed to
20018 in a particular package's source directory), you must rename it to
20019 @file{acsite.m4}.  @xref{autoconf Invocation}.
20021 If you distribute @file{install.sh} with your package, rename it to
20022 @file{install-sh} so @command{make} builtin rules don't inadvertently
20023 create a file called @file{install} from it.  @code{AC_PROG_INSTALL}
20024 looks for the script under both names, but it is best to use the new name.
20026 If you were using @file{config.h.top}, @file{config.h.bot}, or
20027 @file{acconfig.h}, you still can, but you have less clutter if you
20028 use the @code{AH_} macros.  @xref{Autoheader Macros}.
20030 @node Changed Makefiles
20031 @subsection Changed Makefiles
20033 Add @samp{@@CFLAGS@@}, @samp{@@CPPFLAGS@@}, and @samp{@@LDFLAGS@@} in
20034 your @file{Makefile.in} files, so they can take advantage of the values
20035 of those variables in the environment when @command{configure} is run.
20036 Doing this isn't necessary, but it's a convenience for users.
20038 Also add @samp{@@configure_input@@} in a comment to each input file for
20039 @code{AC_OUTPUT}, so that the output files contain a comment saying
20040 they were produced by @command{configure}.  Automatically selecting the
20041 right comment syntax for all the kinds of files that people call
20042 @code{AC_OUTPUT} on became too much work.
20044 Add @file{config.log} and @file{config.cache} to the list of files you
20045 remove in @code{distclean} targets.
20047 If you have the following in @file{Makefile.in}:
20049 @example
20050 prefix = /usr/local
20051 exec_prefix = $(prefix)
20052 @end example
20054 @noindent
20055 you must change it to:
20057 @example
20058 prefix = @@prefix@@
20059 exec_prefix = @@exec_prefix@@
20060 @end example
20062 @noindent
20063 The old behavior of replacing those variables without @samp{@@}
20064 characters around them has been removed.
20066 @node Changed Macros
20067 @subsection Changed Macros
20069 Many of the macros were renamed in Autoconf version 2.  You can still
20070 use the old names, but the new ones are clearer, and it's easier to find
20071 the documentation for them.  @xref{Obsolete Macros}, for a table showing the
20072 new names for the old macros.  Use the @command{autoupdate} program to
20073 convert your @file{configure.ac} to using the new macro names.
20074 @xref{autoupdate Invocation}.
20076 Some macros have been superseded by similar ones that do the job better,
20077 but are not call-compatible.  If you get warnings about calling obsolete
20078 macros while running @command{autoconf}, you may safely ignore them, but
20079 your @command{configure} script generally works better if you follow
20080 the advice that is printed about what to replace the obsolete macros with.  In
20081 particular, the mechanism for reporting the results of tests has
20082 changed.  If you were using @command{echo} or @code{AC_VERBOSE} (perhaps
20083 via @code{AC_COMPILE_CHECK}), your @command{configure} script's output
20084 looks better if you switch to @code{AC_MSG_CHECKING} and
20085 @code{AC_MSG_RESULT}.  @xref{Printing Messages}.  Those macros work best
20086 in conjunction with cache variables.  @xref{Caching Results}.
20090 @node Changed Results
20091 @subsection Changed Results
20093 If you were checking the results of previous tests by examining the
20094 shell variable @code{DEFS}, you need to switch to checking the values of
20095 the cache variables for those tests.  @code{DEFS} no longer exists while
20096 @command{configure} is running; it is only created when generating output
20097 files.  This difference from version 1 is because properly quoting the
20098 contents of that variable turned out to be too cumbersome and
20099 inefficient to do every time @code{AC_DEFINE} is called.  @xref{Cache
20100 Variable Names}.
20102 For example, here is a @file{configure.ac} fragment written for Autoconf
20103 version 1:
20105 @example
20106 AC_HAVE_FUNCS(syslog)
20107 case "$DEFS" in
20108 *-DHAVE_SYSLOG*) ;;
20109 *) # syslog is not in the default libraries.  See if it's in some other.
20110   saved_LIBS="$LIBS"
20111   for lib in bsd socket inet; do
20112     AC_CHECKING(for syslog in -l$lib)
20113     LIBS="-l$lib $saved_LIBS"
20114     AC_HAVE_FUNCS(syslog)
20115     case "$DEFS" in
20116     *-DHAVE_SYSLOG*) break ;;
20117     *) ;;
20118     esac
20119     LIBS="$saved_LIBS"
20120   done ;;
20121 esac
20122 @end example
20124 Here is a way to write it for version 2:
20126 @example
20127 AC_CHECK_FUNCS([syslog])
20128 if test $ac_cv_func_syslog = no; then
20129   # syslog is not in the default libraries.  See if it's in some other.
20130   for lib in bsd socket inet; do
20131     AC_CHECK_LIB([$lib], [syslog], [AC_DEFINE([HAVE_SYSLOG])
20132       LIBS="-l$lib $LIBS"; break])
20133   done
20135 @end example
20137 If you were working around bugs in @code{AC_DEFINE_UNQUOTED} by adding
20138 backslashes before quotes, you need to remove them.  It now works
20139 predictably, and does not treat quotes (except back quotes) specially.
20140 @xref{Setting Output Variables}.
20142 All of the Boolean shell variables set by Autoconf macros now use
20143 @samp{yes} for the true value.  Most of them use @samp{no} for false,
20144 though for backward compatibility some use the empty string instead.  If
20145 you were relying on a shell variable being set to something like 1 or
20146 @samp{t} for true, you need to change your tests.
20148 @node Changed Macro Writing
20149 @subsection Changed Macro Writing
20151 When defining your own macros, you should now use @code{AC_DEFUN}
20152 instead of @code{define}.  @code{AC_DEFUN} automatically calls
20153 @code{AC_PROVIDE} and ensures that macros called via @code{AC_REQUIRE}
20154 do not interrupt other macros, to prevent nested @samp{checking@dots{}}
20155 messages on the screen.  There's no actual harm in continuing to use the
20156 older way, but it's less convenient and attractive.  @xref{Macro
20157 Definitions}.
20159 You probably looked at the macros that came with Autoconf as a guide for
20160 how to do things.  It would be a good idea to take a look at the new
20161 versions of them, as the style is somewhat improved and they take
20162 advantage of some new features.
20164 If you were doing tricky things with undocumented Autoconf internals
20165 (macros, variables, diversions), check whether you need to change
20166 anything to account for changes that have been made.  Perhaps you can
20167 even use an officially supported technique in version 2 instead of
20168 kludging.  Or perhaps not.
20170 To speed up your locally written feature tests, add caching to them.
20171 See whether any of your tests are of general enough usefulness to
20172 encapsulate them into macros that you can share.
20175 @node Autoconf 2.13
20176 @section Upgrading From Version 2.13
20177 @cindex Upgrading autoconf
20178 @cindex Autoconf upgrading
20180 The introduction of the previous section (@pxref{Autoconf 1}) perfectly
20181 suits this section@enddots{}
20183 @quotation
20184 Autoconf version 2.50 is mostly backward compatible with version 2.13.
20185 However, it introduces better ways to do some things, and doesn't
20186 support some of the ugly things in version 2.13.  So, depending on how
20187 sophisticated your @file{configure.ac} files are, you might have to do
20188 some manual work in order to upgrade to version 2.50.  This chapter
20189 points out some problems to watch for when upgrading.  Also, perhaps
20190 your @command{configure} scripts could benefit from some of the new
20191 features in version 2.50; the changes are summarized in the file
20192 @file{NEWS} in the Autoconf distribution.
20193 @end quotation
20195 @menu
20196 * Changed Quotation::           Broken code which used to work
20197 * New Macros::                  Interaction with foreign macros
20198 * Hosts and Cross-Compilation::  Bugward compatibility kludges
20199 * AC_LIBOBJ vs LIBOBJS::        LIBOBJS is a forbidden token
20200 * AC_FOO_IFELSE vs AC_TRY_FOO::  A more generic scheme for testing sources
20201 @end menu
20203 @node Changed Quotation
20204 @subsection Changed Quotation
20206 The most important changes are invisible to you: the implementation of
20207 most macros have completely changed.  This allowed more factorization of
20208 the code, better error messages, a higher uniformity of the user's
20209 interface etc.  Unfortunately, as a side effect, some construct which
20210 used to (miraculously) work might break starting with Autoconf 2.50.
20211 The most common culprit is bad quotation.
20213 For instance, in the following example, the message is not properly
20214 quoted:
20216 @example
20217 AC_INIT
20218 AC_CHECK_HEADERS(foo.h, ,
20219   AC_MSG_ERROR(cannot find foo.h, bailing out))
20220 AC_OUTPUT
20221 @end example
20223 @noindent
20224 Autoconf 2.13 simply ignores it:
20226 @example
20227 $ @kbd{autoconf-2.13; ./configure --silent}
20228 creating cache ./config.cache
20229 configure: error: cannot find foo.h
20231 @end example
20233 @noindent
20234 while Autoconf 2.50 produces a broken @file{configure}:
20236 @example
20237 $ @kbd{autoconf-2.50; ./configure --silent}
20238 configure: error: cannot find foo.h
20239 ./configure: exit: bad non-numeric arg `bailing'
20240 ./configure: exit: bad non-numeric arg `bailing'
20242 @end example
20244 The message needs to be quoted, and the @code{AC_MSG_ERROR} invocation
20245 too!
20247 @example
20248 AC_INIT([Example], [1.0], [bug-example@@example.org])
20249 AC_CHECK_HEADERS([foo.h], [],
20250   [AC_MSG_ERROR([cannot find foo.h, bailing out])])
20251 AC_OUTPUT
20252 @end example
20254 Many many (and many more) Autoconf macros were lacking proper quotation,
20255 including no less than@dots{} @code{AC_DEFUN} itself!
20257 @example
20258 $ @kbd{cat configure.in}
20259 AC_DEFUN([AC_PROG_INSTALL],
20260 [# My own much better version
20262 AC_INIT
20263 AC_PROG_INSTALL
20264 AC_OUTPUT
20265 $ @kbd{autoconf-2.13}
20266 autoconf: Undefined macros:
20267 ***BUG in Autoconf--please report*** AC_FD_MSG
20268 ***BUG in Autoconf--please report*** AC_EPI
20269 configure.in:1:AC_DEFUN([AC_PROG_INSTALL],
20270 configure.in:5:AC_PROG_INSTALL
20271 $ @kbd{autoconf-2.50}
20273 @end example
20276 @node New Macros
20277 @subsection New Macros
20279 @cindex undefined macro
20280 @cindex @code{_m4_divert_diversion}
20282 While Autoconf was relatively dormant in the late 1990s, Automake
20283 provided Autoconf-like macros for a while.  Starting with Autoconf 2.50
20284 in 2001, Autoconf provided
20285 versions of these macros, integrated in the @code{AC_} namespace,
20286 instead of @code{AM_}.  But in order to ease the upgrading via
20287 @command{autoupdate}, bindings to such @code{AM_} macros are provided.
20289 Unfortunately older versions of Automake (e.g., Automake 1.4)
20290 did not quote the names of these macros.
20291 Therefore, when @command{m4} finds something like
20292 @samp{AC_DEFUN(AM_TYPE_PTRDIFF_T, @dots{})} in @file{aclocal.m4},
20293 @code{AM_TYPE_PTRDIFF_T} is
20294 expanded, replaced with its Autoconf definition.
20296 Fortunately Autoconf catches pre-@code{AC_INIT} expansions, and
20297 complains, in its own words:
20299 @example
20300 $ @kbd{cat configure.ac}
20301 AC_INIT([Example], [1.0], [bug-example@@example.org])
20302 AM_TYPE_PTRDIFF_T
20303 $ @kbd{aclocal-1.4}
20304 $ @kbd{autoconf}
20305 aclocal.m4:17: error: m4_defn: undefined macro: _m4_divert_diversion
20306 aclocal.m4:17: the top level
20307 autom4te: m4 failed with exit status: 1
20309 @end example
20311 Modern versions of Automake no longer define most of these
20312 macros, and properly quote the names of the remaining macros.
20313 If you must use an old Automake, do not depend upon macros from Automake
20314 as it is simply not its job
20315 to provide macros (but the one it requires itself):
20317 @example
20318 $ @kbd{cat configure.ac}
20319 AC_INIT([Example], [1.0], [bug-example@@example.org])
20320 AM_TYPE_PTRDIFF_T
20321 $ @kbd{rm aclocal.m4}
20322 $ @kbd{autoupdate}
20323 autoupdate: `configure.ac' is updated
20324 $ @kbd{cat configure.ac}
20325 AC_INIT([Example], [1.0], [bug-example@@example.org])
20326 AC_CHECK_TYPES([ptrdiff_t])
20327 $ @kbd{aclocal-1.4}
20328 $ @kbd{autoconf}
20330 @end example
20333 @node Hosts and Cross-Compilation
20334 @subsection Hosts and Cross-Compilation
20335 @cindex Cross compilation
20337 Based on the experience of compiler writers, and after long public
20338 debates, many aspects of the cross-compilation chain have changed:
20340 @itemize @minus
20341 @item
20342 the relationship between the build, host, and target architecture types,
20344 @item
20345 the command line interface for specifying them to @command{configure},
20347 @item
20348 the variables defined in @command{configure},
20350 @item
20351 the enabling of cross-compilation mode.
20352 @end itemize
20354 @sp 1
20356 The relationship between build, host, and target have been cleaned up:
20357 the chain of default is now simply: target defaults to host, host to
20358 build, and build to the result of @command{config.guess}.  Nevertheless,
20359 in order to ease the transition from 2.13 to 2.50, the following
20360 transition scheme is implemented.  @emph{Do not rely on it}, as it will
20361 be completely disabled in a couple of releases (we cannot keep it, as it
20362 proves to cause more problems than it cures).
20364 They all default to the result of running @command{config.guess}, unless
20365 you specify either @option{--build} or @option{--host}.  In this case,
20366 the default becomes the system type you specified.  If you specify both,
20367 and they're different, @command{configure} enters cross compilation
20368 mode, so it doesn't run any tests that require execution.
20370 Hint: if you mean to override the result of @command{config.guess},
20371 prefer @option{--build} over @option{--host}.  In the future,
20372 @option{--host} will not override the name of the build system type.
20373 Whenever you specify @option{--host}, be sure to specify @option{--build}
20374 too.
20376 @sp 1
20378 For backward compatibility, @command{configure} accepts a system
20379 type as an option by itself.  Such an option overrides the
20380 defaults for build, host, and target system types.  The following
20381 configure statement configures a cross toolchain that runs on
20382 Net@acronym{BSD}/alpha but generates code for @acronym{GNU} Hurd/sparc,
20383 which is also the build platform.
20385 @example
20386 ./configure --host=alpha-netbsd sparc-gnu
20387 @end example
20389 @sp 1
20391 In Autoconf 2.13 and before, the variables @code{build}, @code{host},
20392 and @code{target} had a different semantics before and after the
20393 invocation of @code{AC_CANONICAL_BUILD} etc.  Now, the argument of
20394 @option{--build} is strictly copied into @code{build_alias}, and is left
20395 empty otherwise.  After the @code{AC_CANONICAL_BUILD}, @code{build} is
20396 set to the canonicalized build type.  To ease the transition, before,
20397 its contents is the same as that of @code{build_alias}.  Do @emph{not}
20398 rely on this broken feature.
20400 For consistency with the backward compatibility scheme exposed above,
20401 when @option{--host} is specified but @option{--build} isn't, the build
20402 system is assumed to be the same as @option{--host}, and
20403 @samp{build_alias} is set to that value.  Eventually, this
20404 historically incorrect behavior will go away.
20406 @sp 1
20408 The former scheme to enable cross-compilation proved to cause more harm
20409 than good, in particular, it used to be triggered too easily, leaving
20410 regular end users puzzled in front of cryptic error messages.
20411 @command{configure} could even enter cross-compilation mode only
20412 because the compiler was not functional.  This is mainly because
20413 @command{configure} used to try to detect cross-compilation, instead of
20414 waiting for an explicit flag from the user.
20416 Now, @command{configure} enters cross-compilation mode if and only if
20417 @option{--host} is passed.
20419 That's the short documentation.  To ease the transition between 2.13 and
20420 its successors, a more complicated scheme is implemented.  @emph{Do not
20421 rely on the following}, as it will be removed in the near future.
20423 If you specify @option{--host}, but not @option{--build}, when
20424 @command{configure} performs the first compiler test it tries to run
20425 an executable produced by the compiler.  If the execution fails, it
20426 enters cross-compilation mode.  This is fragile.  Moreover, by the time
20427 the compiler test is performed, it may be too late to modify the
20428 build-system type: other tests may have already been performed.
20429 Therefore, whenever you specify @option{--host}, be sure to specify
20430 @option{--build} too.
20432 @example
20433 ./configure --build=i686-pc-linux-gnu --host=m68k-coff
20434 @end example
20436 @noindent
20437 enters cross-compilation mode.  The former interface, which
20438 consisted in setting the compiler to a cross-compiler without informing
20439 @command{configure} is obsolete.  For instance, @command{configure}
20440 fails if it can't run the code generated by the specified compiler if you
20441 configure as follows:
20443 @example
20444 ./configure CC=m68k-coff-gcc
20445 @end example
20448 @node AC_LIBOBJ vs LIBOBJS
20449 @subsection @code{AC_LIBOBJ} vs.@: @code{LIBOBJS}
20451 Up to Autoconf 2.13, the replacement of functions was triggered via the
20452 variable @code{LIBOBJS}.  Since Autoconf 2.50, the macro
20453 @code{AC_LIBOBJ} should be used instead (@pxref{Generic Functions}).
20454 Starting at Autoconf 2.53, the use of @code{LIBOBJS} is an error.
20456 This change is mandated by the unification of the @acronym{GNU} Build System
20457 components.  In particular, the various fragile techniques used to parse
20458 a @file{configure.ac} are all replaced with the use of traces.  As a
20459 consequence, any action must be traceable, which obsoletes critical
20460 variable assignments.  Fortunately, @code{LIBOBJS} was the only problem,
20461 and it can even be handled gracefully (read, ``without your having to
20462 change something'').
20464 There were two typical uses of @code{LIBOBJS}: asking for a replacement
20465 function, and adjusting @code{LIBOBJS} for Automake and/or Libtool.
20467 @sp 1
20469 As for function replacement, the fix is immediate: use
20470 @code{AC_LIBOBJ}.  For instance:
20472 @example
20473 LIBOBJS="$LIBOBJS fnmatch.o"
20474 LIBOBJS="$LIBOBJS malloc.$ac_objext"
20475 @end example
20477 @noindent
20478 should be replaced with:
20480 @example
20481 AC_LIBOBJ([fnmatch])
20482 AC_LIBOBJ([malloc])
20483 @end example
20485 @sp 1
20487 @ovindex LIBOBJDIR
20488 When used with Automake 1.10 or newer, a suitable value for
20489 @code{LIBOBJDIR} is set so that the @code{LIBOBJS} and @code{LTLIBOBJS}
20490 can be referenced from any @file{Makefile.am}.  Even without Automake,
20491 arranging for @code{LIBOBJDIR} to be set correctly enables
20492 referencing @code{LIBOBJS} and @code{LTLIBOBJS} in another directory.
20493 The @code{LIBOBJDIR} feature is experimental.
20496 @node AC_FOO_IFELSE vs AC_TRY_FOO
20497 @subsection @code{AC_FOO_IFELSE} vs.@: @code{AC_TRY_FOO}
20499 Since Autoconf 2.50, internal codes uses @code{AC_PREPROC_IFELSE},
20500 @code{AC_COMPILE_IFELSE}, @code{AC_LINK_IFELSE}, and
20501 @code{AC_RUN_IFELSE} on one hand and @code{AC_LANG_SOURCES},
20502 and @code{AC_LANG_PROGRAM} on the other hand instead of the deprecated
20503 @code{AC_TRY_CPP}, @code{AC_TRY_COMPILE}, @code{AC_TRY_LINK}, and
20504 @code{AC_TRY_RUN}.  The motivations where:
20505 @itemize @minus
20506 @item
20507 a more consistent interface: @code{AC_TRY_COMPILE} etc.@: were double
20508 quoting their arguments;
20510 @item
20511 the combinatoric explosion is solved by decomposing on the one hand the
20512 generation of sources, and on the other hand executing the program;
20514 @item
20515 this scheme helps supporting more languages than plain C and C++.
20516 @end itemize
20518 In addition to the change of syntax, the philosophy has changed too:
20519 while emphasis was put on speed at the expense of accuracy, today's
20520 Autoconf promotes accuracy of the testing framework at, ahem@dots{}, the
20521 expense of speed.
20524 As a perfect example of what is @emph{not} to be done, here is how to
20525 find out whether a header file contains a particular declaration, such
20526 as a typedef, a structure, a structure member, or a function.  Use
20527 @code{AC_EGREP_HEADER} instead of running @code{grep} directly on the
20528 header file; on some systems the symbol might be defined in another
20529 header file that the file you are checking includes.
20531 As a (bad) example, here is how you should not check for C preprocessor
20532 symbols, either defined by header files or predefined by the C
20533 preprocessor: using @code{AC_EGREP_CPP}:
20535 @example
20536 @group
20537 AC_EGREP_CPP(yes,
20538 [#ifdef _AIX
20539   yes
20540 #endif
20541 ], is_aix=yes, is_aix=no)
20542 @end group
20543 @end example
20545 The above example, properly written would (i) use
20546 @code{AC_LANG_PROGRAM}, and (ii) run the compiler:
20548 @example
20549 @group
20550 AC_COMPILE_IFELSE([AC_LANG_PROGRAM(
20551 [[#ifndef _AIX
20552  error: This isn't AIX!
20553 #endif
20554 ]])],
20555                    [is_aix=yes],
20556                    [is_aix=no])
20557 @end group
20558 @end example
20561 @c ============================= Generating Test Suites with Autotest
20563 @node Using Autotest
20564 @chapter Generating Test Suites with Autotest
20566 @cindex Autotest
20568 @display
20569 @strong{N.B.: This section describes an experimental feature which will
20570 be part of Autoconf in a forthcoming release.  Although we believe
20571 Autotest is stabilizing, this documentation describes an interface which
20572 might change in the future: do not depend upon Autotest without
20573 subscribing to the Autoconf mailing lists.}
20574 @end display
20576 It is paradoxical that portable projects depend on nonportable tools
20577 to run their test suite.  Autoconf by itself is the paragon of this
20578 problem: although it aims at perfectly portability, up to 2.13 its
20579 test suite was using Deja@acronym{GNU}, a rich and complex testing
20580 framework, but which is far from being standard on Posix systems.
20581 Worse yet, it was likely to be missing on the most fragile platforms,
20582 the very platforms that are most likely to torture Autoconf and
20583 exhibit deficiencies.
20585 To circumvent this problem, many package maintainers have developed their
20586 own testing framework, based on simple shell scripts whose sole outputs
20587 are exit status values describing whether the test succeeded.  Most of
20588 these tests share common patterns, and this can result in lots of
20589 duplicated code and tedious maintenance.
20591 Following exactly the same reasoning that yielded to the inception of
20592 Autoconf, Autotest provides a test suite generation framework, based on
20593 M4 macros building a portable shell script.  The suite itself is
20594 equipped with automatic logging and tracing facilities which greatly
20595 diminish the interaction with bug reporters, and simple timing reports.
20597 Autoconf itself has been using Autotest for years, and we do attest that
20598 it has considerably improved the strength of the test suite and the
20599 quality of bug reports.  Other projects are known to use some generation
20600 of Autotest, such as Bison, Free Recode, Free Wdiff, @acronym{GNU} Tar, each of
20601 them with different needs, and this usage has validated Autotest as a general
20602 testing framework.
20604 Nonetheless, compared to Deja@acronym{GNU}, Autotest is inadequate for
20605 interactive tool testing, which is probably its main limitation.
20607 @menu
20608 * Using an Autotest Test Suite::  Autotest and the user
20609 * Writing Testsuites::          Autotest macros
20610 * testsuite Invocation::        Running @command{testsuite} scripts
20611 * Making testsuite Scripts::    Using autom4te to create @command{testsuite}
20612 @end menu
20614 @node Using an Autotest Test Suite
20615 @section Using an Autotest Test Suite
20617 @menu
20618 * testsuite Scripts::           The concepts of Autotest
20619 * Autotest Logs::               Their contents
20620 @end menu
20622 @node testsuite Scripts
20623 @subsection @command{testsuite} Scripts
20625 @cindex @command{testsuite}
20627 Generating testing or validation suites using Autotest is rather easy.
20628 The whole validation suite is held in a file to be processed through
20629 @command{autom4te}, itself using @acronym{GNU} M4 under the scene, to
20630 produce a stand-alone Bourne shell script which then gets distributed.
20631 Neither @command{autom4te} nor @acronym{GNU} M4 are needed at
20632 the installer's end.
20634 @cindex test group
20635 Each test of the validation suite should be part of some test group.  A
20636 @dfn{test group} is a sequence of interwoven tests that ought to be
20637 executed together, usually because one test in the group creates data
20638 files than a later test in the same group needs to read.  Complex test
20639 groups make later debugging more tedious.  It is much better to
20640 keep only a few tests per test group.  Ideally there is only one test
20641 per test group.
20643 For all but the simplest packages, some file such as @file{testsuite.at}
20644 does not fully hold all test sources, as these are often easier to
20645 maintain in separate files.  Each of these separate files holds a single
20646 test group, or a sequence of test groups all addressing some common
20647 functionality in the package.  In such cases, @file{testsuite.at}
20648 merely initializes the validation suite, and sometimes does elementary
20649 health checking, before listing include statements for all other test
20650 files.  The special file @file{package.m4}, containing the
20651 identification of the package, is automatically included if found.
20653 A convenient alternative consists in moving all the global issues
20654 (local Autotest macros, elementary health checking, and @code{AT_INIT}
20655 invocation) into the file @code{local.at}, and making
20656 @file{testsuite.at} be a simple list of @code{m4_include} of sub test
20657 suites.  In such case, generating the whole test suite or pieces of it
20658 is only a matter of choosing the @command{autom4te} command line
20659 arguments.
20661 The validation scripts that Autotest produces are by convention called
20662 @command{testsuite}.  When run, @command{testsuite} executes each test
20663 group in turn, producing only one summary line per test to say if that
20664 particular test succeeded or failed.  At end of all tests, summarizing
20665 counters get printed.  One debugging directory is left for each test
20666 group which failed, if any: such directories are named
20667 @file{testsuite.dir/@var{nn}}, where @var{nn} is the sequence number of
20668 the test group, and they include:
20670 @itemize @bullet
20671 @item a debugging script named @file{run} which reruns the test in
20672 @dfn{debug mode} (@pxref{testsuite Invocation}).  The automatic generation
20673 of debugging scripts has the purpose of easing the chase for bugs.
20675 @item all the files created with @code{AT_DATA}
20677 @item a log of the run, named @file{testsuite.log}
20678 @end itemize
20680 In the ideal situation, none of the tests fail, and consequently no
20681 debugging directory is left behind for validation.
20683 It often happens in practice that individual tests in the validation
20684 suite need to get information coming out of the configuration process.
20685 Some of this information, common for all validation suites, is provided
20686 through the file @file{atconfig}, automatically created by
20687 @code{AC_CONFIG_TESTDIR}.  For configuration informations which your
20688 testing environment specifically needs, you might prepare an optional
20689 file named @file{atlocal.in}, instantiated by @code{AC_CONFIG_FILES}.
20690 The configuration process produces @file{atconfig} and @file{atlocal}
20691 out of these two input files, and these two produced files are
20692 automatically read by the @file{testsuite} script.
20694 Here is a diagram showing the relationship between files.
20696 @noindent
20697 Files used in preparing a software package for distribution:
20699 @example
20700                 [package.m4] -->.
20701                                  \
20702 subfile-1.at ->.  [local.at] ---->+
20703     ...         \                  \
20704 subfile-i.at ---->-- testsuite.at -->-- autom4te* -->testsuite
20705     ...         /
20706 subfile-n.at ->'
20707 @end example
20709 @noindent
20710 Files used in configuring a software package:
20712 @example
20713                                      .--> atconfig
20714                                     /
20715 [atlocal.in] -->  config.status* --<
20716                                     \
20717                                      `--> [atlocal]
20718 @end example
20720 @noindent
20721 Files created during the test suite execution:
20723 @example
20724 atconfig -->.                    .--> testsuite.log
20725              \                  /
20726               >-- testsuite* --<
20727              /                  \
20728 [atlocal] ->'                    `--> [testsuite.dir]
20729 @end example
20732 @node Autotest Logs
20733 @subsection Autotest Logs
20735 When run, the test suite creates a log file named after itself, e.g., a
20736 test suite named @command{testsuite} creates @file{testsuite.log}.  It
20737 contains a lot of information, usually more than maintainers actually
20738 need, but therefore most of the time it contains all that is needed:
20740 @table @asis
20741 @item command line arguments
20742 @c akim s/to consist in/to consist of/
20743 A bad but unfortunately widespread habit consists of
20744 setting environment variables before the command, such as in
20745 @samp{CC=my-home-grown-cc ./testsuite}.  The test suite does not
20746 know this change, hence (i) it cannot report it to you, and (ii)
20747 it cannot preserve the value of @code{CC} for subsequent runs.
20748 Autoconf faced exactly the same problem, and solved it by asking
20749 users to pass the variable definitions as command line arguments.
20750 Autotest requires this rule, too, but has no means to enforce it; the log
20751 then contains a trace of the variables that were changed by the user.
20753 @item @file{ChangeLog} excerpts
20754 The topmost lines of all the @file{ChangeLog} files found in the source
20755 hierarchy.  This is especially useful when bugs are reported against
20756 development versions of the package, since the version string does not
20757 provide sufficient information to know the exact state of the sources
20758 the user compiled.  Of course, this relies on the use of a
20759 @file{ChangeLog}.
20761 @item build machine
20762 Running a test suite in a cross-compile environment is not an easy task,
20763 since it would mean having the test suite run on a machine @var{build},
20764 while running programs on a machine @var{host}.  It is much simpler to
20765 run both the test suite and the programs on @var{host}, but then, from
20766 the point of view of the test suite, there remains a single environment,
20767 @var{host} = @var{build}.  The log contains relevant information on the
20768 state of the build machine, including some important environment
20769 variables.
20770 @c FIXME: How about having an M4sh macro to say `hey, log the value
20771 @c of `@dots{}'?  This would help both Autoconf and Autotest.
20773 @item tested programs
20774 The absolute file name and answers to @option{--version} of the tested
20775 programs (see @ref{Writing Testsuites}, @code{AT_TESTED}).
20777 @item configuration log
20778 The contents of @file{config.log}, as created by @command{configure},
20779 are appended.  It contains the configuration flags and a detailed report
20780 on the configuration itself.
20781 @end table
20784 @node Writing Testsuites
20785 @section Writing @file{testsuite.at}
20787 The @file{testsuite.at} is a Bourne shell script making use of special
20788 Autotest M4 macros.  It often contains a call to @code{AT_INIT} near
20789 its beginning followed by one call to @code{m4_include} per source file
20790 for tests.  Each such included file, or the remainder of
20791 @file{testsuite.at} if include files are not used, contain a sequence of
20792 test groups.  Each test group begins with a call to @code{AT_SETUP},
20793 then an arbitrary number of shell commands or calls to @code{AT_CHECK},
20794 and then completes with a call to @code{AT_CLEANUP}.  Multiple test
20795 groups can be categorized by a call to @code{AT_BANNER}.
20797 @defmac AT_INIT (@ovar{name})
20798 @atindex{INIT}
20799 @c FIXME: Not clear, plus duplication of the information.
20800 Initialize Autotest.  Giving a @var{name} to the test suite is
20801 encouraged if your package includes several test suites.  In any case,
20802 the test suite always displays the package name and version.  It also
20803 inherits the package bug report address.
20804 @end defmac
20806 @defmac AT_COPYRIGHT (@var{copyright-notice})
20807 @atindex{COPYRIGHT}
20808 @cindex Copyright Notice
20809 State that, in addition to the Free Software Foundation's copyright on
20810 the Autotest macros, parts of your test suite are covered by
20811 @var{copyright-notice}.
20813 The @var{copyright-notice} shows up in both the head of
20814 @command{testsuite} and in @samp{testsuite --version}.
20815 @end defmac
20817 @defmac AT_TESTED (@var{executables})
20818 @atindex{TESTED}
20819 Log the file name and answer to @option{--version} of each program in
20820 space-separated list @var{executables}.  Several invocations register
20821 new executables, in other words, don't fear registering one program
20822 several times.
20823 @end defmac
20825 Autotest test suites rely on @env{PATH} to find the tested program.
20826 This avoids the need to generate absolute names of the various tools, and
20827 makes it possible to test installed programs.  Therefore, knowing which
20828 programs are being exercised is crucial to understanding problems in
20829 the test suite itself, or its occasional misuses.  It is a good idea to
20830 also subscribe foreign programs you depend upon, to avoid incompatible
20831 diagnostics.
20833 @sp 1
20835 @defmac AT_BANNER (@var{test-category-name})
20836 @atindex{BANNER}
20837 This macro identifies the start of a category of related test groups.
20838 When the resulting @file{testsuite} is invoked with more than one test
20839 group to run, its output will include a banner containing
20840 @var{test-category-name} prior to any tests run from that category.  The
20841 banner should be no more than about 40 or 50 characters.  A blank banner
20842 will not print, effectively ending a category and letting subsequent
20843 test groups behave as though they are uncategorized when run in
20844 isolation.
20845 @end defmac
20847 @defmac AT_SETUP (@var{test-group-name})
20848 @atindex{SETUP}
20849 This macro starts a group of related tests, all to be executed in the
20850 same subshell.  It accepts a single argument, which holds a few words
20851 (no more than about 30 or 40 characters) quickly describing the purpose
20852 of the test group being started.  @var{test-group-name} must not expand
20853 to unbalanced quotes, although quadrigraphs can be used.
20854 @end defmac
20856 @defmac AT_KEYWORDS (@var{keywords})
20857 @atindex{KEYWORDS}
20858 Associate the space-separated list of @var{keywords} to the enclosing
20859 test group.  This makes it possible to run ``slices'' of the test suite.
20860 For instance, if some of your test groups exercise some @samp{foo}
20861 feature, then using @samp{AT_KEYWORDS(foo)} lets you run
20862 @samp{./testsuite -k foo} to run exclusively these test groups.  The
20863 @var{title} of the test group is automatically recorded to
20864 @code{AT_KEYWORDS}.
20866 Several invocations within a test group accumulate new keywords.  In
20867 other words, don't fear registering the same keyword several times in a
20868 test group.
20869 @end defmac
20871 @defmac AT_CAPTURE_FILE (@var{file})
20872 @atindex{CAPTURE_FILE}
20873 If the current test group fails, log the contents of @var{file}.
20874 Several identical calls within one test group have no additional effect.
20875 @end defmac
20877 @defmac AT_XFAIL_IF (@var{shell-condition})
20878 @atindex{XFAIL_IF}
20879 Determine whether the test is expected to fail because it is a known
20880 bug (for unsupported features, you should skip the test).
20881 @var{shell-condition} is a shell expression such as a @code{test}
20882 command; you can instantiate this macro many times from within the
20883 same test group, and one of the conditions is enough to turn
20884 the test into an expected failure.
20885 @end defmac
20887 @defmac AT_CLEANUP
20888 @atindex{CLEANUP}
20889 End the current test group.
20890 @end defmac
20892 @sp 1
20894 @defmac AT_DATA (@var{file}, @var{contents})
20895 @atindex{DATA}
20896 Initialize an input data @var{file} with given @var{contents}.  Of
20897 course, the @var{contents} have to be properly quoted between square
20898 brackets to protect against included commas or spurious M4
20899 expansion.  The contents must end with an end of line.  @var{file} must
20900 be a single shell word that expands into a single file name.
20901 @end defmac
20903 @defmac AT_CHECK (@var{commands}, @dvar{status, 0}, @dvar{stdout, }, @
20904   @dvar{stderr, }, @ovar{run-if-fail}, @ovar{run-if-pass})
20905 @atindex{CHECK}
20906 Execute a test by performing given shell @var{commands}.  These commands
20907 should normally exit with @var{status}, while producing expected
20908 @var{stdout} and @var{stderr} contents.  If @var{commands} exit with
20909 status 77, then the whole test group is skipped.  Otherwise, if this test
20910 fails, run shell commands @var{run-if-fail} or, if this test passes, run shell
20911 commands @var{run-if-pass}.
20913 This macro must be invoked in between @code{AT_SETUP} and @code{AT_CLEANUP}.
20915 @c Previously, we had this:
20916 @c  The @var{commands} @emph{must not} redirect the standard output, nor the
20917 @c  standard error.
20918 @c to prevent trigerring the double redirect bug on Ultrix, see
20919 @c `File Descriptors'.  This was too restricting, and Ultrix is pretty
20920 @c much dead, so we dropped the limitation; the obvious workaround on
20921 @c Ultrix is to use a working shell there.
20923 If @var{status}, or @var{stdout}, or @var{stderr} is @samp{ignore}, then
20924 the corresponding value is not checked.
20926 The special value @samp{expout} for @var{stdout} means the expected
20927 output of the @var{commands} is the content of the file @file{expout}.
20928 If @var{stdout} is @samp{stdout}, then the standard output of the
20929 @var{commands} is available for further tests in the file @file{stdout}.
20930 Similarly for @var{stderr} with @samp{experr} and @samp{stderr}.
20931 @end defmac
20934 @node testsuite Invocation
20935 @section Running @command{testsuite} Scripts
20936 @cindex @command{testsuite}
20938 Autotest test suites support the following arguments:
20940 @table @option
20941 @item --help
20942 @itemx -h
20943 Display the list of options and exit successfully.
20945 @item --version
20946 @itemx -V
20947 Display the version of the test suite and exit successfully.
20949 @item --directory=@var{dir}
20950 @itemx -C @var{dir}
20951 Change the current directory to @var{dir} before creating any files.
20952 Useful for running the testsuite in a subdirectory from a top-level
20953 Makefile.
20955 @item --clean
20956 @itemx -c
20957 Remove all the files the test suite might have created and exit.  Meant
20958 for @code{clean} Make targets.
20960 @item --list
20961 @itemx -l
20962 List all the tests (or only the selection), including their possible
20963 keywords.
20964 @end table
20966 @sp 1
20968 By default all tests are performed (or described with
20969 @option{--list}) in the default environment first silently, then
20970 verbosely, but the environment, set of tests, and verbosity level can be
20971 tuned:
20973 @table @samp
20974 @item @var{variable}=@var{value}
20975 Set the environment @var{variable} to @var{value}.  Use this rather
20976 than @samp{FOO=foo ./testsuite} as debugging scripts would then run in a
20977 different environment.
20979 @cindex @code{AUTOTEST_PATH}
20980 The variable @code{AUTOTEST_PATH} specifies the testing path to prepend
20981 to @env{PATH}.  Relative directory names (not starting with
20982 @samp{/}) are considered to be relative to the top level of the
20983 package being built.  All directories are made absolute, first
20984 starting from the top level @emph{build} tree, then from the
20985 @emph{source} tree.  For instance @samp{./testsuite
20986 AUTOTEST_PATH=tests:bin} for a @file{/src/foo-1.0} source package built
20987 in @file{/tmp/foo} results in @samp{/tmp/foo/tests:/tmp/foo/bin} and
20988 then @samp{/src/foo-1.0/tests:/src/foo-1.0/bin} being prepended to
20989 @env{PATH}.
20991 @item @var{number}
20992 @itemx @var{number}-@var{number}
20993 @itemx @var{number}-
20994 @itemx -@var{number}
20995 Add the corresponding test groups, with obvious semantics, to the
20996 selection.
20998 @item --keywords=@var{keywords}
20999 @itemx -k @var{keywords}
21000 Add to the selection the test groups with title or keywords (arguments
21001 to @code{AT_SETUP} or @code{AT_KEYWORDS}) that match @emph{all} keywords
21002 of the comma separated list @var{keywords}, case-insensitively.  Use
21003 @samp{!} immediately before the keyword to invert the selection for this
21004 keyword.  By default, the keywords match whole words; enclose them in
21005 @samp{.*} to also match parts of words.
21007 For example, running
21009 @example
21010 @kbd{./testsuite -k 'autoupdate,.*FUNC.*'}
21011 @end example
21013 @noindent
21014 selects all tests tagged @samp{autoupdate} @emph{and} with tags
21015 containing @samp{FUNC} (as in @samp{AC_CHECK_FUNC}, @samp{AC_FUNC_ALLOCA},
21016 etc.), while
21018 @example
21019 @kbd{./testsuite -k '!autoupdate' -k '.*FUNC.*'}
21020 @end example
21022 @noindent
21023 selects all tests not tagged @samp{autoupdate} @emph{or} with tags
21024 containing @samp{FUNC}.
21026 @item --errexit
21027 @itemx -e
21028 If any test fails, immediately abort testing.  It implies
21029 @option{--debug}: post test group clean up, and top-level logging
21030 are inhibited.  This option is meant for the full test
21031 suite, it is not really useful for generated debugging scripts.
21033 @item --verbose
21034 @itemx -v
21035 Force more verbosity in the detailed output of what is being done.  This
21036 is the default for debugging scripts.
21038 @item --debug
21039 @itemx -d
21040 Do not remove the files after a test group was performed ---but they are
21041 still removed @emph{before}, therefore using this option is sane when
21042 running several test groups.  Create debugging scripts.  Do not
21043 overwrite the top-level
21044 log (in order to preserve supposedly existing full log file).  This is
21045 the default for debugging scripts, but it can also be useful to debug
21046 the testsuite itself.
21048 @item --trace
21049 @itemx -x
21050 Trigger shell tracing of the test groups.
21051 @end table
21054 @node Making testsuite Scripts
21055 @section Making @command{testsuite} Scripts
21057 For putting Autotest into movement, you need some configuration and
21058 makefile machinery.  We recommend, at least if your package uses deep or
21059 shallow hierarchies, that you use @file{tests/} as the name of the
21060 directory holding all your tests and their makefile.  Here is a
21061 check list of things to do.
21063 @itemize @minus
21065 @item
21066 @cindex @file{package.m4}
21067 Make sure to create the file @file{package.m4}, which defines the
21068 identity of the package.  It must define @code{AT_PACKAGE_STRING}, the
21069 full signature of the package, and @code{AT_PACKAGE_BUGREPORT}, the
21070 address to which bug reports should be sent.  For sake of completeness,
21071 we suggest that you also define @code{AT_PACKAGE_NAME},
21072 @code{AT_PACKAGE_TARNAME}, and @code{AT_PACKAGE_VERSION}.
21073 @xref{Initializing configure}, for a description of these variables.  We
21074 suggest the following makefile excerpt:
21076 @smallexample
21077 # The `:;' works around a Bash 3.2 bug when the output is not writeable.
21078 $(srcdir)/package.m4: $(top_srcdir)/configure.ac
21079         :;@{ \
21080           echo '# Signature of the current package.' && \
21081           echo 'm4_define([AT_PACKAGE_NAME],      [@@PACKAGE_NAME@@])' && \
21082           echo 'm4_define([AT_PACKAGE_TARNAME],   [@@PACKAGE_TARNAME@@])' && \
21083           echo 'm4_define([AT_PACKAGE_VERSION],   [@@PACKAGE_VERSION@@])' && \
21084           echo 'm4_define([AT_PACKAGE_STRING],    [@@PACKAGE_STRING@@])' && \
21085           echo 'm4_define([AT_PACKAGE_BUGREPORT], [@@PACKAGE_BUGREPORT@@])'; \
21086         @} >'$(srcdir)/package.m4'
21087 @end smallexample
21089 @noindent
21090 Be sure to distribute @file{package.m4} and to put it into the source
21091 hierarchy: the test suite ought to be shipped!
21093 @item
21094 Invoke @code{AC_CONFIG_TESTDIR}.
21096 @defmac AC_CONFIG_TESTDIR (@var{directory}, @dvar{test-path, directory})
21097 @acindex{CONFIG_TESTDIR}
21098 An Autotest test suite is to be configured in @var{directory}.  This
21099 macro requires the instantiation of @file{@var{directory}/atconfig} from
21100 @file{@var{directory}/atconfig.in}, and sets the default
21101 @code{AUTOTEST_PATH} to @var{test-path} (@pxref{testsuite Invocation}).
21102 @end defmac
21104 @item
21105 Still within @file{configure.ac}, as appropriate, ensure that some
21106 @code{AC_CONFIG_FILES} command includes substitution for
21107 @file{tests/atlocal}.
21109 @item
21110 The @file{tests/Makefile.in} should be modified so the validation in
21111 your package is triggered by @samp{make check}.  An example is provided
21112 below.
21113 @end itemize
21115 With Automake, here is a minimal example about how to link @samp{make
21116 check} with a validation suite.
21118 @example
21119 EXTRA_DIST = testsuite.at $(TESTSUITE) atlocal.in
21120 TESTSUITE = $(srcdir)/testsuite
21122 check-local: atconfig atlocal $(TESTSUITE)
21123         $(SHELL) '$(TESTSUITE)' $(TESTSUITEFLAGS)
21125 installcheck-local: atconfig atlocal $(TESTSUITE)
21126         $(SHELL) '$(TESTSUITE)' AUTOTEST_PATH='$(bindir)' \
21127           $(TESTSUITEFLAGS)
21129 clean-local:
21130         test ! -f '$(TESTSUITE)' || \
21131          $(SHELL) '$(TESTSUITE)' --clean
21133 AUTOTEST = $(AUTOM4TE) --language=autotest
21134 $(TESTSUITE): $(srcdir)/testsuite.at
21135         $(AUTOTEST) -I '$(srcdir)' -o $@@.tmp $@@.at
21136         mv $@@.tmp $@@
21137 @end example
21139 You might want to list explicitly the dependencies, i.e., the list of
21140 the files @file{testsuite.at} includes.
21142 If you don't use Automake, you might need to add lines inspired from the
21143 following:
21145 @example
21146 subdir = tests
21148 atconfig: $(top_builddir)/config.status
21149         cd $(top_builddir) && \
21150            $(SHELL) ./config.status $(subdir)/$@@
21152 atlocal: $(srcdir)/atlocal.in $(top_builddir)/config.status
21153         cd $(top_builddir) && \
21154            $(SHELL) ./config.status $(subdir)/$@@
21155 @end example
21157 @noindent
21158 and manage to have @code{$(EXTRA_DIST)} distributed.
21160 If you use Automake, however, you don't need to add a rule to generate
21161 @file{atlocal}.
21163 With all this in place, and if you have not initialized @samp{TESTSUITEFLAGS}
21164 within your makefile, you can fine-tune test suite execution with this
21165 variable, for example:
21167 @example
21168 make check TESTSUITEFLAGS='-v -d -x 75 -k AC_PROG_CC CFLAGS=-g'
21169 @end example
21173 @c =============================== Frequent Autoconf Questions, with answers
21175 @node FAQ
21176 @chapter Frequent Autoconf Questions, with answers
21178 Several questions about Autoconf come up occasionally.  Here some of them
21179 are addressed.
21181 @menu
21182 * Distributing::                Distributing @command{configure} scripts
21183 * Why GNU M4::                  Why not use the standard M4?
21184 * Bootstrapping::               Autoconf and @acronym{GNU} M4 require each other?
21185 * Why Not Imake::               Why @acronym{GNU} uses @command{configure} instead of Imake
21186 * Defining Directories::        Passing @code{datadir} to program
21187 * Autom4te Cache::              What is it?  Can I remove it?
21188 * Present But Cannot Be Compiled::  Compiler and Preprocessor Disagree
21189 @end menu
21191 @node Distributing
21192 @section Distributing @command{configure} Scripts
21193 @cindex License
21195 @display
21196 What are the restrictions on distributing @command{configure}
21197 scripts that Autoconf generates?  How does that affect my
21198 programs that use them?
21199 @end display
21201 There are no restrictions on how the configuration scripts that Autoconf
21202 produces may be distributed or used.  In Autoconf version 1, they were
21203 covered by the @acronym{GNU} General Public License.  We still encourage
21204 software authors to distribute their work under terms like those of the
21205 @acronym{GPL}, but doing so is not required to use Autoconf.
21207 Of the other files that might be used with @command{configure},
21208 @file{config.h.in} is under whatever copyright you use for your
21209 @file{configure.ac}.  @file{config.sub} and @file{config.guess} have an
21210 exception to the @acronym{GPL} when they are used with an Autoconf-generated
21211 @command{configure} script, which permits you to distribute them under the
21212 same terms as the rest of your package.  @file{install-sh} is from the X
21213 Consortium and is not copyrighted.
21215 @node Why GNU M4
21216 @section Why Require @acronym{GNU} M4?
21218 @display
21219 Why does Autoconf require @acronym{GNU} M4?
21220 @end display
21222 Many M4 implementations have hard-coded limitations on the size and
21223 number of macros that Autoconf exceeds.  They also lack several
21224 builtin macros that it would be difficult to get along without in a
21225 sophisticated application like Autoconf, including:
21227 @example
21228 m4_builtin
21229 m4_indir
21230 m4_bpatsubst
21231 __file__
21232 __line__
21233 @end example
21235 Autoconf requires version 1.4.5 or later of @acronym{GNU} M4.
21237 Since only software maintainers need to use Autoconf, and since @acronym{GNU}
21238 M4 is simple to configure and install, it seems reasonable to require
21239 @acronym{GNU} M4 to be installed also.  Many maintainers of @acronym{GNU} and
21240 other free software already have most of the @acronym{GNU} utilities
21241 installed, since they prefer them.
21243 @node Bootstrapping
21244 @section How Can I Bootstrap?
21245 @cindex Bootstrap
21247 @display
21248 If Autoconf requires @acronym{GNU} M4 and @acronym{GNU} M4 has an Autoconf
21249 @command{configure} script, how do I bootstrap?  It seems like a chicken
21250 and egg problem!
21251 @end display
21253 This is a misunderstanding.  Although @acronym{GNU} M4 does come with a
21254 @command{configure} script produced by Autoconf, Autoconf is not required
21255 in order to run the script and install @acronym{GNU} M4.  Autoconf is only
21256 required if you want to change the M4 @command{configure} script, which few
21257 people have to do (mainly its maintainer).
21259 @node Why Not Imake
21260 @section Why Not Imake?
21261 @cindex Imake
21263 @display
21264 Why not use Imake instead of @command{configure} scripts?
21265 @end display
21267 Several people have written addressing this question, so I include
21268 adaptations of their explanations here.
21270 The following answer is based on one written by Richard Pixley:
21272 @quotation
21273 Autoconf generated scripts frequently work on machines that it has
21274 never been set up to handle before.  That is, it does a good job of
21275 inferring a configuration for a new system.  Imake cannot do this.
21277 Imake uses a common database of host specific data.  For X11, this makes
21278 sense because the distribution is made as a collection of tools, by one
21279 central authority who has control over the database.
21281 @acronym{GNU} tools are not released this way.  Each @acronym{GNU} tool has a
21282 maintainer; these maintainers are scattered across the world.  Using a
21283 common database would be a maintenance nightmare.  Autoconf may appear
21284 to be this kind of database, but in fact it is not.  Instead of listing
21285 host dependencies, it lists program requirements.
21287 If you view the @acronym{GNU} suite as a collection of native tools, then the
21288 problems are similar.  But the @acronym{GNU} development tools can be
21289 configured as cross tools in almost any host+target permutation.  All of
21290 these configurations can be installed concurrently.  They can even be
21291 configured to share host independent files across hosts.  Imake doesn't
21292 address these issues.
21294 Imake templates are a form of standardization.  The @acronym{GNU} coding
21295 standards address the same issues without necessarily imposing the same
21296 restrictions.
21297 @end quotation
21300 Here is some further explanation, written by Per Bothner:
21302 @quotation
21303 One of the advantages of Imake is that it easy to generate large
21304 makefiles using the @samp{#include} and macro mechanisms of @command{cpp}.
21305 However, @code{cpp} is not programmable: it has limited conditional
21306 facilities, and no looping.  And @code{cpp} cannot inspect its
21307 environment.
21309 All of these problems are solved by using @code{sh} instead of
21310 @code{cpp}.  The shell is fully programmable, has macro substitution,
21311 can execute (or source) other shell scripts, and can inspect its
21312 environment.
21313 @end quotation
21316 Paul Eggert elaborates more:
21318 @quotation
21319 With Autoconf, installers need not assume that Imake itself is already
21320 installed and working well.  This may not seem like much of an advantage
21321 to people who are accustomed to Imake.  But on many hosts Imake is not
21322 installed or the default installation is not working well, and requiring
21323 Imake to install a package hinders the acceptance of that package on
21324 those hosts.  For example, the Imake template and configuration files
21325 might not be installed properly on a host, or the Imake build procedure
21326 might wrongly assume that all source files are in one big directory
21327 tree, or the Imake configuration might assume one compiler whereas the
21328 package or the installer needs to use another, or there might be a
21329 version mismatch between the Imake expected by the package and the Imake
21330 supported by the host.  These problems are much rarer with Autoconf,
21331 where each package comes with its own independent configuration
21332 processor.
21334 Also, Imake often suffers from unexpected interactions between
21335 @command{make} and the installer's C preprocessor.  The fundamental problem
21336 here is that the C preprocessor was designed to preprocess C programs,
21337 not makefiles.  This is much less of a problem with Autoconf,
21338 which uses the general-purpose preprocessor M4, and where the
21339 package's author (rather than the installer) does the preprocessing in a
21340 standard way.
21341 @end quotation
21344 Finally, Mark Eichin notes:
21346 @quotation
21347 Imake isn't all that extensible, either.  In order to add new features to
21348 Imake, you need to provide your own project template, and duplicate most
21349 of the features of the existing one.  This means that for a sophisticated
21350 project, using the vendor-provided Imake templates fails to provide any
21351 leverage---since they don't cover anything that your own project needs
21352 (unless it is an X11 program).
21354 On the other side, though:
21356 The one advantage that Imake has over @command{configure}:
21357 @file{Imakefile} files tend to be much shorter (likewise, less redundant)
21358 than @file{Makefile.in} files.  There is a fix to this, however---at least
21359 for the Kerberos V5 tree, we've modified things to call in common
21360 @file{post.in} and @file{pre.in} makefile fragments for the
21361 entire tree.  This means that a lot of common things don't have to be
21362 duplicated, even though they normally are in @command{configure} setups.
21363 @end quotation
21366 @node Defining Directories
21367 @section How Do I @code{#define} Installation Directories?
21369 @display
21370 My program needs library files, installed in @code{datadir} and
21371 similar.  If I use
21373 @example
21374 AC_DEFINE_UNQUOTED([DATADIR], [$datadir],
21375   [Define to the read-only architecture-independent
21376    data directory.])
21377 @end example
21379 @noindent
21380 I get
21382 @example
21383 #define DATADIR "$@{prefix@}/share"
21384 @end example
21385 @end display
21387 As already explained, this behavior is on purpose, mandated by the
21388 @acronym{GNU} Coding Standards, see @ref{Installation Directory
21389 Variables}.  There are several means to achieve a similar goal:
21391 @itemize @minus
21392 @item
21393 Do not use @code{AC_DEFINE} but use your makefile to pass the
21394 actual value of @code{datadir} via compilation flags.
21395 @xref{Installation Directory Variables}, for the details.
21397 @item
21398 This solution can be simplified when compiling a program: you may either
21399 extend the @code{CPPFLAGS}:
21401 @example
21402 CPPFLAGS = -DDATADIR='"$(datadir)"' @@CPPFLAGS@@
21403 @end example
21405 @noindent
21406 If you are using Automake, you should use @code{AM_CPPFLAGS} instead:
21408 @example
21409 AM_CPPFLAGS = -DDATADIR='"$(datadir)"'
21410 @end example
21412 @noindent
21413 Alternatively, create a dedicated header file:
21415 @example
21416 DISTCLEANFILES = myprog-paths.h
21417 myprog-paths.h: Makefile
21418         echo '#define DATADIR "$(datadir)"' >$@@
21419 @end example
21421 @item
21422 Use @code{AC_DEFINE} but have @command{configure} compute the literal
21423 value of @code{datadir} and others.  Many people have wrapped macros to
21424 automate this task.  For instance, the macro @code{AC_DEFINE_DIR} from
21425 the @uref{http://autoconf-archive.cryp.to/, Autoconf Macro
21426 Archive}.
21428 This solution does not conform to the @acronym{GNU} Coding Standards.
21430 @item
21431 Note that all the previous solutions hard wire the absolute name of
21432 these directories in the executables, which is not a good property.  You
21433 may try to compute the names relative to @code{prefix}, and try to
21434 find @code{prefix} at runtime, this way your package is relocatable.
21435 @end itemize
21438 @node Autom4te Cache
21439 @section What is @file{autom4te.cache}?
21441 @display
21442 What is this directory @file{autom4te.cache}?  Can I safely remove it?
21443 @end display
21445 In the @acronym{GNU} Build System, @file{configure.ac} plays a central
21446 role and is read by many tools: @command{autoconf} to create
21447 @file{configure}, @command{autoheader} to create @file{config.h.in},
21448 @command{automake} to create @file{Makefile.in}, @command{autoscan} to
21449 check the completeness of @file{configure.ac}, @command{autoreconf} to
21450 check the @acronym{GNU} Build System components that are used.  To
21451 ``read @file{configure.ac}'' actually means to compile it with M4,
21452 which can be a long process for complex @file{configure.ac}.
21454 This is why all these tools, instead of running directly M4, invoke
21455 @command{autom4te} (@pxref{autom4te Invocation}) which, while answering to
21456 a specific demand, stores additional information in
21457 @file{autom4te.cache} for future runs.  For instance, if you run
21458 @command{autoconf}, behind the scenes, @command{autom4te} also
21459 stores information for the other tools, so that when you invoke
21460 @command{autoheader} or @command{automake} etc., reprocessing
21461 @file{configure.ac} is not needed.  The speed up is frequently 30%,
21462 and is increasing with the size of @file{configure.ac}.
21464 But it is and remains being simply a cache: you can safely remove it.
21466 @sp 1
21468 @display
21469 Can I permanently get rid of it?
21470 @end display
21472 The creation of this cache can be disabled from
21473 @file{~/.autom4te.cfg}, see @ref{Customizing autom4te}, for more
21474 details.  You should be aware that disabling the cache slows down the
21475 Autoconf test suite by 40%.  The more @acronym{GNU} Build System
21476 components are used, the more the cache is useful; for instance
21477 running @samp{autoreconf -f} on the Core Utilities is twice slower without
21478 the cache @emph{although @option{--force} implies that the cache is
21479 not fully exploited}, and eight times slower than without
21480 @option{--force}.
21483 @node Present But Cannot Be Compiled
21484 @section Header Present But Cannot Be Compiled
21486 The most important guideline to bear in mind when checking for
21487 features is to mimic as much as possible the intended use.
21488 Unfortunately, old versions of @code{AC_CHECK_HEADER} and
21489 @code{AC_CHECK_HEADERS} failed to follow this idea, and called
21490 the preprocessor, instead of the compiler, to check for headers.  As a
21491 result, incompatibilities between headers went unnoticed during
21492 configuration, and maintainers finally had to deal with this issue
21493 elsewhere.
21495 As of Autoconf 2.56 both checks are performed, and @command{configure}
21496 complains loudly if the compiler and the preprocessor do not agree.
21497 For the time being the result used is that of the preprocessor, to give
21498 maintainers time to adjust their @file{configure.ac}, but in the
21499 future, only the compiler will be considered.
21501 Consider the following example:
21503 @smallexample
21504 $ @kbd{cat number.h}
21505 typedef int number;
21506 $ @kbd{cat pi.h}
21507 const number pi = 3;
21508 $ @kbd{cat configure.ac}
21509 AC_INIT([Example], [1.0], [bug-example@@example.org])
21510 AC_CHECK_HEADERS([pi.h])
21511 $ @kbd{autoconf -Wall}
21512 $ @kbd{./configure}
21513 checking for gcc... gcc
21514 checking for C compiler default output file name... a.out
21515 checking whether the C compiler works... yes
21516 checking whether we are cross compiling... no
21517 checking for suffix of executables...
21518 checking for suffix of object files... o
21519 checking whether we are using the GNU C compiler... yes
21520 checking whether gcc accepts -g... yes
21521 checking for gcc option to accept ISO C89... none needed
21522 checking how to run the C preprocessor... gcc -E
21523 checking for grep that handles long lines and -e... grep
21524 checking for egrep... grep -E
21525 checking for ANSI C header files... yes
21526 checking for sys/types.h... yes
21527 checking for sys/stat.h... yes
21528 checking for stdlib.h... yes
21529 checking for string.h... yes
21530 checking for memory.h... yes
21531 checking for strings.h... yes
21532 checking for inttypes.h... yes
21533 checking for stdint.h... yes
21534 checking for unistd.h... yes
21535 checking pi.h usability... no
21536 checking pi.h presence... yes
21537 configure: WARNING: pi.h: present but cannot be compiled
21538 configure: WARNING: pi.h:     check for missing prerequisite headers?
21539 configure: WARNING: pi.h: see the Autoconf documentation
21540 configure: WARNING: pi.h:     section "Present But Cannot Be Compiled"
21541 configure: WARNING: pi.h: proceeding with the preprocessor's result
21542 configure: WARNING: pi.h: in the future, the compiler will take precedence
21543 configure: WARNING:     ## -------------------------------------- ##
21544 configure: WARNING:     ## Report this to bug-example@@example.org ##
21545 configure: WARNING:     ## -------------------------------------- ##
21546 checking for pi.h... yes
21547 @end smallexample
21549 @noindent
21550 The proper way the handle this case is using the fourth argument
21551 (@pxref{Generic Headers}):
21553 @example
21554 $ @kbd{cat configure.ac}
21555 AC_INIT([Example], [1.0], [bug-example@@example.org])
21556 AC_CHECK_HEADERS([number.h pi.h], [], [],
21557 [[#ifdef HAVE_NUMBER_H
21558 # include <number.h>
21559 #endif
21561 $ @kbd{autoconf -Wall}
21562 $ @kbd{./configure}
21563 checking for gcc... gcc
21564 checking for C compiler default output... a.out
21565 checking whether the C compiler works... yes
21566 checking whether we are cross compiling... no
21567 checking for suffix of executables...
21568 checking for suffix of object files... o
21569 checking whether we are using the GNU C compiler... yes
21570 checking whether gcc accepts -g... yes
21571 checking for gcc option to accept ANSI C... none needed
21572 checking for number.h... yes
21573 checking for pi.h... yes
21574 @end example
21576 See @ref{Particular Headers}, for a list of headers with their
21577 prerequisite.
21579 @c ===================================================== History of Autoconf.
21581 @node History
21582 @chapter History of Autoconf
21583 @cindex History of autoconf
21585 You may be wondering, Why was Autoconf originally written?  How did it
21586 get into its present form?  (Why does it look like gorilla spit?)  If
21587 you're not wondering, then this chapter contains no information useful
21588 to you, and you might as well skip it.  If you @emph{are} wondering,
21589 then let there be light@enddots{}
21591 @menu
21592 * Genesis::                     Prehistory and naming of @command{configure}
21593 * Exodus::                      The plagues of M4 and Perl
21594 * Leviticus::                   The priestly code of portability arrives
21595 * Numbers::                     Growth and contributors
21596 * Deuteronomy::                 Approaching the promises of easy configuration
21597 @end menu
21599 @node Genesis
21600 @section Genesis
21602 In June 1991 I was maintaining many of the @acronym{GNU} utilities for the
21603 Free Software Foundation.  As they were ported to more platforms and
21604 more programs were added, the number of @option{-D} options that users
21605 had to select in the makefile (around 20) became burdensome.
21606 Especially for me---I had to test each new release on a bunch of
21607 different systems.  So I wrote a little shell script to guess some of
21608 the correct settings for the fileutils package, and released it as part
21609 of fileutils 2.0.  That @command{configure} script worked well enough that
21610 the next month I adapted it (by hand) to create similar @command{configure}
21611 scripts for several other @acronym{GNU} utilities packages.  Brian Berliner
21612 also adapted one of my scripts for his @acronym{CVS} revision control system.
21614 Later that summer, I learned that Richard Stallman and Richard Pixley
21615 were developing similar scripts to use in the @acronym{GNU} compiler tools;
21616 so I adapted my @command{configure} scripts to support their evolving
21617 interface: using the file name @file{Makefile.in} as the templates;
21618 adding @samp{+srcdir}, the first option (of many); and creating
21619 @file{config.status} files.
21621 @node Exodus
21622 @section Exodus
21624 As I got feedback from users, I incorporated many improvements, using
21625 Emacs to search and replace, cut and paste, similar changes in each of
21626 the scripts.  As I adapted more @acronym{GNU} utilities packages to use
21627 @command{configure} scripts, updating them all by hand became impractical.
21628 Rich Murphey, the maintainer of the @acronym{GNU} graphics utilities, sent me
21629 mail saying that the @command{configure} scripts were great, and asking if
21630 I had a tool for generating them that I could send him.  No, I thought,
21631 but I should!  So I started to work out how to generate them.  And the
21632 journey from the slavery of hand-written @command{configure} scripts to the
21633 abundance and ease of Autoconf began.
21635 Cygnus @command{configure}, which was being developed at around that time,
21636 is table driven; it is meant to deal mainly with a discrete number of
21637 system types with a small number of mainly unguessable features (such as
21638 details of the object file format).  The automatic configuration system
21639 that Brian Fox had developed for Bash takes a similar approach.  For
21640 general use, it seems to me a hopeless cause to try to maintain an
21641 up-to-date database of which features each variant of each operating
21642 system has.  It's easier and more reliable to check for most features on
21643 the fly---especially on hybrid systems that people have hacked on
21644 locally or that have patches from vendors installed.
21646 I considered using an architecture similar to that of Cygnus
21647 @command{configure}, where there is a single @command{configure} script that
21648 reads pieces of @file{configure.in} when run.  But I didn't want to have
21649 to distribute all of the feature tests with every package, so I settled
21650 on having a different @command{configure} made from each
21651 @file{configure.in} by a preprocessor.  That approach also offered more
21652 control and flexibility.
21654 I looked briefly into using the Metaconfig package, by Larry Wall,
21655 Harlan Stenn, and Raphael Manfredi, but I decided not to for several
21656 reasons.  The @command{Configure} scripts it produces are interactive,
21657 which I find quite inconvenient; I didn't like the ways it checked for
21658 some features (such as library functions); I didn't know that it was
21659 still being maintained, and the @command{Configure} scripts I had
21660 seen didn't work on many modern systems (such as System V R4 and NeXT);
21661 it wasn't flexible in what it could do in response to a feature's
21662 presence or absence; I found it confusing to learn; and it was too big
21663 and complex for my needs (I didn't realize then how much Autoconf would
21664 eventually have to grow).
21666 I considered using Perl to generate my style of @command{configure}
21667 scripts, but decided that M4 was better suited to the job of simple
21668 textual substitutions: it gets in the way less, because output is
21669 implicit.  Plus, everyone already has it.  (Initially I didn't rely on
21670 the @acronym{GNU} extensions to M4.)  Also, some of my friends at the
21671 University of Maryland had recently been putting M4 front ends on
21672 several programs, including @code{tvtwm}, and I was interested in trying
21673 out a new language.
21675 @node Leviticus
21676 @section Leviticus
21678 Since my @command{configure} scripts determine the system's capabilities
21679 automatically, with no interactive user intervention, I decided to call
21680 the program that generates them Autoconfig.  But with a version number
21681 tacked on, that name would be too long for old Unix file systems,
21682 so I shortened it to Autoconf.
21684 In the fall of 1991 I called together a group of fellow questers after
21685 the Holy Grail of portability (er, that is, alpha testers) to give me
21686 feedback as I encapsulated pieces of my handwritten scripts in M4 macros
21687 and continued to add features and improve the techniques used in the
21688 checks.  Prominent among the testers were Fran@,{c}ois Pinard, who came up
21689 with the idea of making an Autoconf shell script to run M4
21690 and check for unresolved macro calls; Richard Pixley, who suggested
21691 running the compiler instead of searching the file system to find
21692 include files and symbols, for more accurate results; Karl Berry, who
21693 got Autoconf to configure @TeX{} and added the macro index to the
21694 documentation; and Ian Lance Taylor, who added support for creating a C
21695 header file as an alternative to putting @option{-D} options in a
21696 makefile, so he could use Autoconf for his @acronym{UUCP} package.
21697 The alpha testers cheerfully adjusted their files again and again as the
21698 names and calling conventions of the Autoconf macros changed from
21699 release to release.  They all contributed many specific checks, great
21700 ideas, and bug fixes.
21702 @node Numbers
21703 @section Numbers
21705 In July 1992, after months of alpha testing, I released Autoconf 1.0,
21706 and converted many @acronym{GNU} packages to use it.  I was surprised by how
21707 positive the reaction to it was.  More people started using it than I
21708 could keep track of, including people working on software that wasn't
21709 part of the @acronym{GNU} Project (such as TCL, FSP, and Kerberos V5).
21710 Autoconf continued to improve rapidly, as many people using the
21711 @command{configure} scripts reported problems they encountered.
21713 Autoconf turned out to be a good torture test for M4 implementations.
21714 Unix M4 started to dump core because of the length of the
21715 macros that Autoconf defined, and several bugs showed up in @acronym{GNU}
21716 M4 as well.  Eventually, we realized that we needed to use some
21717 features that only @acronym{GNU} M4 has.  4.3@acronym{BSD} M4, in
21718 particular, has an impoverished set of builtin macros; the System V
21719 version is better, but still doesn't provide everything we need.
21721 More development occurred as people put Autoconf under more stresses
21722 (and to uses I hadn't anticipated).  Karl Berry added checks for X11.
21723 david zuhn contributed C++ support.  Fran@,{c}ois Pinard made it diagnose
21724 invalid arguments.  Jim Blandy bravely coerced it into configuring
21725 @acronym{GNU} Emacs, laying the groundwork for several later improvements.
21726 Roland McGrath got it to configure the @acronym{GNU} C Library, wrote the
21727 @command{autoheader} script to automate the creation of C header file
21728 templates, and added a @option{--verbose} option to @command{configure}.
21729 Noah Friedman added the @option{--autoconf-dir} option and
21730 @code{AC_MACRODIR} environment variable.  (He also coined the term
21731 @dfn{autoconfiscate} to mean ``adapt a software package to use
21732 Autoconf''.)  Roland and Noah improved the quoting protection in
21733 @code{AC_DEFINE} and fixed many bugs, especially when I got sick of
21734 dealing with portability problems from February through June, 1993.
21736 @node Deuteronomy
21737 @section Deuteronomy
21739 A long wish list for major features had accumulated, and the effect of
21740 several years of patching by various people had left some residual
21741 cruft.  In April 1994, while working for Cygnus Support, I began a major
21742 revision of Autoconf.  I added most of the features of the Cygnus
21743 @command{configure} that Autoconf had lacked, largely by adapting the
21744 relevant parts of Cygnus @command{configure} with the help of david zuhn
21745 and Ken Raeburn.  These features include support for using
21746 @file{config.sub}, @file{config.guess}, @option{--host}, and
21747 @option{--target}; making links to files; and running @command{configure}
21748 scripts in subdirectories.  Adding these features enabled Ken to convert
21749 @acronym{GNU} @code{as}, and Rob Savoye to convert Deja@acronym{GNU}, to using
21750 Autoconf.
21752 I added more features in response to other peoples' requests.  Many
21753 people had asked for @command{configure} scripts to share the results of
21754 the checks between runs, because (particularly when configuring a large
21755 source tree, like Cygnus does) they were frustratingly slow.  Mike
21756 Haertel suggested adding site-specific initialization scripts.  People
21757 distributing software that had to unpack on MS-DOS asked for a way to
21758 override the @file{.in} extension on the file names, which produced file
21759 names like @file{config.h.in} containing two dots.  Jim Avera did an
21760 extensive examination of the problems with quoting in @code{AC_DEFINE}
21761 and @code{AC_SUBST}; his insights led to significant improvements.
21762 Richard Stallman asked that compiler output be sent to @file{config.log}
21763 instead of @file{/dev/null}, to help people debug the Emacs
21764 @command{configure} script.
21766 I made some other changes because of my dissatisfaction with the quality
21767 of the program.  I made the messages showing results of the checks less
21768 ambiguous, always printing a result.  I regularized the names of the
21769 macros and cleaned up coding style inconsistencies.  I added some
21770 auxiliary utilities that I had developed to help convert source code
21771 packages to use Autoconf.  With the help of Fran@,{c}ois Pinard, I made
21772 the macros not interrupt each others' messages.  (That feature revealed
21773 some performance bottlenecks in @acronym{GNU} M4, which he hastily
21774 corrected!)  I reorganized the documentation around problems people want
21775 to solve.  And I began a test suite, because experience had shown that
21776 Autoconf has a pronounced tendency to regress when we change it.
21778 Again, several alpha testers gave invaluable feedback, especially
21779 Fran@,{c}ois Pinard, Jim Meyering, Karl Berry, Rob Savoye, Ken Raeburn,
21780 and Mark Eichin.
21782 Finally, version 2.0 was ready.  And there was much rejoicing.  (And I
21783 have free time again.  I think.  Yeah, right.)
21786 @c ========================================================== Appendices
21789 @node GNU Free Documentation License
21790 @appendix GNU Free Documentation License
21792 @include fdl.texi
21794 @node Indices
21795 @appendix Indices
21797 @menu
21798 * Environment Variable Index::  Index of environment variables used
21799 * Output Variable Index::       Index of variables set in output files
21800 * Preprocessor Symbol Index::   Index of C preprocessor symbols defined
21801 * Autoconf Macro Index::        Index of Autoconf macros
21802 * M4 Macro Index::              Index of M4, M4sugar, and M4sh macros
21803 * Autotest Macro Index::        Index of Autotest macros
21804 * Program & Function Index::    Index of those with portability problems
21805 * Concept Index::               General index
21806 @end menu
21808 @node Environment Variable Index
21809 @appendixsec Environment Variable Index
21811 This is an alphabetical list of the environment variables that Autoconf
21812 checks.
21814 @printindex ev
21816 @node Output Variable Index
21817 @appendixsec Output Variable Index
21819 This is an alphabetical list of the variables that Autoconf can
21820 substitute into files that it creates, typically one or more
21821 makefiles.  @xref{Setting Output Variables}, for more information
21822 on how this is done.
21824 @printindex ov
21826 @node Preprocessor Symbol Index
21827 @appendixsec Preprocessor Symbol Index
21829 This is an alphabetical list of the C preprocessor symbols that the
21830 Autoconf macros define.  To work with Autoconf, C source code needs to
21831 use these names in @code{#if} or @code{#ifdef} directives.
21833 @printindex cv
21835 @node Autoconf Macro Index
21836 @appendixsec Autoconf Macro Index
21838 This is an alphabetical list of the Autoconf macros.
21839 @ifset shortindexflag
21840 To make the list easier to use, the macros are listed without their
21841 preceding @samp{AC_}.
21842 @end ifset
21844 @printindex AC
21846 @node M4 Macro Index
21847 @appendixsec M4 Macro Index
21849 This is an alphabetical list of the M4, M4sugar, and M4sh macros.
21850 @ifset shortindexflag
21851 To make the list easier to use, the macros are listed without their
21852 preceding @samp{m4_} or @samp{AS_}.
21853 @end ifset
21855 @printindex MS
21857 @node Autotest Macro Index
21858 @appendixsec Autotest Macro Index
21860 This is an alphabetical list of the Autotest macros.
21861 @ifset shortindexflag
21862 To make the list easier to use, the macros are listed without their
21863 preceding @samp{AT_}.
21864 @end ifset
21866 @printindex AT
21868 @node Program & Function Index
21869 @appendixsec Program and Function Index
21871 This is an alphabetical list of the programs and functions whose
21872 portability is discussed in this document.
21874 @printindex pr
21876 @node Concept Index
21877 @appendixsec Concept Index
21879 This is an alphabetical list of the files, tools, and concepts
21880 introduced in this document.
21882 @printindex cp
21884 @bye
21886 @c  LocalWords:  texinfo setfilename autoconf texi settitle setchapternewpage
21887 @c  LocalWords:  setcontentsaftertitlepage finalout ARG ovar varname dvar acx
21888 @c  LocalWords:  makeinfo dvi defcodeindex ev ov CPP cv Autotest mv defindex fn
21889 @c  LocalWords:  shortindexflag iftex ifset acindex ACindex ifclear ahindex fu
21890 @c  LocalWords:  asindex MSindex atindex ATindex auindex hdrindex prindex FIXME
21891 @c  LocalWords:  msindex alloca fnindex Aaarg indices FSF's dircategory ifnames
21892 @c  LocalWords:  direntry autoscan autoreconf autoheader autoupdate config FDs
21893 @c  LocalWords:  testsuite titlepage Elliston Demaille vskip filll ifnottex hmm
21894 @c  LocalWords:  insertcopying Autoconf's detailmenu Automake Libtool Posix ois
21895 @c  LocalWords:  Systemology Checkpointing Changequote INTERCAL changequote dfn
21896 @c  LocalWords:  Quadrigraphs builtins Shellology acconfig Bugward LIBOBJ Imake
21897 @c  LocalWords:  LIBOBJS IFELSE cindex flushright Pinard Metaconfig uref Simons
21898 @c  LocalWords:  distclean uninstall noindent versioning Tromey dir
21899 @c  LocalWords:  SAMS samp aclocal acsite underquoted emph itemx prepend SUBST
21900 @c  LocalWords:  evindex automake Gettext autopoint gettext symlink libtoolize
21901 @c  LocalWords:  defmac INIT tarname ovindex cvindex BUGREPORT PREREQ asis PROG
21902 @c  LocalWords:  SRCDIR srcdir globbing afterwards cmds foos fooo foooo init cd
21903 @c  LocalWords:  builddir timestamp src Imakefile chmod defvar CFLAGS CPPFLAGS
21904 @c  LocalWords:  CXXFLAGS DEFS DHAVE defvarx FCFLAGS FFLAGS LDFLAGS bindir GCC
21905 @c  LocalWords:  datadir datarootdir docdir dvidir htmldir libdir ifnothtml kbd
21906 @c  LocalWords:  includedir infodir libexecdir localedir localstatedir mandir
21907 @c  LocalWords:  oldincludedir pdfdir PDF psdir PostScript sbindir sysconfdir
21908 @c  LocalWords:  sharedstatedir DDATADIR sed tmp pkgdatadir VPATH conf unistd
21909 @c  LocalWords:  undef endif builtin FUNCS ifndef STACKSEG getb GETB YMP fubar
21910 @c  LocalWords:  PRE dest SUBDIRS subdirs fi struct STDC stdlib stddef INTTYPES
21911 @c  LocalWords:  inttypes STDINT stdint AWK AIX Solaris NeXT env EGREP FGREP yy
21912 @c  LocalWords:  LEXLIB YYTEXT lfl nonportable Automake's LN RANLIB byacc INETD
21913 @c  LocalWords:  inetd prog PROGS progs ranlib lmp lXt lX nsl gethostbyname UX
21914 @c  LocalWords:  NextStep isinf isnan glibc IRIX sunmath lm lsunmath pre sizeof
21915 @c  LocalWords:  ld inline malloc putenv setenv FreeBSD realloc SunOS MinGW
21916 @c  LocalWords:  snprintf vsnprintf sprintf vsprintf sscanf gcc strerror ifdef
21917 @c  LocalWords:  strnlen sysconf PAGESIZE unsetenv va fallback memcpy dst FUNC
21918 @c  LocalWords:  PowerPC GNUC libPW pragma Olibcalls CHOWN chown CLOSEDIR VFORK
21919 @c  LocalWords:  closedir FNMATCH fnmatch vfork FSEEKO LARGEFILE fseeko SVR sc
21920 @c  LocalWords:  largefile GETGROUPS getgroups GETLOADAVG DGUX UMAX NLIST KMEM
21921 @c  LocalWords:  SETGID getloadavg nlist GETMNTENT irix
21922 @c  LocalWords:  getmntent UnixWare GETPGRP getpgid getpgrp Posix's pid LSTAT
21923 @c  LocalWords:  lstat rpl MEMCMP memcmp OpenStep MBRTOWC mbrtowc MKTIME mktime
21924 @c  LocalWords:  localtime MMAP mmap OBSTACK obstack obstacks ARGTYPES timeval
21925 @c  LocalWords:  SETPGRP setpgrp defmacx Hurd SETVBUF setvbuf STRCOLL strcoll
21926 @c  LocalWords:  STRTOD strtod DECL STRFTIME strftime SCO UTIME utime VPRINTF
21927 @c  LocalWords:  DOPRNT vprintf doprnt sp unfixable LIBSOURCE LIBSOURCES Eggert
21928 @c  LocalWords:  linux netinet ia Tru XFree DIRENT NDIR dirent ndir multitable
21929 @c  LocalWords:  NAMLEN strlen namlen MKDEV SYSMACROS makedev RESOLV resolv DNS
21930 @c  LocalWords:  inet structs NAMESER arpa NETDB netdb UTekV UTS GCC's kB
21931 @c  LocalWords:  STDBOOL BOOL stdbool conformant cplusplus bool Bool stdarg tm
21932 @c  LocalWords:  ctype strchr strrchr rindex bcopy memmove memchr WEXITSTATUS
21933 @c  LocalWords:  WIFEXITED TIOCGWINSZ GWINSZ termios preprocess preprocessable
21934 @c  LocalWords:  DECLS strdup calloc BLKSIZE blksize RDEV rdev TZNAME tzname pw
21935 @c  LocalWords:  passwd gecos pwd MBSTATE mbstate wchar RETSIGTYPE hup UID uid
21936 @c  LocalWords:  gid ptrdiff uintmax EXEEXT OBJEXT Ae conftest AXP str
21937 @c  LocalWords:  ALIGNOF WERROR Werror cpp HP's WorkShop egcs un fied stdc CXX
21938 @c  LocalWords:  varargs BIGENDIAN Endianness SPARC endianness grep'ed CONST FC
21939 @c  LocalWords:  const STRINGIZE stringizing PARAMS unprotoize protos KCC cxx
21940 @c  LocalWords:  xlC aCC CXXCPP FREEFORM xlf FLIBS FCLIBS ish SRCEXT XTRA LFS
21941 @c  LocalWords:  ISC lcposix MINIX Minix conditionalized inlines hw dD confdefs
21942 @c  LocalWords:  fputs stdout PREPROC ar UFS HFS QNX realtime fstype STATVFS se
21943 @c  LocalWords:  statvfs STATFS statfs func machfile hdr lelf raboof DEFUN GTK
21944 @c  LocalWords:  GTKMM Grmph ified ine defn baz EOF qar Ahhh changecom algol io
21945 @c  LocalWords:  changeword quadrigraphs quadrigraph dnl SGI atoi overquoting
21946 @c  LocalWords:  Aas Wcross sep args namespace undefine bpatsubst popdef dquote
21947 @c  LocalWords:  bregexp Overquote overquotation meisch maisch meische maische
21948 @c  LocalWords:  miscian DIRNAME dirname MKDIR CATFILE XMKMF TRAVOLTA celsius
21949 @c  LocalWords:  EMX emxos Emacsen Korn DYNIX subshell posix Ksh ksh Pdksh Zsh
21950 @c  LocalWords:  pdksh zsh Allbery Lipe Kubota UWS zorglub stderr eval esac lfn
21951 @c  LocalWords:  drivespec Posixy DJGPP doschk prettybird LPT pfew Zsh's yu yaa
21952 @c  LocalWords:  yM uM aM firebird IP subdir misparses ok Unpatched abc bc zA
21953 @c  LocalWords:  CDPATH DUALCASE LINENO prepass Subshells lineno NULLCMD cmp wc
21954 @c  LocalWords:  MAILPATH scanset arg NetBSD Almquist printf expr cp
21955 @c  LocalWords:  Oliva awk Aaaaarg cmd regex xfoo GNV OpenVMS VM
21956 @c  LocalWords:  sparc Proulx nbar nfoo maxdepth acdilrtu TWG mc
21957 @c  LocalWords:  mkdir exe uname OpenBSD Fileutils mktemp umask TMPDIR guid os
21958 @c  LocalWords:  fooXXXXXX Unicos utimes hpux hppa unescaped
21959 @c  LocalWords:  pmake DOS's gmake ifoo DESTDIR autoconfiscated pc coff mips gg
21960 @c  LocalWords:  dec ultrix cpu wildcards rpcc rdtsc powerpc readline
21961 @c  LocalWords:  withval vxworks gless localcache usr LOFF loff CYGWIN Cygwin
21962 @c  LocalWords:  cygwin SIGLIST siglist SYSNDIR SYSDIR ptx lseq rusage elif MSC
21963 @c  LocalWords:  lfoo POUNDBANG lsun NIS getpwnam SYSCALLS RSH INTL lintl aix
21964 @c  LocalWords:  intl lx ldir syslog bsd EPI toolchain netbsd objext de KNR nn
21965 @c  LocalWords:  fication LTLIBOBJS Wdiff TESTDIR atconfig atlocal akim XFAIL
21966 @c  LocalWords:  ChangeLog prepended errexit smallexample TESTSUITEFLAGS GPL er
21967 @c  LocalWords:  installcheck autotest indir Pixley Bothner Eichin Kerberos adl
21968 @c  LocalWords:  DISTCLEANFILES preprocessor's fileutils Stallman Murphey Stenn
21969 @c  LocalWords:  Manfredi Autoconfig TCL FSP david zuhn Blandy MACRODIR Raeburn
21970 @c  LocalWords:  autoconfiscate Savoye Haertel Avera Meyering fdl appendixsec
21971 @c  LocalWords:  printindex american LIBOBJDIR LibdirTest ERLCFLAGS OBJCFLAGS
21972 @c  LocalWords:  VER Gnulib online xyes strcpy TYPEOF typeof OBJC objcc objc ln
21973 @c  LocalWords:  GOBJC OTP ERLC erl valloc decr dumpdef errprint incr
21974 @c  LocalWords:  esyscmd len maketemp pushdef substr syscmd sysval translit txt
21975 @c  LocalWords:  sinclude foreach myvar tolower toupper uniq BASENAME STDIN
21976 @c  LocalWords:  Dynix descrips basename aname cname macroexpands xno xcheck
21977 @c  LocalWords:  LIBREADLINE lreadline lncurses libreadline
21979 @c Local Variables:
21980 @c fill-column: 72
21981 @c ispell-local-dictionary: "american"
21982 @c indent-tabs-mode: nil
21983 @c whitespace-check-buffer-indent: nil
21984 @c End: